compiler: record final type for numeric expressions
[official-gcc.git] / gcc / go / gofrontend / gogo.cc
blob5654e30849d3bde6b321d16437d5df91e88465a1
1 // gogo.cc -- Go frontend parsed representation.
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.
7 #include "go-system.h"
9 #include <fstream>
11 #include "filenames.h"
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"
28 // Class Gogo.
30 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
31 : backend_(backend),
32 linemap_(linemap),
33 package_(NULL),
34 functions_(),
35 globals_(new Bindings(NULL)),
36 file_block_names_(),
37 imports_(),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
40 packages_(),
41 init_functions_(),
42 var_deps_(),
43 need_init_fn_(false),
44 init_fn_name_(),
45 imported_init_fns_(),
46 pkgpath_(),
47 pkgpath_symbol_(),
48 prefix_(),
49 pkgpath_set_(false),
50 pkgpath_from_option_(false),
51 prefix_from_option_(false),
52 relative_import_path_(),
53 c_header_(),
54 check_divide_by_zero_(true),
55 check_divide_overflow_(true),
56 compiling_runtime_(false),
57 debug_escape_level_(0),
58 nil_check_size_threshold_(4096),
59 verify_types_(),
60 interface_types_(),
61 specific_type_functions_(),
62 specific_type_functions_are_written_(false),
63 named_types_are_converted_(false),
64 analysis_sets_(),
65 gc_roots_(),
66 imported_inlinable_functions_(),
67 imported_inline_functions_()
69 const Location loc = Linemap::predeclared_location();
71 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
72 RUNTIME_TYPE_KIND_UINT8);
73 this->add_named_type(uint8_type);
74 this->add_named_type(Type::make_integer_type("uint16", true, 16,
75 RUNTIME_TYPE_KIND_UINT16));
76 this->add_named_type(Type::make_integer_type("uint32", true, 32,
77 RUNTIME_TYPE_KIND_UINT32));
78 this->add_named_type(Type::make_integer_type("uint64", true, 64,
79 RUNTIME_TYPE_KIND_UINT64));
81 this->add_named_type(Type::make_integer_type("int8", false, 8,
82 RUNTIME_TYPE_KIND_INT8));
83 this->add_named_type(Type::make_integer_type("int16", false, 16,
84 RUNTIME_TYPE_KIND_INT16));
85 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
86 RUNTIME_TYPE_KIND_INT32);
87 this->add_named_type(int32_type);
88 this->add_named_type(Type::make_integer_type("int64", false, 64,
89 RUNTIME_TYPE_KIND_INT64));
91 this->add_named_type(Type::make_float_type("float32", 32,
92 RUNTIME_TYPE_KIND_FLOAT32));
93 this->add_named_type(Type::make_float_type("float64", 64,
94 RUNTIME_TYPE_KIND_FLOAT64));
96 this->add_named_type(Type::make_complex_type("complex64", 64,
97 RUNTIME_TYPE_KIND_COMPLEX64));
98 this->add_named_type(Type::make_complex_type("complex128", 128,
99 RUNTIME_TYPE_KIND_COMPLEX128));
101 int int_type_size = pointer_size;
102 if (int_type_size < 32)
103 int_type_size = 32;
104 this->add_named_type(Type::make_integer_type("uint", true,
105 int_type_size,
106 RUNTIME_TYPE_KIND_UINT));
107 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
108 RUNTIME_TYPE_KIND_INT);
109 this->add_named_type(int_type);
111 this->add_named_type(Type::make_integer_type("uintptr", true,
112 pointer_size,
113 RUNTIME_TYPE_KIND_UINTPTR));
115 // "byte" is an alias for "uint8".
116 uint8_type->integer_type()->set_is_byte();
117 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
118 loc);
119 byte_type->type_value()->set_is_alias();
120 this->add_named_type(byte_type->type_value());
122 // "rune" is an alias for "int32".
123 int32_type->integer_type()->set_is_rune();
124 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
125 loc);
126 rune_type->type_value()->set_is_alias();
127 this->add_named_type(rune_type->type_value());
129 this->add_named_type(Type::make_named_bool_type());
131 this->add_named_type(Type::make_named_string_type());
133 // "error" is interface { Error() string }.
135 Typed_identifier_list *methods = new Typed_identifier_list;
136 Typed_identifier_list *results = new Typed_identifier_list;
137 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
138 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
139 methods->push_back(Typed_identifier("Error", method_type, loc));
140 Interface_type *error_iface = Type::make_interface_type(methods, loc);
141 error_iface->finalize_methods();
142 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
143 this->add_named_type(error_type);
146 this->globals_->add_constant(Typed_identifier("true",
147 Type::make_boolean_type(),
148 loc),
149 NULL,
150 Expression::make_boolean(true, loc),
152 this->globals_->add_constant(Typed_identifier("false",
153 Type::make_boolean_type(),
154 loc),
155 NULL,
156 Expression::make_boolean(false, loc),
159 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
160 loc),
161 NULL,
162 Expression::make_nil(loc),
165 Type* abstract_int_type = Type::make_abstract_integer_type();
166 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
167 loc),
168 NULL,
169 Expression::make_iota(),
172 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
173 new_type->set_is_varargs();
174 new_type->set_is_builtin();
175 this->globals_->add_function_declaration("new", NULL, new_type, loc);
177 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
178 make_type->set_is_varargs();
179 make_type->set_is_builtin();
180 this->globals_->add_function_declaration("make", NULL, make_type, loc);
182 Typed_identifier_list* len_result = new Typed_identifier_list();
183 len_result->push_back(Typed_identifier("", int_type, loc));
184 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
185 loc);
186 len_type->set_is_builtin();
187 this->globals_->add_function_declaration("len", NULL, len_type, loc);
189 Typed_identifier_list* cap_result = new Typed_identifier_list();
190 cap_result->push_back(Typed_identifier("", int_type, loc));
191 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
192 loc);
193 cap_type->set_is_builtin();
194 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
196 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
197 print_type->set_is_varargs();
198 print_type->set_is_builtin();
199 this->globals_->add_function_declaration("print", NULL, print_type, loc);
201 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
202 print_type->set_is_varargs();
203 print_type->set_is_builtin();
204 this->globals_->add_function_declaration("println", NULL, print_type, loc);
206 Type *empty = Type::make_empty_interface_type(loc);
207 Typed_identifier_list* panic_parms = new Typed_identifier_list();
208 panic_parms->push_back(Typed_identifier("e", empty, loc));
209 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
210 NULL, loc);
211 panic_type->set_is_builtin();
212 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
214 Typed_identifier_list* recover_result = new Typed_identifier_list();
215 recover_result->push_back(Typed_identifier("", empty, loc));
216 Function_type* recover_type = Type::make_function_type(NULL, NULL,
217 recover_result,
218 loc);
219 recover_type->set_is_builtin();
220 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
222 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
223 close_type->set_is_varargs();
224 close_type->set_is_builtin();
225 this->globals_->add_function_declaration("close", NULL, close_type, loc);
227 Typed_identifier_list* copy_result = new Typed_identifier_list();
228 copy_result->push_back(Typed_identifier("", int_type, loc));
229 Function_type* copy_type = Type::make_function_type(NULL, NULL,
230 copy_result, loc);
231 copy_type->set_is_varargs();
232 copy_type->set_is_builtin();
233 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
235 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
236 append_type->set_is_varargs();
237 append_type->set_is_builtin();
238 this->globals_->add_function_declaration("append", NULL, append_type, loc);
240 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
241 complex_type->set_is_varargs();
242 complex_type->set_is_builtin();
243 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
245 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
246 real_type->set_is_varargs();
247 real_type->set_is_builtin();
248 this->globals_->add_function_declaration("real", NULL, real_type, loc);
250 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
251 imag_type->set_is_varargs();
252 imag_type->set_is_builtin();
253 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
255 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
256 delete_type->set_is_varargs();
257 delete_type->set_is_builtin();
258 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
261 std::string
262 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
264 go_assert(!pkgpath.empty());
265 return go_encode_id(pkgpath);
268 // Get the package path to use for type reflection data. This should
269 // ideally be unique across the entire link.
271 const std::string&
272 Gogo::pkgpath() const
274 go_assert(this->pkgpath_set_);
275 return this->pkgpath_;
278 // Set the package path from the -fgo-pkgpath command line option.
280 void
281 Gogo::set_pkgpath(const std::string& arg)
283 go_assert(!this->pkgpath_set_);
284 this->pkgpath_ = arg;
285 this->pkgpath_set_ = true;
286 this->pkgpath_from_option_ = true;
289 // Get the package path to use for symbol names.
291 const std::string&
292 Gogo::pkgpath_symbol() const
294 go_assert(this->pkgpath_set_);
295 return this->pkgpath_symbol_;
298 // Set the unique prefix to use to determine the package path, from
299 // the -fgo-prefix command line option.
301 void
302 Gogo::set_prefix(const std::string& arg)
304 go_assert(!this->prefix_from_option_);
305 this->prefix_ = arg;
306 this->prefix_from_option_ = true;
309 // Given a name which may or may not have been hidden, append the
310 // appropriate version of the name to the result string. Take care
311 // to avoid creating a sequence that will be rejected by go_encode_id
312 // (avoid ..u, ..U, ..z).
313 void
314 Gogo::append_possibly_hidden_name(std::string *result, const std::string& name)
316 // FIXME: This adds in pkgpath twice for hidden symbols, which is
317 // less than ideal.
318 if (!Gogo::is_hidden_name(name))
319 (*result) += name;
320 else
322 std::string n = ".";
323 std::string pkgpath = Gogo::hidden_name_pkgpath(name);
324 char lastR = result->at(result->length() - 1);
325 char firstP = pkgpath.at(0);
326 if (lastR == '.' && (firstP == 'u' || firstP == 'U' || firstP == 'z'))
327 n = "_.";
328 n.append(pkgpath);
329 n.append(1, '.');
330 n.append(Gogo::unpack_hidden_name(name));
331 (*result) += n;
335 // Munge name for use in an error message.
337 std::string
338 Gogo::message_name(const std::string& name)
340 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
343 // Get the package name.
345 const std::string&
346 Gogo::package_name() const
348 go_assert(this->package_ != NULL);
349 return this->package_->package_name();
352 // Set the package name.
354 void
355 Gogo::set_package_name(const std::string& package_name,
356 Location location)
358 if (this->package_ != NULL)
360 if (this->package_->package_name() != package_name)
361 go_error_at(location, "expected package %<%s%>",
362 Gogo::message_name(this->package_->package_name()).c_str());
363 return;
366 // Now that we know the name of the package we are compiling, set
367 // the package path to use for reflect.Type.PkgPath and global
368 // symbol names.
369 if (this->pkgpath_set_)
370 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
371 else
373 if (!this->prefix_from_option_ && package_name == "main")
375 this->pkgpath_ = package_name;
376 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name);
378 else
380 if (!this->prefix_from_option_)
381 this->prefix_ = "go";
382 this->pkgpath_ = this->prefix_ + '.' + package_name;
383 this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.'
384 + Gogo::pkgpath_for_symbol(package_name));
386 this->pkgpath_set_ = true;
389 this->package_ = this->register_package(this->pkgpath_,
390 this->pkgpath_symbol_, location);
391 this->package_->set_package_name(package_name, location);
393 if (this->is_main_package())
395 // Declare "main" as a function which takes no parameters and
396 // returns no value.
397 Location uloc = Linemap::unknown_location();
398 this->declare_function(Gogo::pack_hidden_name("main", false),
399 Type::make_function_type (NULL, NULL, NULL, uloc),
400 uloc);
404 // Return whether this is the "main" package. This is not true if
405 // -fgo-pkgpath or -fgo-prefix was used.
407 bool
408 Gogo::is_main_package() const
410 return (this->package_name() == "main"
411 && !this->pkgpath_from_option_
412 && !this->prefix_from_option_);
415 // Import a package.
417 void
418 Gogo::import_package(const std::string& filename,
419 const std::string& local_name,
420 bool is_local_name_exported,
421 bool must_exist,
422 Location location)
424 if (filename.empty())
426 go_error_at(location, "import path is empty");
427 return;
430 const char *pf = filename.data();
431 const char *pend = pf + filename.length();
432 while (pf < pend)
434 unsigned int c;
435 int adv = Lex::fetch_char(pf, &c);
436 if (adv == 0)
438 go_error_at(location, "import path contains invalid UTF-8 sequence");
439 return;
441 if (c == '\0')
443 go_error_at(location, "import path contains NUL");
444 return;
446 if (c < 0x20 || c == 0x7f)
448 go_error_at(location, "import path contains control character");
449 return;
451 if (c == '\\')
453 go_error_at(location, "import path contains backslash; use slash");
454 return;
456 if (Lex::is_unicode_space(c))
458 go_error_at(location, "import path contains space character");
459 return;
461 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
463 go_error_at(location,
464 "import path contains invalid character '%c'", c);
465 return;
467 pf += adv;
470 if (IS_ABSOLUTE_PATH(filename.c_str()))
472 go_error_at(location, "import path cannot be absolute path");
473 return;
476 if (local_name == "init")
477 go_error_at(location, "cannot import package as init");
479 if (filename == "unsafe")
481 this->import_unsafe(local_name, is_local_name_exported, location);
482 this->current_file_imported_unsafe_ = true;
483 return;
486 Imports::const_iterator p = this->imports_.find(filename);
487 if (p != this->imports_.end())
489 Package* package = p->second;
490 package->set_location(location);
491 std::string ln = local_name;
492 bool is_ln_exported = is_local_name_exported;
493 if (ln.empty())
495 ln = package->package_name();
496 go_assert(!ln.empty());
497 is_ln_exported = Lex::is_exported_name(ln);
499 if (ln == "_")
501 else if (ln == ".")
503 Bindings* bindings = package->bindings();
504 for (Bindings::const_declarations_iterator p =
505 bindings->begin_declarations();
506 p != bindings->end_declarations();
507 ++p)
508 this->add_dot_import_object(p->second);
509 std::string dot_alias = "." + package->package_name();
510 package->add_alias(dot_alias, location);
512 else
514 package->add_alias(ln, location);
515 ln = this->pack_hidden_name(ln, is_ln_exported);
516 this->package_->bindings()->add_package(ln, package);
518 return;
521 Import::Stream* stream = Import::open_package(filename, location,
522 this->relative_import_path_);
523 if (stream == NULL)
525 if (must_exist)
526 go_error_at(location, "import file %qs not found", filename.c_str());
527 return;
530 Import* imp = new Import(stream, location);
531 imp->register_builtin_types(this);
532 Package* package = imp->import(this, local_name, is_local_name_exported);
533 if (package != NULL)
535 if (package->pkgpath() == this->pkgpath())
536 go_error_at(location,
537 ("imported package uses same package path as package "
538 "being compiled (see -fgo-pkgpath option)"));
540 this->imports_.insert(std::make_pair(filename, package));
543 imp->clear_stream();
544 delete stream;
546 // FIXME: we never delete imp; we may need it for inlinable functions.
549 Import_init *
550 Gogo::lookup_init(const std::string& init_name)
552 Import_init tmp("", init_name, -1);
553 Import_init_set::iterator it = this->imported_init_fns_.find(&tmp);
554 return (it != this->imported_init_fns_.end()) ? *it : NULL;
557 // Add an import control function for an imported package to the list.
559 void
560 Gogo::add_import_init_fn(const std::string& package_name,
561 const std::string& init_name, int prio)
563 for (Import_init_set::iterator p =
564 this->imported_init_fns_.begin();
565 p != this->imported_init_fns_.end();
566 ++p)
568 Import_init *ii = (*p);
569 if (ii->init_name() == init_name)
571 // If a test of package P1, built as part of package P1,
572 // imports package P2, and P2 imports P1 (perhaps
573 // indirectly), then we will see the same import name with
574 // different import priorities. That is OK, so don't give
575 // an error about it.
576 if (ii->package_name() != package_name)
578 go_error_at(Linemap::unknown_location(),
579 "duplicate package initialization name %qs",
580 Gogo::message_name(init_name).c_str());
581 go_inform(Linemap::unknown_location(), "used by package %qs",
582 Gogo::message_name(ii->package_name()).c_str());
583 go_inform(Linemap::unknown_location(), " and by package %qs",
584 Gogo::message_name(package_name).c_str());
586 ii->set_priority(prio);
587 return;
591 Import_init* nii = new Import_init(package_name, init_name, prio);
592 this->imported_init_fns_.insert(nii);
595 // Return whether we are at the global binding level.
597 bool
598 Gogo::in_global_scope() const
600 return this->functions_.empty();
603 // Return the current binding contour.
605 Bindings*
606 Gogo::current_bindings()
608 if (!this->functions_.empty())
609 return this->functions_.back().blocks.back()->bindings();
610 else if (this->package_ != NULL)
611 return this->package_->bindings();
612 else
613 return this->globals_;
616 const Bindings*
617 Gogo::current_bindings() const
619 if (!this->functions_.empty())
620 return this->functions_.back().blocks.back()->bindings();
621 else if (this->package_ != NULL)
622 return this->package_->bindings();
623 else
624 return this->globals_;
627 void
628 Gogo::update_init_priority(Import_init* ii,
629 std::set<const Import_init *>* visited)
631 visited->insert(ii);
632 int succ_prior = -1;
634 for (std::set<std::string>::const_iterator pci =
635 ii->precursors().begin();
636 pci != ii->precursors().end();
637 ++pci)
639 Import_init* succ = this->lookup_init(*pci);
640 if (visited->find(succ) == visited->end())
641 update_init_priority(succ, visited);
642 succ_prior = std::max(succ_prior, succ->priority());
644 if (ii->priority() <= succ_prior)
645 ii->set_priority(succ_prior + 1);
648 void
649 Gogo::recompute_init_priorities()
651 std::set<Import_init *> nonroots;
653 for (Import_init_set::const_iterator p =
654 this->imported_init_fns_.begin();
655 p != this->imported_init_fns_.end();
656 ++p)
658 const Import_init *ii = *p;
659 for (std::set<std::string>::const_iterator pci =
660 ii->precursors().begin();
661 pci != ii->precursors().end();
662 ++pci)
664 Import_init* ii = this->lookup_init(*pci);
665 nonroots.insert(ii);
669 // Recursively update priorities starting at roots.
670 std::set<const Import_init*> visited;
671 for (Import_init_set::iterator p =
672 this->imported_init_fns_.begin();
673 p != this->imported_init_fns_.end();
674 ++p)
676 Import_init* ii = *p;
677 if (nonroots.find(ii) != nonroots.end())
678 continue;
679 update_init_priority(ii, &visited);
683 // Add statements to INIT_STMTS which run the initialization
684 // functions for imported packages. This is only used for the "main"
685 // package.
687 void
688 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction)
690 go_assert(this->is_main_package());
692 if (this->imported_init_fns_.empty())
693 return;
695 Location unknown_loc = Linemap::unknown_location();
696 Function_type* func_type =
697 Type::make_function_type(NULL, NULL, NULL, unknown_loc);
698 Btype* fntype = func_type->get_backend_fntype(this);
700 // Recompute init priorities based on a walk of the init graph.
701 recompute_init_priorities();
703 // We must call them in increasing priority order.
704 std::vector<const Import_init*> v;
705 for (Import_init_set::const_iterator p =
706 this->imported_init_fns_.begin();
707 p != this->imported_init_fns_.end();
708 ++p)
710 if ((*p)->priority() < 0)
711 go_error_at(Linemap::unknown_location(),
712 "internal error: failed to set init priority for %s",
713 (*p)->package_name().c_str());
714 v.push_back(*p);
716 std::sort(v.begin(), v.end(), priority_compare);
718 // We build calls to the init functions, which take no arguments.
719 std::vector<Bexpression*> empty_args;
720 for (std::vector<const Import_init*>::const_iterator p = v.begin();
721 p != v.end();
722 ++p)
724 const Import_init* ii = *p;
725 std::string user_name = ii->package_name() + ".init";
726 const std::string& init_name(ii->init_name());
727 const unsigned int flags =
728 (Backend::function_is_visible
729 | Backend::function_is_declaration
730 | Backend::function_is_inlinable);
731 Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
732 flags, unknown_loc);
733 Bexpression* pfunc_code =
734 this->backend()->function_code_expression(pfunc, unknown_loc);
735 Bexpression* pfunc_call =
736 this->backend()->call_expression(bfunction, pfunc_code, empty_args,
737 NULL, unknown_loc);
738 init_stmts.push_back(this->backend()->expression_statement(bfunction,
739 pfunc_call));
743 // Register global variables with the garbage collector. We need to
744 // register all variables which can hold a pointer value. They become
745 // roots during the mark phase. We build a struct that is easy to
746 // hook into a list of roots.
748 // type gcRoot struct {
749 // decl unsafe.Pointer // Pointer to variable.
750 // size uintptr // Total size of variable.
751 // ptrdata uintptr // Length of variable's gcdata.
752 // gcdata *byte // Pointer mask.
753 // }
755 // type gcRootList struct {
756 // next *gcRootList
757 // count int
758 // roots [...]gcRoot
759 // }
761 // The last entry in the roots array has a NULL decl field.
763 void
764 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
765 std::vector<Bstatement*>& init_stmts,
766 Bfunction* init_bfn)
768 if (var_gc.empty() && this->gc_roots_.empty())
769 return;
771 Type* pvt = Type::make_pointer_type(Type::make_void_type());
772 Type* uintptr_type = Type::lookup_integer_type("uintptr");
773 Type* byte_type = this->lookup_global("byte")->type_value();
774 Type* pointer_byte_type = Type::make_pointer_type(byte_type);
775 Struct_type* root_type =
776 Type::make_builtin_struct_type(4,
777 "decl", pvt,
778 "size", uintptr_type,
779 "ptrdata", uintptr_type,
780 "gcdata", pointer_byte_type);
782 Location builtin_loc = Linemap::predeclared_location();
783 unsigned long roots_len = var_gc.size() + this->gc_roots_.size();
784 Expression* length = Expression::make_integer_ul(roots_len, NULL,
785 builtin_loc);
786 Array_type* root_array_type = Type::make_array_type(root_type, length);
787 root_array_type->set_is_array_incomparable();
789 Type* int_type = Type::lookup_integer_type("int");
790 Struct_type* root_list_type =
791 Type::make_builtin_struct_type(3,
792 "next", pvt,
793 "count", int_type,
794 "roots", root_array_type);
796 // Build an initializer for the roots array.
798 Expression_list* roots_init = new Expression_list();
800 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
801 p != var_gc.end();
802 ++p)
804 Expression_list* init = new Expression_list();
806 Location no_loc = (*p)->location();
807 Expression* decl = Expression::make_var_reference(*p, no_loc);
808 Expression* decl_addr =
809 Expression::make_unary(OPERATOR_AND, decl, no_loc);
810 decl_addr->unary_expression()->set_does_not_escape();
811 decl_addr = Expression::make_cast(pvt, decl_addr, no_loc);
812 init->push_back(decl_addr);
814 Expression* size =
815 Expression::make_type_info(decl->type(),
816 Expression::TYPE_INFO_SIZE);
817 init->push_back(size);
819 Expression* ptrdata =
820 Expression::make_type_info(decl->type(),
821 Expression::TYPE_INFO_BACKEND_PTRDATA);
822 init->push_back(ptrdata);
824 Expression* gcdata = Expression::make_ptrmask_symbol(decl->type());
825 init->push_back(gcdata);
827 Expression* root_ctor =
828 Expression::make_struct_composite_literal(root_type, init, no_loc);
829 roots_init->push_back(root_ctor);
832 for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin();
833 p != this->gc_roots_.end();
834 ++p)
836 Expression_list *init = new Expression_list();
838 Expression* expr = *p;
839 Location eloc = expr->location();
840 init->push_back(Expression::make_cast(pvt, expr, eloc));
842 Type* type = expr->type()->points_to();
843 go_assert(type != NULL);
845 Expression* size =
846 Expression::make_type_info(type,
847 Expression::TYPE_INFO_SIZE);
848 init->push_back(size);
850 Expression* ptrdata =
851 Expression::make_type_info(type,
852 Expression::TYPE_INFO_BACKEND_PTRDATA);
853 init->push_back(ptrdata);
855 Expression* gcdata = Expression::make_ptrmask_symbol(type);
856 init->push_back(gcdata);
858 Expression* root_ctor =
859 Expression::make_struct_composite_literal(root_type, init, eloc);
860 roots_init->push_back(root_ctor);
863 // Build a constructor for the struct.
865 Expression_list* root_list_init = new Expression_list();
866 root_list_init->push_back(Expression::make_nil(builtin_loc));
867 root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type,
868 builtin_loc));
870 Expression* roots_ctor =
871 Expression::make_array_composite_literal(root_array_type, roots_init,
872 builtin_loc);
873 root_list_init->push_back(roots_ctor);
875 Expression* root_list_ctor =
876 Expression::make_struct_composite_literal(root_list_type, root_list_init,
877 builtin_loc);
879 Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
880 builtin_loc);
881 root_addr->unary_expression()->set_is_gc_root();
882 Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
883 builtin_loc, 1, root_addr);
885 Translate_context context(this, NULL, NULL, NULL);
886 Bexpression* bcall = register_roots->get_backend(&context);
887 init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall));
890 // Build the decl for the initialization function.
892 Named_object*
893 Gogo::initialization_function_decl()
895 std::string name = this->get_init_fn_name();
896 Location loc = this->package_->location();
898 Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
899 Function* initfn = new Function(fntype, NULL, NULL, loc);
900 return Named_object::make_function(name, NULL, initfn);
903 // Create the magic initialization function. CODE_STMT is the
904 // code that it needs to run.
906 Named_object*
907 Gogo::create_initialization_function(Named_object* initfn,
908 Bstatement* code_stmt)
910 // Make sure that we thought we needed an initialization function,
911 // as otherwise we will not have reported it in the export data.
912 go_assert(this->is_main_package() || this->need_init_fn_);
914 if (initfn == NULL)
915 initfn = this->initialization_function_decl();
917 // Bind the initialization function code to a block.
918 Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
919 Location pkg_loc = this->package_->location();
920 std::vector<Bvariable*> vars;
921 this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
923 if (!this->backend()->function_set_body(fndecl, code_stmt))
925 go_assert(saw_errors());
926 return NULL;
928 return initfn;
931 // Given an expression, collect all the global variables defined in
932 // this package that it references.
934 class Find_vars : public Traverse
936 private:
937 // The list of variables we accumulate.
938 typedef Unordered_set(Named_object*) Vars;
940 // A hash table we use to avoid looping. The index is a
941 // Named_object* or a Temporary_statement*. We only look through
942 // objects defined in this package.
943 typedef Unordered_set(const void*) Seen_objects;
945 public:
946 Find_vars()
947 : Traverse(traverse_expressions),
948 vars_(), seen_objects_()
951 // An iterator through the variables found, after the traversal.
952 typedef Vars::const_iterator const_iterator;
954 const_iterator
955 begin() const
956 { return this->vars_.begin(); }
958 const_iterator
959 end() const
960 { return this->vars_.end(); }
963 expression(Expression**);
965 private:
966 // Accumulated variables.
967 Vars vars_;
968 // Objects we have already seen.
969 Seen_objects seen_objects_;
972 // Collect global variables referenced by EXPR. Look through function
973 // calls and variable initializations.
976 Find_vars::expression(Expression** pexpr)
978 Expression* e = *pexpr;
980 Var_expression* ve = e->var_expression();
981 if (ve != NULL)
983 Named_object* v = ve->named_object();
984 if (!v->is_variable() || v->package() != NULL)
986 // This is a result parameter or a variable defined in a
987 // different package. Either way we don't care about it.
988 return TRAVERSE_CONTINUE;
991 std::pair<Seen_objects::iterator, bool> ins =
992 this->seen_objects_.insert(v);
993 if (!ins.second)
995 // We've seen this variable before.
996 return TRAVERSE_CONTINUE;
999 if (v->var_value()->is_global())
1000 this->vars_.insert(v);
1002 Expression* init = v->var_value()->init();
1003 if (init != NULL)
1005 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1006 return TRAVERSE_EXIT;
1010 // We traverse the code of any function or bound method we see. Note that
1011 // this means that we will traverse the code of a function or bound method
1012 // whose address is taken even if it is not called.
1013 Func_expression* fe = e->func_expression();
1014 Bound_method_expression* bme = e->bound_method_expression();
1015 if (fe != NULL || bme != NULL)
1017 const Named_object* f = fe != NULL ? fe->named_object() : bme->function();
1018 if (f->is_function() && f->package() == NULL)
1020 std::pair<Seen_objects::iterator, bool> ins =
1021 this->seen_objects_.insert(f);
1022 if (ins.second)
1024 // This is the first time we have seen this name.
1025 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
1026 return TRAVERSE_EXIT;
1031 Temporary_reference_expression* tre = e->temporary_reference_expression();
1032 if (tre != NULL)
1034 Temporary_statement* ts = tre->statement();
1035 Expression* init = ts->init();
1036 if (init != NULL)
1038 std::pair<Seen_objects::iterator, bool> ins =
1039 this->seen_objects_.insert(ts);
1040 if (ins.second)
1042 // This is the first time we have seen this temporary
1043 // statement.
1044 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1045 return TRAVERSE_EXIT;
1050 return TRAVERSE_CONTINUE;
1053 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1055 static bool
1056 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1057 Named_object* var)
1059 Find_vars find_vars;
1060 if (expr != NULL)
1061 Expression::traverse(&expr, &find_vars);
1062 if (preinit != NULL)
1063 preinit->traverse(&find_vars);
1064 if (dep != NULL)
1066 Expression* init = dep->var_value()->init();
1067 if (init != NULL)
1068 Expression::traverse(&init, &find_vars);
1069 if (dep->var_value()->has_pre_init())
1070 dep->var_value()->preinit()->traverse(&find_vars);
1073 for (Find_vars::const_iterator p = find_vars.begin();
1074 p != find_vars.end();
1075 ++p)
1077 if (*p == var)
1078 return true;
1080 return false;
1083 // Sort variable initializations. If the initialization expression
1084 // for variable A refers directly or indirectly to the initialization
1085 // expression for variable B, then we must initialize B before A.
1087 class Var_init
1089 public:
1090 Var_init()
1091 : var_(NULL), init_(NULL), refs_(NULL), dep_count_(0)
1094 Var_init(Named_object* var, Bstatement* init)
1095 : var_(var), init_(init), refs_(NULL), dep_count_(0)
1098 // Return the variable.
1099 Named_object*
1100 var() const
1101 { return this->var_; }
1103 // Return the initialization expression.
1104 Bstatement*
1105 init() const
1106 { return this->init_; }
1108 // Add a reference.
1109 void
1110 add_ref(Named_object* var);
1112 // The variables which this variable's initializers refer to.
1113 const std::vector<Named_object*>*
1114 refs()
1115 { return this->refs_; }
1117 // Clear the references, if any.
1118 void
1119 clear_refs();
1121 // Return the number of remaining dependencies.
1122 size_t
1123 dep_count() const
1124 { return this->dep_count_; }
1126 // Increment the number of dependencies.
1127 void
1128 add_dependency()
1129 { ++this->dep_count_; }
1131 // Decrement the number of dependencies.
1132 void
1133 remove_dependency()
1134 { --this->dep_count_; }
1136 private:
1137 // The variable being initialized.
1138 Named_object* var_;
1139 // The backend initialization statement.
1140 Bstatement* init_;
1141 // Variables this refers to.
1142 std::vector<Named_object*>* refs_;
1143 // The number of initializations this is dependent on. A variable
1144 // initialization should not be emitted if any of its dependencies
1145 // have not yet been resolved.
1146 size_t dep_count_;
1149 // Add a reference.
1151 void
1152 Var_init::add_ref(Named_object* var)
1154 if (this->refs_ == NULL)
1155 this->refs_ = new std::vector<Named_object*>;
1156 this->refs_->push_back(var);
1159 // Clear the references, if any.
1161 void
1162 Var_init::clear_refs()
1164 if (this->refs_ != NULL)
1166 delete this->refs_;
1167 this->refs_ = NULL;
1171 // For comparing Var_init keys in a map.
1173 inline bool
1174 operator<(const Var_init& v1, const Var_init& v2)
1175 { return v1.var()->name() < v2.var()->name(); }
1177 typedef std::list<Var_init> Var_inits;
1179 // Sort the variable initializations. The rule we follow is that we
1180 // emit them in the order they appear in the array, except that if the
1181 // initialization expression for a variable V1 depends upon another
1182 // variable V2 then we initialize V1 after V2.
1184 static void
1185 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1187 if (var_inits->empty())
1188 return;
1190 std::map<Named_object*, Var_init*> var_to_init;
1192 // A mapping from a variable initialization to a set of
1193 // variable initializations that depend on it.
1194 typedef std::map<Var_init, std::set<Var_init*> > Init_deps;
1195 Init_deps init_deps;
1196 bool init_loop = false;
1198 // Compute all variable references.
1199 for (Var_inits::iterator pvar = var_inits->begin();
1200 pvar != var_inits->end();
1201 ++pvar)
1203 Named_object* var = pvar->var();
1204 var_to_init[var] = &*pvar;
1206 Find_vars find_vars;
1207 Expression* init = var->var_value()->init();
1208 if (init != NULL)
1209 Expression::traverse(&init, &find_vars);
1210 if (var->var_value()->has_pre_init())
1211 var->var_value()->preinit()->traverse(&find_vars);
1212 Named_object* dep = gogo->var_depends_on(var->var_value());
1213 if (dep != NULL)
1215 Expression* dinit = dep->var_value()->init();
1216 if (dinit != NULL)
1217 Expression::traverse(&dinit, &find_vars);
1218 if (dep->var_value()->has_pre_init())
1219 dep->var_value()->preinit()->traverse(&find_vars);
1221 for (Find_vars::const_iterator p = find_vars.begin();
1222 p != find_vars.end();
1223 ++p)
1224 pvar->add_ref(*p);
1227 // Add dependencies to init_deps, and check for cycles.
1228 for (Var_inits::iterator pvar = var_inits->begin();
1229 pvar != var_inits->end();
1230 ++pvar)
1232 Named_object* var = pvar->var();
1234 const std::vector<Named_object*>* refs = pvar->refs();
1235 if (refs == NULL)
1236 continue;
1237 for (std::vector<Named_object*>::const_iterator pdep = refs->begin();
1238 pdep != refs->end();
1239 ++pdep)
1241 Named_object* dep = *pdep;
1242 if (var == dep)
1244 // This is a reference from a variable to itself, which
1245 // may indicate a loop. We only report an error if
1246 // there is an initializer and there is no dependency.
1247 // When there is no initializer, it means that the
1248 // preinitializer sets the variable, which will appear
1249 // to be a loop here.
1250 if (var->var_value()->init() != NULL
1251 && gogo->var_depends_on(var->var_value()) == NULL)
1252 go_error_at(var->location(),
1253 ("initialization expression for %qs "
1254 "depends upon itself"),
1255 var->message_name().c_str());
1257 continue;
1260 Var_init* dep_init = var_to_init[dep];
1261 if (dep_init == NULL)
1263 // This is a dependency on some variable that doesn't
1264 // have an initializer, so for purposes of
1265 // initialization ordering this is irrelevant.
1266 continue;
1269 init_deps[*dep_init].insert(&(*pvar));
1270 pvar->add_dependency();
1272 // Check for cycles.
1273 const std::vector<Named_object*>* deprefs = dep_init->refs();
1274 if (deprefs == NULL)
1275 continue;
1276 for (std::vector<Named_object*>::const_iterator pdepdep =
1277 deprefs->begin();
1278 pdepdep != deprefs->end();
1279 ++pdepdep)
1281 if (*pdepdep == var)
1283 go_error_at(var->location(),
1284 ("initialization expressions for %qs and "
1285 "%qs depend upon each other"),
1286 var->message_name().c_str(),
1287 dep->message_name().c_str());
1288 go_inform(dep->location(), "%qs defined here",
1289 dep->message_name().c_str());
1290 init_loop = true;
1291 break;
1297 var_to_init.clear();
1298 for (Var_inits::iterator pvar = var_inits->begin();
1299 pvar != var_inits->end();
1300 ++pvar)
1301 pvar->clear_refs();
1303 // If there are no dependencies then the declaration order is sorted.
1304 if (!init_deps.empty() && !init_loop)
1306 // Otherwise, sort variable initializations by emitting all variables with
1307 // no dependencies in declaration order. VAR_INITS is already in
1308 // declaration order.
1309 Var_inits ready;
1310 while (!var_inits->empty())
1312 Var_inits::iterator v1;;
1313 for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1)
1315 if (v1->dep_count() == 0)
1316 break;
1318 go_assert(v1 != var_inits->end());
1320 // V1 either has no dependencies or its dependencies have already
1321 // been emitted, add it to READY next. When V1 is emitted, remove
1322 // a dependency from each V that depends on V1.
1323 ready.splice(ready.end(), *var_inits, v1);
1325 Init_deps::iterator p1 = init_deps.find(*v1);
1326 if (p1 != init_deps.end())
1328 std::set<Var_init*> resolved = p1->second;
1329 for (std::set<Var_init*>::iterator pv = resolved.begin();
1330 pv != resolved.end();
1331 ++pv)
1332 (*pv)->remove_dependency();
1333 init_deps.erase(p1);
1336 var_inits->swap(ready);
1337 go_assert(init_deps.empty());
1341 // Give an error if the initialization expression for VAR depends on
1342 // itself. We only check if INIT is not NULL and there is no
1343 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1344 // which we will interpret as a loop.
1346 void
1347 Gogo::check_self_dep(Named_object* var)
1349 Expression* init = var->var_value()->init();
1350 Block* preinit = var->var_value()->preinit();
1351 Named_object* dep = this->var_depends_on(var->var_value());
1352 if (init != NULL
1353 && dep == NULL
1354 && expression_requires(init, preinit, NULL, var))
1355 go_error_at(var->location(),
1356 "initialization expression for %qs depends upon itself",
1357 var->message_name().c_str());
1360 // Write out the global definitions.
1362 void
1363 Gogo::write_globals()
1365 this->build_interface_method_tables();
1367 Bindings* bindings = this->current_bindings();
1369 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1370 p != bindings->end_declarations();
1371 ++p)
1373 // If any function declarations needed a descriptor, make sure
1374 // we build it.
1375 Named_object* no = p->second;
1376 if (no->is_function_declaration())
1377 no->func_declaration_value()->build_backend_descriptor(this);
1380 // Lists of globally declared types, variables, constants, and functions
1381 // that must be defined.
1382 std::vector<Btype*> type_decls;
1383 std::vector<Bvariable*> var_decls;
1384 std::vector<Bexpression*> const_decls;
1385 std::vector<Bfunction*> func_decls;
1387 // The init function declaration and associated Bfunction, if necessary.
1388 Named_object* init_fndecl = NULL;
1389 Bfunction* init_bfn = NULL;
1391 std::vector<Bstatement*> init_stmts;
1392 std::vector<Bstatement*> var_init_stmts;
1394 if (this->is_main_package())
1396 init_fndecl = this->initialization_function_decl();
1397 init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl);
1398 this->init_imports(init_stmts, init_bfn);
1401 // A list of variable initializations.
1402 Var_inits var_inits;
1404 // A list of variables which need to be registered with the garbage
1405 // collector.
1406 size_t count_definitions = bindings->size_definitions();
1407 std::vector<Named_object*> var_gc;
1408 var_gc.reserve(count_definitions);
1410 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1411 p != bindings->end_definitions();
1412 ++p)
1414 Named_object* no = *p;
1415 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1417 // There is nothing to do for a package.
1418 if (no->is_package())
1419 continue;
1421 // There is nothing to do for an object which was imported from
1422 // a different package into the global scope.
1423 if (no->package() != NULL)
1424 continue;
1426 // Skip blank named functions and constants.
1427 if ((no->is_function() && no->func_value()->is_sink())
1428 || (no->is_const() && no->const_value()->is_sink()))
1429 continue;
1431 // There is nothing useful we can output for constants which
1432 // have ideal or non-integral type.
1433 if (no->is_const())
1435 Type* type = no->const_value()->type();
1436 if (type == NULL)
1437 type = no->const_value()->expr()->type();
1438 if (type->is_abstract() || !type->is_numeric_type())
1439 continue;
1442 if (!no->is_variable())
1443 no->get_backend(this, const_decls, type_decls, func_decls);
1444 else
1446 Variable* var = no->var_value();
1447 Bvariable* bvar = no->get_backend_variable(this, NULL);
1448 var_decls.push_back(bvar);
1450 // Check for a sink variable, which may be used to run an
1451 // initializer purely for its side effects.
1452 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1454 Bstatement* var_init_stmt = NULL;
1455 if (!var->has_pre_init())
1457 // If the backend representation of the variable initializer is
1458 // constant, we can just set the initial value using
1459 // global_var_set_init instead of during the init() function.
1460 // The initializer is constant if it is the zero-value of the
1461 // variable's type or if the initial value is an immutable value
1462 // that is not copied to the heap.
1463 bool is_static_initializer = false;
1464 if (var->init() == NULL)
1465 is_static_initializer = true;
1466 else
1468 Type* var_type = var->type();
1469 Expression* init = var->init();
1470 Expression* init_cast =
1471 Expression::make_cast(var_type, init, var->location());
1472 is_static_initializer = init_cast->is_static_initializer();
1475 // Non-constant variable initializations might need to create
1476 // temporary variables, which will need the initialization
1477 // function as context.
1478 Named_object* var_init_fn;
1479 if (is_static_initializer)
1480 var_init_fn = NULL;
1481 else
1483 if (init_fndecl == NULL)
1485 init_fndecl = this->initialization_function_decl();
1486 Function* func = init_fndecl->func_value();
1487 init_bfn = func->get_or_make_decl(this, init_fndecl);
1489 var_init_fn = init_fndecl;
1491 Bexpression* var_binit = var->get_init(this, var_init_fn);
1493 if (var_binit == NULL)
1495 else if (is_static_initializer)
1497 if (expression_requires(var->init(), NULL,
1498 this->var_depends_on(var), no))
1499 go_error_at(no->location(),
1500 "initialization expression for %qs depends "
1501 "upon itself",
1502 no->message_name().c_str());
1503 this->backend()->global_variable_set_init(bvar, var_binit);
1505 else if (is_sink)
1506 var_init_stmt =
1507 this->backend()->expression_statement(init_bfn, var_binit);
1508 else
1510 Location loc = var->location();
1511 Bexpression* var_expr =
1512 this->backend()->var_expression(bvar, loc);
1513 var_init_stmt =
1514 this->backend()->assignment_statement(init_bfn, var_expr,
1515 var_binit, loc);
1518 else
1520 // We are going to create temporary variables which
1521 // means that we need an fndecl.
1522 if (init_fndecl == NULL)
1523 init_fndecl = this->initialization_function_decl();
1525 Bvariable* var_decl = is_sink ? NULL : bvar;
1526 var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1529 if (var_init_stmt != NULL)
1531 if (var->init() == NULL && !var->has_pre_init())
1532 var_init_stmts.push_back(var_init_stmt);
1533 else
1534 var_inits.push_back(Var_init(no, var_init_stmt));
1536 else if (this->var_depends_on(var) != NULL)
1538 // This variable is initialized from something that is
1539 // not in its init or preinit. This variable needs to
1540 // participate in dependency analysis sorting, in case
1541 // some other variable depends on this one.
1542 Btype* btype = no->var_value()->type()->get_backend(this);
1543 Bexpression* zero = this->backend()->zero_expression(btype);
1544 Bstatement* zero_stmt =
1545 this->backend()->expression_statement(init_bfn, zero);
1546 var_inits.push_back(Var_init(no, zero_stmt));
1549 // Collect a list of all global variables with pointers,
1550 // to register them for the garbage collector.
1551 if (!is_sink && var->type()->has_pointer())
1553 // Avoid putting runtime.gcRoots itself on the list.
1554 if (this->compiling_runtime()
1555 && this->package_name() == "runtime"
1556 && (Gogo::unpack_hidden_name(no->name()) == "gcRoots"
1557 || Gogo::unpack_hidden_name(no->name()) == "gcRootsIndex"))
1559 else
1560 var_gc.push_back(no);
1565 // Output inline functions, which are in different packages.
1566 for (std::vector<Named_object*>::const_iterator p =
1567 this->imported_inline_functions_.begin();
1568 p != this->imported_inline_functions_.end();
1569 ++p)
1570 (*p)->get_backend(this, const_decls, type_decls, func_decls);
1572 // Register global variables with the garbage collector.
1573 this->register_gc_vars(var_gc, init_stmts, init_bfn);
1575 // Simple variable initializations, after all variables are
1576 // registered.
1577 init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1579 // Complete variable initializations, first sorting them into a
1580 // workable order.
1581 if (!var_inits.empty())
1583 sort_var_inits(this, &var_inits);
1584 for (Var_inits::const_iterator p = var_inits.begin();
1585 p != var_inits.end();
1586 ++p)
1587 init_stmts.push_back(p->init());
1590 // After all the variables are initialized, call the init
1591 // functions if there are any. Init functions take no arguments, so
1592 // we pass in EMPTY_ARGS to call them.
1593 std::vector<Bexpression*> empty_args;
1594 for (std::vector<Named_object*>::const_iterator p =
1595 this->init_functions_.begin();
1596 p != this->init_functions_.end();
1597 ++p)
1599 Location func_loc = (*p)->location();
1600 Function* func = (*p)->func_value();
1601 Bfunction* initfn = func->get_or_make_decl(this, *p);
1602 Bexpression* func_code =
1603 this->backend()->function_code_expression(initfn, func_loc);
1604 Bexpression* call = this->backend()->call_expression(init_bfn, func_code,
1605 empty_args,
1606 NULL, func_loc);
1607 Bstatement* ist = this->backend()->expression_statement(init_bfn, call);
1608 init_stmts.push_back(ist);
1611 // Set up a magic function to do all the initialization actions.
1612 // This will be called if this package is imported.
1613 Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1614 if (this->need_init_fn_ || this->is_main_package())
1616 init_fndecl =
1617 this->create_initialization_function(init_fndecl, init_fncode);
1618 if (init_fndecl != NULL)
1619 func_decls.push_back(init_fndecl->func_value()->get_decl());
1622 // We should not have seen any new bindings created during the conversion.
1623 go_assert(count_definitions == this->current_bindings()->size_definitions());
1625 // Define all globally declared values.
1626 if (!saw_errors())
1627 this->backend()->write_global_definitions(type_decls, const_decls,
1628 func_decls, var_decls);
1631 // Return the current block.
1633 Block*
1634 Gogo::current_block()
1636 if (this->functions_.empty())
1637 return NULL;
1638 else
1639 return this->functions_.back().blocks.back();
1642 // Look up a name in the current binding contour. If PFUNCTION is not
1643 // NULL, set it to the function in which the name is defined, or NULL
1644 // if the name is defined in global scope.
1646 Named_object*
1647 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1649 if (pfunction != NULL)
1650 *pfunction = NULL;
1652 if (Gogo::is_sink_name(name))
1653 return Named_object::make_sink();
1655 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1656 p != this->functions_.rend();
1657 ++p)
1659 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1660 if (ret != NULL)
1662 if (pfunction != NULL)
1663 *pfunction = p->function;
1664 return ret;
1668 if (this->package_ != NULL)
1670 Named_object* ret = this->package_->bindings()->lookup(name);
1671 if (ret != NULL)
1673 if (ret->package() != NULL)
1675 std::string dot_alias = "." + ret->package()->package_name();
1676 ret->package()->note_usage(dot_alias);
1678 return ret;
1682 // We do not look in the global namespace. If we did, the global
1683 // namespace would effectively hide names which were defined in
1684 // package scope which we have not yet seen. Instead,
1685 // define_global_names is called after parsing is over to connect
1686 // undefined names at package scope with names defined at global
1687 // scope.
1689 return NULL;
1692 // Look up a name in the current block, without searching enclosing
1693 // blocks.
1695 Named_object*
1696 Gogo::lookup_in_block(const std::string& name) const
1698 go_assert(!this->functions_.empty());
1699 go_assert(!this->functions_.back().blocks.empty());
1700 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1703 // Look up a name in the global namespace.
1705 Named_object*
1706 Gogo::lookup_global(const char* name) const
1708 return this->globals_->lookup(name);
1711 // Add an imported package.
1713 Package*
1714 Gogo::add_imported_package(const std::string& real_name,
1715 const std::string& alias_arg,
1716 bool is_alias_exported,
1717 const std::string& pkgpath,
1718 const std::string& pkgpath_symbol,
1719 Location location,
1720 bool* padd_to_globals)
1722 Package* ret = this->register_package(pkgpath, pkgpath_symbol, location);
1723 ret->set_package_name(real_name, location);
1725 *padd_to_globals = false;
1727 if (alias_arg == "_")
1729 else if (alias_arg == ".")
1731 *padd_to_globals = true;
1732 std::string dot_alias = "." + real_name;
1733 ret->add_alias(dot_alias, location);
1735 else
1737 std::string alias = alias_arg;
1738 if (alias.empty())
1740 alias = real_name;
1741 is_alias_exported = Lex::is_exported_name(alias);
1743 ret->add_alias(alias, location);
1744 alias = this->pack_hidden_name(alias, is_alias_exported);
1745 Named_object* no = this->package_->bindings()->add_package(alias, ret);
1746 if (!no->is_package())
1747 return NULL;
1750 return ret;
1753 // Register a package. This package may or may not be imported. This
1754 // returns the Package structure for the package, creating if it
1755 // necessary. LOCATION is the location of the import statement that
1756 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1757 // for names in the package; it may be the empty string, in which case
1758 // we either get it later or make a guess when we need it.
1760 Package*
1761 Gogo::register_package(const std::string& pkgpath,
1762 const std::string& pkgpath_symbol, Location location)
1764 Package* package = NULL;
1765 std::pair<Packages::iterator, bool> ins =
1766 this->packages_.insert(std::make_pair(pkgpath, package));
1767 if (!ins.second)
1769 // We have seen this package name before.
1770 package = ins.first->second;
1771 go_assert(package != NULL && package->pkgpath() == pkgpath);
1772 if (!pkgpath_symbol.empty())
1773 package->set_pkgpath_symbol(pkgpath_symbol);
1774 if (Linemap::is_unknown_location(package->location()))
1775 package->set_location(location);
1777 else
1779 // First time we have seen this package name.
1780 package = new Package(pkgpath, pkgpath_symbol, location);
1781 go_assert(ins.first->second == NULL);
1782 ins.first->second = package;
1785 return package;
1788 // Return the pkgpath symbol for a package, given the pkgpath.
1790 std::string
1791 Gogo::pkgpath_symbol_for_package(const std::string& pkgpath)
1793 Packages::iterator p = this->packages_.find(pkgpath);
1794 go_assert(p != this->packages_.end());
1795 return p->second->pkgpath_symbol();
1798 // Start compiling a function.
1800 Named_object*
1801 Gogo::start_function(const std::string& name, Function_type* type,
1802 bool add_method_to_type, Location location)
1804 bool at_top_level = this->functions_.empty();
1806 Block* block = new Block(NULL, location);
1808 Named_object* enclosing = (at_top_level
1809 ? NULL
1810 : this->functions_.back().function);
1812 Function* function = new Function(type, enclosing, block, location);
1814 if (type->is_method())
1816 const Typed_identifier* receiver = type->receiver();
1817 Variable* this_param = new Variable(receiver->type(), NULL, false,
1818 true, true, location);
1819 std::string rname = receiver->name();
1820 if (rname.empty() || Gogo::is_sink_name(rname))
1822 // We need to give receivers a name since they wind up in
1823 // DECL_ARGUMENTS. FIXME.
1824 static unsigned int count;
1825 char buf[50];
1826 snprintf(buf, sizeof buf, "r.%u", count);
1827 ++count;
1828 rname = buf;
1830 block->bindings()->add_variable(rname, NULL, this_param);
1833 const Typed_identifier_list* parameters = type->parameters();
1834 bool is_varargs = type->is_varargs();
1835 if (parameters != NULL)
1837 for (Typed_identifier_list::const_iterator p = parameters->begin();
1838 p != parameters->end();
1839 ++p)
1841 Variable* param = new Variable(p->type(), NULL, false, true, false,
1842 p->location());
1843 if (is_varargs && p + 1 == parameters->end())
1844 param->set_is_varargs_parameter();
1846 std::string pname = p->name();
1847 if (pname.empty() || Gogo::is_sink_name(pname))
1849 // We need to give parameters a name since they wind up
1850 // in DECL_ARGUMENTS. FIXME.
1851 static unsigned int count;
1852 char buf[50];
1853 snprintf(buf, sizeof buf, "p.%u", count);
1854 ++count;
1855 pname = buf;
1857 block->bindings()->add_variable(pname, NULL, param);
1861 function->create_result_variables(this);
1863 const std::string* pname;
1864 std::string nested_name;
1865 bool is_init = false;
1866 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
1868 if ((type->parameters() != NULL && !type->parameters()->empty())
1869 || (type->results() != NULL && !type->results()->empty()))
1870 go_error_at(location,
1871 "func init must have no arguments and no return values");
1872 // There can be multiple "init" functions, so give them each a
1873 // different name.
1874 nested_name = this->init_function_name();
1875 pname = &nested_name;
1876 is_init = true;
1878 else if (!name.empty())
1879 pname = &name;
1880 else
1882 // Invent a name for a nested function.
1883 nested_name = this->nested_function_name(enclosing);
1884 pname = &nested_name;
1887 Named_object* ret;
1888 if (Gogo::is_sink_name(*pname))
1890 std::string sname(this->sink_function_name());
1891 ret = Named_object::make_function(sname, NULL, function);
1892 ret->func_value()->set_is_sink();
1894 if (!type->is_method())
1895 ret = this->package_->bindings()->add_named_object(ret);
1896 else if (add_method_to_type)
1898 // We should report errors even for sink methods.
1899 Type* rtype = type->receiver()->type();
1900 // Avoid points_to and deref to avoid getting an error if
1901 // the type is not yet defined.
1902 if (rtype->classification() == Type::TYPE_POINTER)
1903 rtype = rtype->points_to();
1904 while (rtype->named_type() != NULL
1905 && rtype->named_type()->is_alias())
1906 rtype = rtype->named_type()->real_type()->forwarded();
1907 if (rtype->is_error_type())
1909 else if (rtype->named_type() != NULL)
1911 if (rtype->named_type()->named_object()->package() != NULL)
1912 go_error_at(type->receiver()->location(),
1913 "may not define methods on non-local type");
1915 else if (rtype->forward_declaration_type() != NULL)
1917 // Go ahead and add the method in case we need to report
1918 // an error when we see the definition.
1919 rtype->forward_declaration_type()->add_existing_method(ret);
1921 else
1922 go_error_at(type->receiver()->location(),
1923 ("invalid receiver type "
1924 "(receiver must be a named type)"));
1927 else if (!type->is_method())
1929 ret = this->package_->bindings()->add_function(*pname, NULL, function);
1930 if (!ret->is_function() || ret->func_value() != function)
1932 // Redefinition error. Invent a name to avoid knockon
1933 // errors.
1934 std::string rname(this->redefined_function_name());
1935 ret = this->package_->bindings()->add_function(rname, NULL, function);
1938 else
1940 if (!add_method_to_type)
1941 ret = Named_object::make_function(name, NULL, function);
1942 else
1944 go_assert(at_top_level);
1945 Type* rtype = type->receiver()->type();
1947 // We want to look through the pointer created by the
1948 // parser, without getting an error if the type is not yet
1949 // defined.
1950 if (rtype->classification() == Type::TYPE_POINTER)
1951 rtype = rtype->points_to();
1953 while (rtype->named_type() != NULL
1954 && rtype->named_type()->is_alias())
1955 rtype = rtype->named_type()->real_type()->forwarded();
1957 if (rtype->is_error_type())
1958 ret = Named_object::make_function(name, NULL, function);
1959 else if (rtype->named_type() != NULL)
1961 if (rtype->named_type()->named_object()->package() != NULL)
1963 go_error_at(type->receiver()->location(),
1964 "may not define methods on non-local type");
1965 ret = Named_object::make_function(name, NULL, function);
1967 else
1969 ret = rtype->named_type()->add_method(name, function);
1970 if (!ret->is_function())
1972 // Redefinition error.
1973 ret = Named_object::make_function(name, NULL, function);
1977 else if (rtype->forward_declaration_type() != NULL)
1979 Named_object* type_no =
1980 rtype->forward_declaration_type()->named_object();
1981 if (type_no->is_unknown())
1983 // If we are seeing methods it really must be a
1984 // type. Declare it as such. An alternative would
1985 // be to support lists of methods for unknown
1986 // expressions. Either way the error messages if
1987 // this is not a type are going to get confusing.
1988 Named_object* declared =
1989 this->declare_package_type(type_no->name(),
1990 type_no->location());
1991 go_assert(declared
1992 == type_no->unknown_value()->real_named_object());
1994 ret = rtype->forward_declaration_type()->add_method(name,
1995 function);
1997 else
1999 go_error_at(type->receiver()->location(),
2000 ("invalid receiver type (receiver must "
2001 "be a named type)"));
2002 ret = Named_object::make_function(name, NULL, function);
2005 this->package_->bindings()->add_method(ret);
2008 this->functions_.resize(this->functions_.size() + 1);
2009 Open_function& of(this->functions_.back());
2010 of.function = ret;
2011 of.blocks.push_back(block);
2013 if (is_init)
2015 this->init_functions_.push_back(ret);
2016 this->need_init_fn_ = true;
2019 return ret;
2022 // Finish compiling a function.
2024 void
2025 Gogo::finish_function(Location location)
2027 this->finish_block(location);
2028 go_assert(this->functions_.back().blocks.empty());
2029 this->functions_.pop_back();
2032 // Return the current function.
2034 Named_object*
2035 Gogo::current_function() const
2037 go_assert(!this->functions_.empty());
2038 return this->functions_.back().function;
2041 // Start a new block.
2043 void
2044 Gogo::start_block(Location location)
2046 go_assert(!this->functions_.empty());
2047 Block* block = new Block(this->current_block(), location);
2048 this->functions_.back().blocks.push_back(block);
2051 // Finish a block.
2053 Block*
2054 Gogo::finish_block(Location location)
2056 go_assert(!this->functions_.empty());
2057 go_assert(!this->functions_.back().blocks.empty());
2058 Block* block = this->functions_.back().blocks.back();
2059 this->functions_.back().blocks.pop_back();
2060 block->set_end_location(location);
2061 return block;
2064 // Add an erroneous name.
2066 Named_object*
2067 Gogo::add_erroneous_name(const std::string& name)
2069 return this->package_->bindings()->add_erroneous_name(name);
2072 // Add an unknown name.
2074 Named_object*
2075 Gogo::add_unknown_name(const std::string& name, Location location)
2077 return this->package_->bindings()->add_unknown_name(name, location);
2080 // Declare a function.
2082 Named_object*
2083 Gogo::declare_function(const std::string& name, Function_type* type,
2084 Location location)
2086 if (!type->is_method())
2087 return this->current_bindings()->add_function_declaration(name, NULL, type,
2088 location);
2089 else
2091 // We don't bother to add this to the list of global
2092 // declarations.
2093 Type* rtype = type->receiver()->type();
2095 // We want to look through the pointer created by the
2096 // parser, without getting an error if the type is not yet
2097 // defined.
2098 if (rtype->classification() == Type::TYPE_POINTER)
2099 rtype = rtype->points_to();
2101 if (rtype->is_error_type())
2102 return NULL;
2103 else if (rtype->named_type() != NULL)
2104 return rtype->named_type()->add_method_declaration(name, NULL, type,
2105 location);
2106 else if (rtype->forward_declaration_type() != NULL)
2108 Forward_declaration_type* ftype = rtype->forward_declaration_type();
2109 return ftype->add_method_declaration(name, NULL, type, location);
2111 else
2113 go_error_at(type->receiver()->location(),
2114 "invalid receiver type (receiver must be a named type)");
2115 return Named_object::make_erroneous_name(name);
2120 // Add a label definition.
2122 Label*
2123 Gogo::add_label_definition(const std::string& label_name,
2124 Location location)
2126 go_assert(!this->functions_.empty());
2127 Function* func = this->functions_.back().function->func_value();
2128 Label* label = func->add_label_definition(this, label_name, location);
2129 this->add_statement(Statement::make_label_statement(label, location));
2130 return label;
2133 // Add a label reference.
2135 Label*
2136 Gogo::add_label_reference(const std::string& label_name,
2137 Location location, bool issue_goto_errors)
2139 go_assert(!this->functions_.empty());
2140 Function* func = this->functions_.back().function->func_value();
2141 return func->add_label_reference(this, label_name, location,
2142 issue_goto_errors);
2145 // Return the current binding state.
2147 Bindings_snapshot*
2148 Gogo::bindings_snapshot(Location location)
2150 return new Bindings_snapshot(this->current_block(), location);
2153 // Add a statement.
2155 void
2156 Gogo::add_statement(Statement* statement)
2158 go_assert(!this->functions_.empty()
2159 && !this->functions_.back().blocks.empty());
2160 this->functions_.back().blocks.back()->add_statement(statement);
2163 // Add a block.
2165 void
2166 Gogo::add_block(Block* block, Location location)
2168 go_assert(!this->functions_.empty()
2169 && !this->functions_.back().blocks.empty());
2170 Statement* statement = Statement::make_block_statement(block, location);
2171 this->functions_.back().blocks.back()->add_statement(statement);
2174 // Add a constant.
2176 Named_object*
2177 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
2178 int iota_value)
2180 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
2183 // Add a type.
2185 void
2186 Gogo::add_type(const std::string& name, Type* type, Location location)
2188 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
2189 location);
2190 if (!this->in_global_scope() && no->is_type())
2192 Named_object* f = this->functions_.back().function;
2193 unsigned int index;
2194 if (f->is_function())
2195 index = f->func_value()->new_local_type_index();
2196 else
2197 index = 0;
2198 no->type_value()->set_in_function(f, index);
2202 // Add a named type.
2204 void
2205 Gogo::add_named_type(Named_type* type)
2207 go_assert(this->in_global_scope());
2208 this->current_bindings()->add_named_type(type);
2211 // Declare a type.
2213 Named_object*
2214 Gogo::declare_type(const std::string& name, Location location)
2216 Bindings* bindings = this->current_bindings();
2217 Named_object* no = bindings->add_type_declaration(name, NULL, location);
2218 if (!this->in_global_scope() && no->is_type_declaration())
2220 Named_object* f = this->functions_.back().function;
2221 unsigned int index;
2222 if (f->is_function())
2223 index = f->func_value()->new_local_type_index();
2224 else
2225 index = 0;
2226 no->type_declaration_value()->set_in_function(f, index);
2228 return no;
2231 // Declare a type at the package level.
2233 Named_object*
2234 Gogo::declare_package_type(const std::string& name, Location location)
2236 return this->package_->bindings()->add_type_declaration(name, NULL, location);
2239 // Declare a function at the package level.
2241 Named_object*
2242 Gogo::declare_package_function(const std::string& name, Function_type* type,
2243 Location location)
2245 return this->package_->bindings()->add_function_declaration(name, NULL, type,
2246 location);
2249 // Add a function declaration to the list of functions we may want to
2250 // inline.
2252 void
2253 Gogo::add_imported_inlinable_function(Named_object* no)
2255 go_assert(no->is_function_declaration());
2256 Function_declaration* fd = no->func_declaration_value();
2257 if (fd->is_on_inlinable_list())
2258 return;
2259 this->imported_inlinable_functions_.push_back(no);
2260 fd->set_is_on_inlinable_list();
2263 // Define a type which was already declared.
2265 void
2266 Gogo::define_type(Named_object* no, Named_type* type)
2268 this->current_bindings()->define_type(no, type);
2271 // Add a variable.
2273 Named_object*
2274 Gogo::add_variable(const std::string& name, Variable* variable)
2276 Named_object* no = this->current_bindings()->add_variable(name, NULL,
2277 variable);
2279 // In a function the middle-end wants to see a DECL_EXPR node.
2280 if (no != NULL
2281 && no->is_variable()
2282 && !no->var_value()->is_parameter()
2283 && !this->functions_.empty())
2284 this->add_statement(Statement::make_variable_declaration(no));
2286 return no;
2289 // Add a sink--a reference to the blank identifier _.
2291 Named_object*
2292 Gogo::add_sink()
2294 return Named_object::make_sink();
2297 // Add a named object for a dot import.
2299 void
2300 Gogo::add_dot_import_object(Named_object* no)
2302 // If the name already exists, then it was defined in some file seen
2303 // earlier. If the earlier name is just a declaration, don't add
2304 // this name, because that will cause the previous declaration to
2305 // merge to this imported name, which should not happen. Just add
2306 // this name to the list of file block names to get appropriate
2307 // errors if we see a later definition.
2308 Named_object* e = this->package_->bindings()->lookup(no->name());
2309 if (e != NULL && e->package() == NULL)
2311 if (e->is_unknown())
2312 e = e->resolve();
2313 if (e->package() == NULL
2314 && (e->is_type_declaration()
2315 || e->is_function_declaration()
2316 || e->is_unknown()))
2318 this->add_file_block_name(no->name(), no->location());
2319 return;
2323 this->current_bindings()->add_named_object(no);
2326 // Add a linkname. This implements the go:linkname compiler directive.
2327 // We only support this for functions and function declarations.
2329 void
2330 Gogo::add_linkname(const std::string& go_name, bool is_exported,
2331 const std::string& ext_name, Location loc)
2333 Named_object* no =
2334 this->package_->bindings()->lookup(this->pack_hidden_name(go_name,
2335 is_exported));
2336 if (no == NULL)
2337 go_error_at(loc, "%s is not defined", go_name.c_str());
2338 else if (no->is_function())
2339 no->func_value()->set_asm_name(ext_name);
2340 else if (no->is_function_declaration())
2341 no->func_declaration_value()->set_asm_name(ext_name);
2342 else
2343 go_error_at(loc,
2344 ("%s is not a function; "
2345 "//go:linkname is only supported for functions"),
2346 go_name.c_str());
2349 // Mark all local variables used. This is used when some types of
2350 // parse error occur.
2352 void
2353 Gogo::mark_locals_used()
2355 for (Open_functions::iterator pf = this->functions_.begin();
2356 pf != this->functions_.end();
2357 ++pf)
2359 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2360 pb != pf->blocks.end();
2361 ++pb)
2362 (*pb)->bindings()->mark_locals_used();
2366 // Record that we've seen an interface type.
2368 void
2369 Gogo::record_interface_type(Interface_type* itype)
2371 this->interface_types_.push_back(itype);
2374 // Define the global names. We do this only after parsing all the
2375 // input files, because the program might define the global names
2376 // itself.
2378 void
2379 Gogo::define_global_names()
2381 if (this->is_main_package())
2383 // Every Go program has to import the runtime package, so that
2384 // it is properly initialized.
2385 this->import_package("runtime", "_", false, false,
2386 Linemap::predeclared_location());
2389 for (Bindings::const_declarations_iterator p =
2390 this->globals_->begin_declarations();
2391 p != this->globals_->end_declarations();
2392 ++p)
2394 Named_object* global_no = p->second;
2395 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2396 Named_object* no = this->package_->bindings()->lookup(name);
2397 if (no == NULL)
2398 continue;
2399 no = no->resolve();
2400 if (no->is_type_declaration())
2402 if (global_no->is_type())
2404 if (no->type_declaration_value()->has_methods())
2406 for (std::vector<Named_object*>::const_iterator p =
2407 no->type_declaration_value()->methods()->begin();
2408 p != no->type_declaration_value()->methods()->end();
2409 p++)
2410 go_error_at((*p)->location(),
2411 "may not define methods on non-local type");
2413 no->set_type_value(global_no->type_value());
2415 else
2417 go_error_at(no->location(), "expected type");
2418 Type* errtype = Type::make_error_type();
2419 Named_object* err =
2420 Named_object::make_type("erroneous_type", NULL, errtype,
2421 Linemap::predeclared_location());
2422 no->set_type_value(err->type_value());
2425 else if (no->is_unknown())
2426 no->unknown_value()->set_real_named_object(global_no);
2429 // Give an error if any name is defined in both the package block
2430 // and the file block. For example, this can happen if one file
2431 // imports "fmt" and another file defines a global variable fmt.
2432 for (Bindings::const_declarations_iterator p =
2433 this->package_->bindings()->begin_declarations();
2434 p != this->package_->bindings()->end_declarations();
2435 ++p)
2437 if (p->second->is_unknown()
2438 && p->second->unknown_value()->real_named_object() == NULL)
2440 // No point in warning about an undefined name, as we will
2441 // get other errors later anyhow.
2442 continue;
2444 File_block_names::const_iterator pf =
2445 this->file_block_names_.find(p->second->name());
2446 if (pf != this->file_block_names_.end())
2448 std::string n = p->second->message_name();
2449 go_error_at(p->second->location(),
2450 "%qs defined as both imported name and global name",
2451 n.c_str());
2452 go_inform(pf->second, "%qs imported here", n.c_str());
2455 // No package scope identifier may be named "init".
2456 if (!p->second->is_function()
2457 && Gogo::unpack_hidden_name(p->second->name()) == "init")
2459 go_error_at(p->second->location(),
2460 "cannot declare init - must be func");
2465 // Clear out names in file scope.
2467 void
2468 Gogo::clear_file_scope()
2470 this->package_->bindings()->clear_file_scope(this);
2472 // Warn about packages which were imported but not used.
2473 bool quiet = saw_errors();
2474 for (Packages::iterator p = this->packages_.begin();
2475 p != this->packages_.end();
2476 ++p)
2478 Package* package = p->second;
2479 if (package != this->package_ && !quiet)
2481 for (Package::Aliases::const_iterator p1 = package->aliases().begin();
2482 p1 != package->aliases().end();
2483 ++p1)
2485 if (!p1->second->used())
2487 // Give a more refined error message if the alias name is known.
2488 std::string pkg_name = package->package_name();
2489 if (p1->first != pkg_name && p1->first[0] != '.')
2491 go_error_at(p1->second->location(),
2492 "imported and not used: %s as %s",
2493 Gogo::message_name(pkg_name).c_str(),
2494 Gogo::message_name(p1->first).c_str());
2496 else
2497 go_error_at(p1->second->location(),
2498 "imported and not used: %s",
2499 Gogo::message_name(pkg_name).c_str());
2503 package->clear_used();
2506 this->current_file_imported_unsafe_ = false;
2509 // Queue up a type specific function for later writing. These are
2510 // written out in write_specific_type_functions, called after the
2511 // parse tree is lowered.
2513 void
2514 Gogo::queue_specific_type_function(Type* type, Named_type* name, int64_t size,
2515 const std::string& hash_name,
2516 Function_type* hash_fntype,
2517 const std::string& equal_name,
2518 Function_type* equal_fntype)
2520 go_assert(!this->specific_type_functions_are_written_);
2521 go_assert(!this->in_global_scope());
2522 Specific_type_function* tsf = new Specific_type_function(type, name, size,
2523 hash_name,
2524 hash_fntype,
2525 equal_name,
2526 equal_fntype);
2527 this->specific_type_functions_.push_back(tsf);
2530 // Look for types which need specific hash or equality functions.
2532 class Specific_type_functions : public Traverse
2534 public:
2535 Specific_type_functions(Gogo* gogo)
2536 : Traverse(traverse_types),
2537 gogo_(gogo)
2541 type(Type*);
2543 private:
2544 Gogo* gogo_;
2548 Specific_type_functions::type(Type* t)
2550 Named_object* hash_fn;
2551 Named_object* equal_fn;
2552 switch (t->classification())
2554 case Type::TYPE_NAMED:
2556 Named_type* nt = t->named_type();
2557 if (nt->is_alias())
2558 return TRAVERSE_CONTINUE;
2559 if (t->needs_specific_type_functions(this->gogo_))
2560 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
2562 // If this is a struct type, we don't want to make functions
2563 // for the unnamed struct.
2564 Type* rt = nt->real_type();
2565 if (rt->struct_type() == NULL)
2567 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2568 return TRAVERSE_EXIT;
2570 else
2572 // If this type is defined in another package, then we don't
2573 // need to worry about the unexported fields.
2574 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2575 const Struct_field_list* fields = rt->struct_type()->fields();
2576 for (Struct_field_list::const_iterator p = fields->begin();
2577 p != fields->end();
2578 ++p)
2580 if (is_defined_elsewhere
2581 && Gogo::is_hidden_name(p->field_name()))
2582 continue;
2583 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2584 return TRAVERSE_EXIT;
2588 return TRAVERSE_SKIP_COMPONENTS;
2591 case Type::TYPE_STRUCT:
2592 case Type::TYPE_ARRAY:
2593 if (t->needs_specific_type_functions(this->gogo_))
2594 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
2595 break;
2597 default:
2598 break;
2601 return TRAVERSE_CONTINUE;
2604 // Write out type specific functions.
2606 void
2607 Gogo::write_specific_type_functions()
2609 Specific_type_functions stf(this);
2610 this->traverse(&stf);
2612 while (!this->specific_type_functions_.empty())
2614 Specific_type_function* tsf = this->specific_type_functions_.back();
2615 this->specific_type_functions_.pop_back();
2616 tsf->type->write_specific_type_functions(this, tsf->name, tsf->size,
2617 tsf->hash_name,
2618 tsf->hash_fntype,
2619 tsf->equal_name,
2620 tsf->equal_fntype);
2621 delete tsf;
2623 this->specific_type_functions_are_written_ = true;
2626 // Traverse the tree.
2628 void
2629 Gogo::traverse(Traverse* traverse)
2631 // Traverse the current package first for consistency. The other
2632 // packages will only contain imported types, constants, and
2633 // declarations.
2634 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2635 return;
2636 for (Packages::const_iterator p = this->packages_.begin();
2637 p != this->packages_.end();
2638 ++p)
2640 if (p->second != this->package_)
2642 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2643 break;
2648 // Add a type to verify. This is used for types of sink variables, in
2649 // order to give appropriate error messages.
2651 void
2652 Gogo::add_type_to_verify(Type* type)
2654 this->verify_types_.push_back(type);
2657 // Traversal class used to verify types.
2659 class Verify_types : public Traverse
2661 public:
2662 Verify_types()
2663 : Traverse(traverse_types)
2667 type(Type*);
2670 // Verify that a type is correct.
2673 Verify_types::type(Type* t)
2675 if (!t->verify())
2676 return TRAVERSE_SKIP_COMPONENTS;
2677 return TRAVERSE_CONTINUE;
2680 // Verify that all types are correct.
2682 void
2683 Gogo::verify_types()
2685 Verify_types traverse;
2686 this->traverse(&traverse);
2688 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2689 p != this->verify_types_.end();
2690 ++p)
2691 (*p)->verify();
2692 this->verify_types_.clear();
2695 // Traversal class used to lower parse tree.
2697 class Lower_parse_tree : public Traverse
2699 public:
2700 Lower_parse_tree(Gogo* gogo, Named_object* function)
2701 : Traverse(traverse_variables
2702 | traverse_constants
2703 | traverse_functions
2704 | traverse_statements
2705 | traverse_expressions),
2706 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2709 void
2710 set_inserter(const Statement_inserter* inserter)
2711 { this->inserter_ = *inserter; }
2714 variable(Named_object*);
2717 constant(Named_object*, bool);
2720 function(Named_object*);
2723 statement(Block*, size_t* pindex, Statement*);
2726 expression(Expression**);
2728 private:
2729 // General IR.
2730 Gogo* gogo_;
2731 // The function we are traversing.
2732 Named_object* function_;
2733 // Value to use for the predeclared constant iota.
2734 int iota_value_;
2735 // Current statement inserter for use by expressions.
2736 Statement_inserter inserter_;
2739 // Lower variables.
2742 Lower_parse_tree::variable(Named_object* no)
2744 if (!no->is_variable())
2745 return TRAVERSE_CONTINUE;
2747 if (no->is_variable() && no->var_value()->is_global())
2749 // Global variables can have loops in their initialization
2750 // expressions. This is handled in lower_init_expression.
2751 no->var_value()->lower_init_expression(this->gogo_, this->function_,
2752 &this->inserter_);
2753 return TRAVERSE_CONTINUE;
2756 // This is a local variable. We are going to return
2757 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2758 // initialization expression when we reach the variable declaration
2759 // statement. However, that means that we need to traverse the type
2760 // ourselves.
2761 if (no->var_value()->has_type())
2763 Type* type = no->var_value()->type();
2764 if (type != NULL)
2766 if (Type::traverse(type, this) == TRAVERSE_EXIT)
2767 return TRAVERSE_EXIT;
2770 go_assert(!no->var_value()->has_pre_init());
2772 return TRAVERSE_SKIP_COMPONENTS;
2775 // Lower constants. We handle constants specially so that we can set
2776 // the right value for the predeclared constant iota. This works in
2777 // conjunction with the way we lower Const_expression objects.
2780 Lower_parse_tree::constant(Named_object* no, bool)
2782 Named_constant* nc = no->const_value();
2784 // Don't get into trouble if the constant's initializer expression
2785 // refers to the constant itself.
2786 if (nc->lowering())
2787 return TRAVERSE_CONTINUE;
2788 nc->set_lowering();
2790 go_assert(this->iota_value_ == -1);
2791 this->iota_value_ = nc->iota_value();
2792 nc->traverse_expression(this);
2793 this->iota_value_ = -1;
2795 nc->clear_lowering();
2797 // We will traverse the expression a second time, but that will be
2798 // fast.
2800 return TRAVERSE_CONTINUE;
2803 // Lower the body of a function, and set the closure type. Record the
2804 // function while lowering it, so that we can pass it down when
2805 // lowering an expression.
2808 Lower_parse_tree::function(Named_object* no)
2810 no->func_value()->set_closure_type();
2812 go_assert(this->function_ == NULL);
2813 this->function_ = no;
2814 int t = no->func_value()->traverse(this);
2815 this->function_ = NULL;
2817 if (t == TRAVERSE_EXIT)
2818 return t;
2819 return TRAVERSE_SKIP_COMPONENTS;
2822 // Lower statement parse trees.
2825 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
2827 // Because we explicitly traverse the statement's contents
2828 // ourselves, we want to skip block statements here. There is
2829 // nothing to lower in a block statement.
2830 if (sorig->is_block_statement())
2831 return TRAVERSE_CONTINUE;
2833 Statement_inserter hold_inserter(this->inserter_);
2834 this->inserter_ = Statement_inserter(block, pindex);
2836 // Lower the expressions first.
2837 int t = sorig->traverse_contents(this);
2838 if (t == TRAVERSE_EXIT)
2840 this->inserter_ = hold_inserter;
2841 return t;
2844 // Keep lowering until nothing changes.
2845 Statement* s = sorig;
2846 while (true)
2848 Statement* snew = s->lower(this->gogo_, this->function_, block,
2849 &this->inserter_);
2850 if (snew == s)
2851 break;
2852 s = snew;
2853 t = s->traverse_contents(this);
2854 if (t == TRAVERSE_EXIT)
2856 this->inserter_ = hold_inserter;
2857 return t;
2861 if (s != sorig)
2862 block->replace_statement(*pindex, s);
2864 this->inserter_ = hold_inserter;
2865 return TRAVERSE_SKIP_COMPONENTS;
2868 // Lower expression parse trees.
2871 Lower_parse_tree::expression(Expression** pexpr)
2873 // We have to lower all subexpressions first, so that we can get
2874 // their type if necessary. This is awkward, because we don't have
2875 // a postorder traversal pass.
2876 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2877 return TRAVERSE_EXIT;
2878 // Keep lowering until nothing changes.
2879 while (true)
2881 Expression* e = *pexpr;
2882 Expression* enew = e->lower(this->gogo_, this->function_,
2883 &this->inserter_, this->iota_value_);
2884 if (enew == e)
2885 break;
2886 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
2887 return TRAVERSE_EXIT;
2888 *pexpr = enew;
2891 // Lower the type of this expression before the parent looks at it,
2892 // in case the type contains an array that has expressions in its
2893 // length. Skip an Unknown_expression, as at this point that means
2894 // a composite literal key that does not have a type.
2895 if ((*pexpr)->unknown_expression() == NULL)
2896 Type::traverse((*pexpr)->type(), this);
2898 return TRAVERSE_SKIP_COMPONENTS;
2901 // Lower the parse tree. This is called after the parse is complete,
2902 // when all names should be resolved.
2904 void
2905 Gogo::lower_parse_tree()
2907 Lower_parse_tree lower_parse_tree(this, NULL);
2908 this->traverse(&lower_parse_tree);
2910 // If we found any functions defined in other packages that are
2911 // inlinables, import their bodies and turn them into functions.
2913 // Note that as we import inlinable functions we may find more
2914 // inlinable functions, so don't use an iterator.
2915 for (size_t i = 0; i < this->imported_inlinable_functions_.size(); i++)
2917 Named_object* no = this->imported_inlinable_functions_[i];
2918 no->func_declaration_value()->import_function_body(this, no);
2921 // There might be type definitions that involve expressions such as the
2922 // array length. Make sure to lower these expressions as well. Otherwise,
2923 // errors hidden within a type can introduce unexpected errors into later
2924 // passes.
2925 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2926 p != this->verify_types_.end();
2927 ++p)
2928 Type::traverse(*p, &lower_parse_tree);
2931 // Lower a block.
2933 void
2934 Gogo::lower_block(Named_object* function, Block* block)
2936 Lower_parse_tree lower_parse_tree(this, function);
2937 block->traverse(&lower_parse_tree);
2940 // Lower an expression. INSERTER may be NULL, in which case the
2941 // expression had better not need to create any temporaries.
2943 void
2944 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
2945 Expression** pexpr)
2947 Lower_parse_tree lower_parse_tree(this, function);
2948 if (inserter != NULL)
2949 lower_parse_tree.set_inserter(inserter);
2950 lower_parse_tree.expression(pexpr);
2953 // Lower a constant. This is called when lowering a reference to a
2954 // constant. We have to make sure that the constant has already been
2955 // lowered.
2957 void
2958 Gogo::lower_constant(Named_object* no)
2960 go_assert(no->is_const());
2961 Lower_parse_tree lower(this, NULL);
2962 lower.constant(no, false);
2965 // Traverse the tree to create function descriptors as needed.
2967 class Create_function_descriptors : public Traverse
2969 public:
2970 Create_function_descriptors(Gogo* gogo)
2971 : Traverse(traverse_functions | traverse_expressions),
2972 gogo_(gogo)
2976 function(Named_object*);
2979 expression(Expression**);
2981 private:
2982 Gogo* gogo_;
2985 // Create a descriptor for every top-level exported function.
2988 Create_function_descriptors::function(Named_object* no)
2990 if (no->is_function()
2991 && no->func_value()->enclosing() == NULL
2992 && !no->func_value()->is_method()
2993 && !Gogo::is_hidden_name(no->name())
2994 && !Gogo::is_thunk(no))
2995 no->func_value()->descriptor(this->gogo_, no);
2997 return TRAVERSE_CONTINUE;
3000 // If we see a function referenced in any way other than calling it,
3001 // create a descriptor for it.
3004 Create_function_descriptors::expression(Expression** pexpr)
3006 Expression* expr = *pexpr;
3008 Func_expression* fe = expr->func_expression();
3009 if (fe != NULL)
3011 // We would not get here for a call to this function, so this is
3012 // a reference to a function other than calling it. We need a
3013 // descriptor.
3014 if (fe->closure() != NULL)
3015 return TRAVERSE_CONTINUE;
3016 Named_object* no = fe->named_object();
3017 if (no->is_function() && !no->func_value()->is_method())
3018 no->func_value()->descriptor(this->gogo_, no);
3019 else if (no->is_function_declaration()
3020 && !no->func_declaration_value()->type()->is_method()
3021 && !Linemap::is_predeclared_location(no->location()))
3022 no->func_declaration_value()->descriptor(this->gogo_, no);
3023 return TRAVERSE_CONTINUE;
3026 Bound_method_expression* bme = expr->bound_method_expression();
3027 if (bme != NULL)
3029 // We would not get here for a call to this method, so this is a
3030 // method value. We need to create a thunk.
3031 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
3032 bme->function());
3033 return TRAVERSE_CONTINUE;
3036 Interface_field_reference_expression* ifre =
3037 expr->interface_field_reference_expression();
3038 if (ifre != NULL)
3040 // We would not get here for a call to this interface method, so
3041 // this is a method value. We need to create a thunk.
3042 Interface_type* type = ifre->expr()->type()->interface_type();
3043 if (type != NULL)
3044 Interface_field_reference_expression::create_thunk(this->gogo_, type,
3045 ifre->name());
3046 return TRAVERSE_CONTINUE;
3049 Call_expression* ce = expr->call_expression();
3050 if (ce != NULL)
3052 Expression* fn = ce->fn();
3053 if (fn->func_expression() != NULL
3054 || fn->bound_method_expression() != NULL
3055 || fn->interface_field_reference_expression() != NULL)
3057 // Traverse the arguments but not the function.
3058 Expression_list* args = ce->args();
3059 if (args != NULL)
3061 if (args->traverse(this) == TRAVERSE_EXIT)
3062 return TRAVERSE_EXIT;
3064 return TRAVERSE_SKIP_COMPONENTS;
3068 return TRAVERSE_CONTINUE;
3071 // Create function descriptors as needed. We need a function
3072 // descriptor for all exported functions and for all functions that
3073 // are referenced without being called.
3075 void
3076 Gogo::create_function_descriptors()
3078 // Create a function descriptor for any exported function that is
3079 // declared in this package. This is so that we have a descriptor
3080 // for functions written in assembly. Gather the descriptors first
3081 // so that we don't add declarations while looping over them.
3082 std::vector<Named_object*> fndecls;
3083 Bindings* b = this->package_->bindings();
3084 for (Bindings::const_declarations_iterator p = b->begin_declarations();
3085 p != b->end_declarations();
3086 ++p)
3088 Named_object* no = p->second;
3089 if (no->is_function_declaration()
3090 && !no->func_declaration_value()->type()->is_method()
3091 && !Linemap::is_predeclared_location(no->location())
3092 && !Gogo::is_hidden_name(no->name()))
3093 fndecls.push_back(no);
3095 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
3096 p != fndecls.end();
3097 ++p)
3098 (*p)->func_declaration_value()->descriptor(this, *p);
3099 fndecls.clear();
3101 Create_function_descriptors cfd(this);
3102 this->traverse(&cfd);
3105 // Look for interface types to finalize methods of inherited
3106 // interfaces.
3108 class Finalize_methods : public Traverse
3110 public:
3111 Finalize_methods(Gogo* gogo)
3112 : Traverse(traverse_types),
3113 gogo_(gogo)
3117 type(Type*);
3119 private:
3120 Gogo* gogo_;
3123 // Finalize the methods of an interface type.
3126 Finalize_methods::type(Type* t)
3128 // Check the classification so that we don't finalize the methods
3129 // twice for a named interface type.
3130 switch (t->classification())
3132 case Type::TYPE_INTERFACE:
3133 t->interface_type()->finalize_methods();
3134 break;
3136 case Type::TYPE_NAMED:
3138 Named_type* nt = t->named_type();
3139 Type* rt = nt->real_type();
3140 if (rt->classification() != Type::TYPE_STRUCT)
3142 // Finalize the methods of the real type first.
3143 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
3144 return TRAVERSE_EXIT;
3146 // Finalize the methods of this type.
3147 nt->finalize_methods(this->gogo_);
3149 else
3151 // We don't want to finalize the methods of a named struct
3152 // type, as the methods should be attached to the named
3153 // type, not the struct type. We just want to finalize
3154 // the field types.
3156 // It is possible that a field type refers indirectly to
3157 // this type, such as via a field with function type with
3158 // an argument or result whose type is this type. To
3159 // avoid the cycle, first finalize the methods of any
3160 // embedded types, which are the only types we need to
3161 // know to finalize the methods of this type.
3162 const Struct_field_list* fields = rt->struct_type()->fields();
3163 if (fields != NULL)
3165 for (Struct_field_list::const_iterator pf = fields->begin();
3166 pf != fields->end();
3167 ++pf)
3169 if (pf->is_anonymous())
3171 if (Type::traverse(pf->type(), this) == TRAVERSE_EXIT)
3172 return TRAVERSE_EXIT;
3177 // Finalize the methods of this type.
3178 nt->finalize_methods(this->gogo_);
3180 // Finalize all the struct fields.
3181 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3182 return TRAVERSE_EXIT;
3185 // If this type is defined in a different package, then finalize the
3186 // types of all the methods, since we won't see them otherwise.
3187 if (nt->named_object()->package() != NULL && nt->has_any_methods())
3189 const Methods* methods = nt->methods();
3190 for (Methods::const_iterator p = methods->begin();
3191 p != methods->end();
3192 ++p)
3194 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3195 return TRAVERSE_EXIT;
3199 // Finalize the types of all methods that are declared but not
3200 // defined, since we won't see the declarations otherwise.
3201 if (nt->named_object()->package() == NULL
3202 && nt->local_methods() != NULL)
3204 const Bindings* methods = nt->local_methods();
3205 for (Bindings::const_declarations_iterator p =
3206 methods->begin_declarations();
3207 p != methods->end_declarations();
3208 p++)
3210 if (p->second->is_function_declaration())
3212 Type* mt = p->second->func_declaration_value()->type();
3213 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3214 return TRAVERSE_EXIT;
3219 return TRAVERSE_SKIP_COMPONENTS;
3222 case Type::TYPE_STRUCT:
3223 // Traverse the field types first in case there is an embedded
3224 // field with methods that the struct should inherit.
3225 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3226 return TRAVERSE_EXIT;
3227 t->struct_type()->finalize_methods(this->gogo_);
3228 return TRAVERSE_SKIP_COMPONENTS;
3230 default:
3231 break;
3234 return TRAVERSE_CONTINUE;
3237 // Finalize method lists and build stub methods for types.
3239 void
3240 Gogo::finalize_methods()
3242 Finalize_methods finalize(this);
3243 this->traverse(&finalize);
3246 // Finalize the method list for a type. This is called when a type is
3247 // parsed for an inlined function body, which happens after the
3248 // finalize_methods pass.
3250 void
3251 Gogo::finalize_methods_for_type(Type* type)
3253 Finalize_methods finalize(this);
3254 Type::traverse(type, &finalize);
3257 // Set types for unspecified variables and constants.
3259 void
3260 Gogo::determine_types()
3262 Bindings* bindings = this->current_bindings();
3263 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3264 p != bindings->end_definitions();
3265 ++p)
3267 if ((*p)->is_function())
3268 (*p)->func_value()->determine_types();
3269 else if ((*p)->is_variable())
3270 (*p)->var_value()->determine_type();
3271 else if ((*p)->is_const())
3272 (*p)->const_value()->determine_type();
3274 // See if a variable requires us to build an initialization
3275 // function. We know that we will see all global variables
3276 // here.
3277 if (!this->need_init_fn_ && (*p)->is_variable())
3279 Variable* variable = (*p)->var_value();
3281 // If this is a global variable which requires runtime
3282 // initialization, we need an initialization function.
3283 if (!variable->is_global())
3285 else if (variable->init() == NULL)
3287 else if (variable->type()->interface_type() != NULL)
3288 this->need_init_fn_ = true;
3289 else if (variable->init()->is_constant())
3291 else if (!variable->init()->is_composite_literal())
3292 this->need_init_fn_ = true;
3293 else if (variable->init()->is_nonconstant_composite_literal())
3294 this->need_init_fn_ = true;
3296 // If this is a global variable which holds a pointer value,
3297 // then we need an initialization function to register it as a
3298 // GC root.
3299 if (variable->is_global() && variable->type()->has_pointer())
3300 this->need_init_fn_ = true;
3304 // Determine the types of constants in packages.
3305 for (Packages::const_iterator p = this->packages_.begin();
3306 p != this->packages_.end();
3307 ++p)
3308 p->second->determine_types();
3311 // Traversal class used for type checking.
3313 class Check_types_traverse : public Traverse
3315 public:
3316 Check_types_traverse(Gogo* gogo)
3317 : Traverse(traverse_variables
3318 | traverse_constants
3319 | traverse_functions
3320 | traverse_statements
3321 | traverse_expressions),
3322 gogo_(gogo)
3326 variable(Named_object*);
3329 constant(Named_object*, bool);
3332 function(Named_object*);
3335 statement(Block*, size_t* pindex, Statement*);
3338 expression(Expression**);
3340 private:
3341 // General IR.
3342 Gogo* gogo_;
3345 // Check that a variable initializer has the right type.
3348 Check_types_traverse::variable(Named_object* named_object)
3350 if (named_object->is_variable())
3352 Variable* var = named_object->var_value();
3354 // Give error if variable type is not defined.
3355 var->type()->base();
3357 Expression* init = var->init();
3358 std::string reason;
3359 if (init != NULL
3360 && !Type::are_assignable(var->type(), init->type(), &reason))
3362 if (reason.empty())
3363 go_error_at(var->location(), "incompatible type in initialization");
3364 else
3365 go_error_at(var->location(),
3366 "incompatible type in initialization (%s)",
3367 reason.c_str());
3368 init = Expression::make_error(named_object->location());
3369 var->clear_init();
3371 else if (init != NULL
3372 && init->func_expression() != NULL)
3374 Named_object* no = init->func_expression()->named_object();
3375 Function_type* fntype;
3376 if (no->is_function())
3377 fntype = no->func_value()->type();
3378 else if (no->is_function_declaration())
3379 fntype = no->func_declaration_value()->type();
3380 else
3381 go_unreachable();
3383 // Builtin functions cannot be used as function values for variable
3384 // initialization.
3385 if (fntype->is_builtin())
3387 go_error_at(init->location(),
3388 "invalid use of special builtin function %qs; "
3389 "must be called",
3390 no->message_name().c_str());
3393 if (!var->is_used()
3394 && !var->is_global()
3395 && !var->is_parameter()
3396 && !var->is_receiver()
3397 && !var->type()->is_error()
3398 && (init == NULL || !init->is_error_expression())
3399 && !Lex::is_invalid_identifier(named_object->name()))
3400 go_error_at(var->location(), "%qs declared and not used",
3401 named_object->message_name().c_str());
3403 return TRAVERSE_CONTINUE;
3406 // Check that a constant initializer has the right type.
3409 Check_types_traverse::constant(Named_object* named_object, bool)
3411 Named_constant* constant = named_object->const_value();
3412 Type* ctype = constant->type();
3413 if (ctype->integer_type() == NULL
3414 && ctype->float_type() == NULL
3415 && ctype->complex_type() == NULL
3416 && !ctype->is_boolean_type()
3417 && !ctype->is_string_type())
3419 if (ctype->is_nil_type())
3420 go_error_at(constant->location(), "const initializer cannot be nil");
3421 else if (!ctype->is_error())
3422 go_error_at(constant->location(), "invalid constant type");
3423 constant->set_error();
3425 else if (!constant->expr()->is_constant())
3427 go_error_at(constant->expr()->location(), "expression is not constant");
3428 constant->set_error();
3430 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3431 NULL))
3433 go_error_at(constant->location(),
3434 "initialization expression has wrong type");
3435 constant->set_error();
3437 return TRAVERSE_CONTINUE;
3440 // There are no types to check in a function, but this is where we
3441 // issue warnings about labels which are defined but not referenced.
3444 Check_types_traverse::function(Named_object* no)
3446 no->func_value()->check_labels();
3447 return TRAVERSE_CONTINUE;
3450 // Check that types are valid in a statement.
3453 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3455 s->check_types(this->gogo_);
3456 return TRAVERSE_CONTINUE;
3459 // Check that types are valid in an expression.
3462 Check_types_traverse::expression(Expression** expr)
3464 (*expr)->check_types(this->gogo_);
3465 return TRAVERSE_CONTINUE;
3468 // Check that types are valid.
3470 void
3471 Gogo::check_types()
3473 Check_types_traverse traverse(this);
3474 this->traverse(&traverse);
3476 Bindings* bindings = this->current_bindings();
3477 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3478 p != bindings->end_declarations();
3479 ++p)
3481 // Also check the types in a function declaration's signature.
3482 Named_object* no = p->second;
3483 if (no->is_function_declaration())
3484 no->func_declaration_value()->check_types();
3488 // Check the types in a single block.
3490 void
3491 Gogo::check_types_in_block(Block* block)
3493 Check_types_traverse traverse(this);
3494 block->traverse(&traverse);
3497 // A traversal class which finds all the expressions which must be
3498 // evaluated in order within a statement or larger expression. This
3499 // is used to implement the rules about order of evaluation.
3501 class Find_eval_ordering : public Traverse
3503 private:
3504 typedef std::vector<Expression**> Expression_pointers;
3506 public:
3507 Find_eval_ordering()
3508 : Traverse(traverse_blocks
3509 | traverse_statements
3510 | traverse_expressions),
3511 exprs_()
3514 size_t
3515 size() const
3516 { return this->exprs_.size(); }
3518 typedef Expression_pointers::const_iterator const_iterator;
3520 const_iterator
3521 begin() const
3522 { return this->exprs_.begin(); }
3524 const_iterator
3525 end() const
3526 { return this->exprs_.end(); }
3528 protected:
3530 block(Block*)
3531 { return TRAVERSE_SKIP_COMPONENTS; }
3534 statement(Block*, size_t*, Statement*)
3535 { return TRAVERSE_SKIP_COMPONENTS; }
3538 expression(Expression**);
3540 private:
3541 // A list of pointers to expressions with side-effects.
3542 Expression_pointers exprs_;
3545 // If an expression must be evaluated in order, put it on the list.
3548 Find_eval_ordering::expression(Expression** expression_pointer)
3550 Binary_expression* binexp = (*expression_pointer)->binary_expression();
3551 if (binexp != NULL
3552 && (binexp->op() == OPERATOR_ANDAND || binexp->op() == OPERATOR_OROR))
3554 // Shortcut expressions may potentially have side effects which need
3555 // to be ordered, so add them to the list.
3556 // We don't order its subexpressions here since they may be evaluated
3557 // conditionally. This is handled in remove_shortcuts.
3558 this->exprs_.push_back(expression_pointer);
3559 return TRAVERSE_SKIP_COMPONENTS;
3562 // We have to look at subexpressions before this one.
3563 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3564 return TRAVERSE_EXIT;
3565 if ((*expression_pointer)->must_eval_in_order())
3566 this->exprs_.push_back(expression_pointer);
3567 return TRAVERSE_SKIP_COMPONENTS;
3570 // A traversal class for ordering evaluations.
3572 class Order_eval : public Traverse
3574 public:
3575 Order_eval(Gogo* gogo)
3576 : Traverse(traverse_variables
3577 | traverse_statements),
3578 gogo_(gogo)
3582 variable(Named_object*);
3585 statement(Block*, size_t*, Statement*);
3587 private:
3588 // The IR.
3589 Gogo* gogo_;
3592 // Implement the order of evaluation rules for a statement.
3595 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3597 // FIXME: This approach doesn't work for switch statements, because
3598 // we add the new statements before the whole switch when we need to
3599 // instead add them just before the switch expression. The right
3600 // fix is probably to lower switch statements with nonconstant cases
3601 // to a series of conditionals.
3602 if (stmt->switch_statement() != NULL)
3603 return TRAVERSE_CONTINUE;
3605 Find_eval_ordering find_eval_ordering;
3607 // If S is a variable declaration, then ordinary traversal won't do
3608 // anything. We want to explicitly traverse the initialization
3609 // expression if there is one.
3610 Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3611 Expression* init = NULL;
3612 Expression* orig_init = NULL;
3613 if (vds == NULL)
3614 stmt->traverse_contents(&find_eval_ordering);
3615 else
3617 init = vds->var()->var_value()->init();
3618 if (init == NULL)
3619 return TRAVERSE_CONTINUE;
3620 orig_init = init;
3622 // It might seem that this could be
3623 // init->traverse_subexpressions. Unfortunately that can fail
3624 // in a case like
3625 // var err os.Error
3626 // newvar, err := call(arg())
3627 // Here newvar will have an init of call result 0 of
3628 // call(arg()). If we only traverse subexpressions, we will
3629 // only find arg(), and we won't bother to move anything out.
3630 // Then we get to the assignment to err, we will traverse the
3631 // whole statement, and this time we will find both call() and
3632 // arg(), and so we will move them out. This will cause them to
3633 // be put into temporary variables before the assignment to err
3634 // but after the declaration of newvar. To avoid that problem,
3635 // we traverse the entire expression here.
3636 Expression::traverse(&init, &find_eval_ordering);
3639 size_t c = find_eval_ordering.size();
3640 if (c == 0)
3641 return TRAVERSE_CONTINUE;
3643 // If there is only one expression with a side-effect, we can
3644 // usually leave it in place.
3645 if (c == 1)
3647 switch (stmt->classification())
3649 case Statement::STATEMENT_ASSIGNMENT:
3650 // For an assignment statement, we need to evaluate an
3651 // expression on the right hand side before we evaluate any
3652 // index expression on the left hand side, so for that case
3653 // we always move the expression. Otherwise we mishandle
3654 // m[0] = len(m) where m is a map.
3655 break;
3657 case Statement::STATEMENT_EXPRESSION:
3659 // If this is a call statement that doesn't return any
3660 // values, it will not have been counted as a value to
3661 // move. We need to move any subexpressions in case they
3662 // are themselves call statements that require passing a
3663 // closure.
3664 Expression* expr = stmt->expression_statement()->expr();
3665 if (expr->call_expression() != NULL
3666 && expr->call_expression()->result_count() == 0)
3667 break;
3668 return TRAVERSE_CONTINUE;
3671 default:
3672 // We can leave the expression in place.
3673 return TRAVERSE_CONTINUE;
3677 bool is_thunk = stmt->thunk_statement() != NULL;
3678 Expression_statement* es = stmt->expression_statement();
3679 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3680 p != find_eval_ordering.end();
3681 ++p)
3683 Expression** pexpr = *p;
3685 // The last expression in a thunk will be the call passed to go
3686 // or defer, which we must not evaluate early.
3687 if (is_thunk && p + 1 == find_eval_ordering.end())
3688 break;
3690 Location loc = (*pexpr)->location();
3691 Statement* s;
3692 if ((*pexpr)->call_expression() == NULL
3693 || (*pexpr)->call_expression()->result_count() < 2)
3695 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3696 loc);
3697 s = ts;
3698 *pexpr = Expression::make_temporary_reference(ts, loc);
3700 else
3702 // A call expression which returns multiple results needs to
3703 // be handled specially. We can't create a temporary
3704 // because there is no type to give it. Any actual uses of
3705 // the values will be done via Call_result_expressions.
3707 // Since a given call expression can be shared by multiple
3708 // Call_result_expressions, avoid hoisting the call the
3709 // second time we see it here. In addition, don't try to
3710 // hoist the top-level multi-return call in the statement,
3711 // since doing this would result a tree with more than one copy
3712 // of the call.
3713 if (this->remember_expression(*pexpr))
3714 s = NULL;
3715 else if (es != NULL && *pexpr == es->expr())
3716 s = NULL;
3717 else
3718 s = Statement::make_statement(*pexpr, true);
3721 if (s != NULL)
3723 block->insert_statement_before(*pindex, s);
3724 ++*pindex;
3728 if (init != orig_init)
3729 vds->var()->var_value()->set_init(init);
3731 return TRAVERSE_CONTINUE;
3734 // Implement the order of evaluation rules for the initializer of a
3735 // global variable.
3738 Order_eval::variable(Named_object* no)
3740 if (no->is_result_variable())
3741 return TRAVERSE_CONTINUE;
3742 Variable* var = no->var_value();
3743 Expression* init = var->init();
3744 if (!var->is_global() || init == NULL)
3745 return TRAVERSE_CONTINUE;
3747 Find_eval_ordering find_eval_ordering;
3748 Expression::traverse(&init, &find_eval_ordering);
3750 if (find_eval_ordering.size() <= 1)
3752 // If there is only one expression with a side-effect, we can
3753 // leave it in place.
3754 return TRAVERSE_SKIP_COMPONENTS;
3757 Expression* orig_init = init;
3759 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3760 p != find_eval_ordering.end();
3761 ++p)
3763 Expression** pexpr = *p;
3764 Location loc = (*pexpr)->location();
3765 Statement* s;
3766 if ((*pexpr)->call_expression() == NULL
3767 || (*pexpr)->call_expression()->result_count() < 2)
3769 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3770 loc);
3771 s = ts;
3772 *pexpr = Expression::make_temporary_reference(ts, loc);
3774 else
3776 // A call expression which returns multiple results needs to
3777 // be handled specially.
3778 s = Statement::make_statement(*pexpr, true);
3780 var->add_preinit_statement(this->gogo_, s);
3783 if (init != orig_init)
3784 var->set_init(init);
3786 return TRAVERSE_SKIP_COMPONENTS;
3789 // Use temporary variables to implement the order of evaluation rules.
3791 void
3792 Gogo::order_evaluations()
3794 Order_eval order_eval(this);
3795 this->traverse(&order_eval);
3798 // A traversal class used to find a single shortcut operator within an
3799 // expression.
3801 class Find_shortcut : public Traverse
3803 public:
3804 Find_shortcut()
3805 : Traverse(traverse_blocks
3806 | traverse_statements
3807 | traverse_expressions),
3808 found_(NULL)
3811 // A pointer to the expression which was found, or NULL if none was
3812 // found.
3813 Expression**
3814 found() const
3815 { return this->found_; }
3817 protected:
3819 block(Block*)
3820 { return TRAVERSE_SKIP_COMPONENTS; }
3823 statement(Block*, size_t*, Statement*)
3824 { return TRAVERSE_SKIP_COMPONENTS; }
3827 expression(Expression**);
3829 private:
3830 Expression** found_;
3833 // Find a shortcut expression.
3836 Find_shortcut::expression(Expression** pexpr)
3838 Expression* expr = *pexpr;
3839 Binary_expression* be = expr->binary_expression();
3840 if (be == NULL)
3841 return TRAVERSE_CONTINUE;
3842 Operator op = be->op();
3843 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
3844 return TRAVERSE_CONTINUE;
3845 go_assert(this->found_ == NULL);
3846 this->found_ = pexpr;
3847 return TRAVERSE_EXIT;
3850 // A traversal class used to turn shortcut operators into explicit if
3851 // statements.
3853 class Shortcuts : public Traverse
3855 public:
3856 Shortcuts(Gogo* gogo)
3857 : Traverse(traverse_variables
3858 | traverse_statements),
3859 gogo_(gogo)
3862 protected:
3864 variable(Named_object*);
3867 statement(Block*, size_t*, Statement*);
3869 private:
3870 // Convert a shortcut operator.
3871 Statement*
3872 convert_shortcut(Block* enclosing, Expression** pshortcut);
3874 // The IR.
3875 Gogo* gogo_;
3878 // Remove shortcut operators in a single statement.
3881 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
3883 // FIXME: This approach doesn't work for switch statements, because
3884 // we add the new statements before the whole switch when we need to
3885 // instead add them just before the switch expression. The right
3886 // fix is probably to lower switch statements with nonconstant cases
3887 // to a series of conditionals.
3888 if (s->switch_statement() != NULL)
3889 return TRAVERSE_CONTINUE;
3891 while (true)
3893 Find_shortcut find_shortcut;
3895 // If S is a variable declaration, then ordinary traversal won't
3896 // do anything. We want to explicitly traverse the
3897 // initialization expression if there is one.
3898 Variable_declaration_statement* vds = s->variable_declaration_statement();
3899 Expression* init = NULL;
3900 if (vds == NULL)
3901 s->traverse_contents(&find_shortcut);
3902 else
3904 init = vds->var()->var_value()->init();
3905 if (init == NULL)
3906 return TRAVERSE_CONTINUE;
3907 init->traverse(&init, &find_shortcut);
3909 Expression** pshortcut = find_shortcut.found();
3910 if (pshortcut == NULL)
3911 return TRAVERSE_CONTINUE;
3913 Statement* snew = this->convert_shortcut(block, pshortcut);
3914 block->insert_statement_before(*pindex, snew);
3915 ++*pindex;
3917 if (pshortcut == &init)
3918 vds->var()->var_value()->set_init(init);
3922 // Remove shortcut operators in the initializer of a global variable.
3925 Shortcuts::variable(Named_object* no)
3927 if (no->is_result_variable())
3928 return TRAVERSE_CONTINUE;
3929 Variable* var = no->var_value();
3930 Expression* init = var->init();
3931 if (!var->is_global() || init == NULL)
3932 return TRAVERSE_CONTINUE;
3934 while (true)
3936 Find_shortcut find_shortcut;
3937 init->traverse(&init, &find_shortcut);
3938 Expression** pshortcut = find_shortcut.found();
3939 if (pshortcut == NULL)
3940 return TRAVERSE_CONTINUE;
3942 Statement* snew = this->convert_shortcut(NULL, pshortcut);
3943 var->add_preinit_statement(this->gogo_, snew);
3944 if (pshortcut == &init)
3945 var->set_init(init);
3949 // Given an expression which uses a shortcut operator, return a
3950 // statement which implements it, and update *PSHORTCUT accordingly.
3952 Statement*
3953 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
3955 Binary_expression* shortcut = (*pshortcut)->binary_expression();
3956 Expression* left = shortcut->left();
3957 Expression* right = shortcut->right();
3958 Location loc = shortcut->location();
3960 Block* retblock = new Block(enclosing, loc);
3961 retblock->set_end_location(loc);
3963 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
3964 left, loc);
3965 retblock->add_statement(ts);
3967 Block* block = new Block(retblock, loc);
3968 block->set_end_location(loc);
3969 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
3970 Statement* assign = Statement::make_assignment(tmpref, right, loc);
3971 block->add_statement(assign);
3973 Expression* cond = Expression::make_temporary_reference(ts, loc);
3974 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
3975 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3977 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
3978 loc);
3979 retblock->add_statement(if_statement);
3981 *pshortcut = Expression::make_temporary_reference(ts, loc);
3983 delete shortcut;
3985 // Now convert any shortcut operators in LEFT and RIGHT.
3986 // LEFT and RIGHT were skipped in the top level
3987 // Gogo::order_evaluations. We need to order their
3988 // components first.
3989 Order_eval order_eval(this->gogo_);
3990 retblock->traverse(&order_eval);
3991 Shortcuts shortcuts(this->gogo_);
3992 retblock->traverse(&shortcuts);
3994 return Statement::make_block_statement(retblock, loc);
3997 // Turn shortcut operators into explicit if statements. Doing this
3998 // considerably simplifies the order of evaluation rules.
4000 void
4001 Gogo::remove_shortcuts()
4003 Shortcuts shortcuts(this);
4004 this->traverse(&shortcuts);
4007 // Traversal to flatten parse tree after order of evaluation rules are applied.
4009 class Flatten : public Traverse
4011 public:
4012 Flatten(Gogo* gogo, Named_object* function)
4013 : Traverse(traverse_variables
4014 | traverse_functions
4015 | traverse_statements
4016 | traverse_expressions),
4017 gogo_(gogo), function_(function), inserter_()
4020 void
4021 set_inserter(const Statement_inserter* inserter)
4022 { this->inserter_ = *inserter; }
4025 variable(Named_object*);
4028 function(Named_object*);
4031 statement(Block*, size_t* pindex, Statement*);
4034 expression(Expression**);
4036 private:
4037 // General IR.
4038 Gogo* gogo_;
4039 // The function we are traversing.
4040 Named_object* function_;
4041 // Current statement inserter for use by expressions.
4042 Statement_inserter inserter_;
4045 // Flatten variables.
4048 Flatten::variable(Named_object* no)
4050 if (!no->is_variable())
4051 return TRAVERSE_CONTINUE;
4053 if (no->is_variable() && no->var_value()->is_global())
4055 // Global variables can have loops in their initialization
4056 // expressions. This is handled in flatten_init_expression.
4057 no->var_value()->flatten_init_expression(this->gogo_, this->function_,
4058 &this->inserter_);
4059 return TRAVERSE_CONTINUE;
4062 if (!no->var_value()->is_parameter()
4063 && !no->var_value()->is_receiver()
4064 && !no->var_value()->is_closure()
4065 && no->var_value()->is_non_escaping_address_taken()
4066 && !no->var_value()->is_in_heap()
4067 && no->var_value()->toplevel_decl() == NULL)
4069 // Local variable that has address taken but not escape.
4070 // It needs to be live beyond its lexical scope. So we
4071 // create a top-level declaration for it.
4072 // No need to do it if it is already in the top level.
4073 Block* top_block = function_->func_value()->block();
4074 if (top_block->bindings()->lookup_local(no->name()) != no)
4076 Variable* var = no->var_value();
4077 Temporary_statement* ts =
4078 Statement::make_temporary(var->type(), NULL, var->location());
4079 ts->set_is_address_taken();
4080 top_block->add_statement_at_front(ts);
4081 var->set_toplevel_decl(ts);
4085 go_assert(!no->var_value()->has_pre_init());
4087 return TRAVERSE_SKIP_COMPONENTS;
4090 // Flatten the body of a function. Record the function while flattening it,
4091 // so that we can pass it down when flattening an expression.
4094 Flatten::function(Named_object* no)
4096 go_assert(this->function_ == NULL);
4097 this->function_ = no;
4098 int t = no->func_value()->traverse(this);
4099 this->function_ = NULL;
4101 if (t == TRAVERSE_EXIT)
4102 return t;
4103 return TRAVERSE_SKIP_COMPONENTS;
4106 // Flatten statement parse trees.
4109 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
4111 // Because we explicitly traverse the statement's contents
4112 // ourselves, we want to skip block statements here. There is
4113 // nothing to flatten in a block statement.
4114 if (sorig->is_block_statement())
4115 return TRAVERSE_CONTINUE;
4117 Statement_inserter hold_inserter(this->inserter_);
4118 this->inserter_ = Statement_inserter(block, pindex);
4120 // Flatten the expressions first.
4121 int t = sorig->traverse_contents(this);
4122 if (t == TRAVERSE_EXIT)
4124 this->inserter_ = hold_inserter;
4125 return t;
4128 // Keep flattening until nothing changes.
4129 Statement* s = sorig;
4130 while (true)
4132 Statement* snew = s->flatten(this->gogo_, this->function_, block,
4133 &this->inserter_);
4134 if (snew == s)
4135 break;
4136 s = snew;
4137 t = s->traverse_contents(this);
4138 if (t == TRAVERSE_EXIT)
4140 this->inserter_ = hold_inserter;
4141 return t;
4145 if (s != sorig)
4146 block->replace_statement(*pindex, s);
4148 this->inserter_ = hold_inserter;
4149 return TRAVERSE_SKIP_COMPONENTS;
4152 // Flatten expression parse trees.
4155 Flatten::expression(Expression** pexpr)
4157 // Keep flattening until nothing changes.
4158 while (true)
4160 Expression* e = *pexpr;
4161 if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
4162 return TRAVERSE_EXIT;
4164 Expression* enew = e->flatten(this->gogo_, this->function_,
4165 &this->inserter_);
4166 if (enew == e)
4167 break;
4168 *pexpr = enew;
4170 return TRAVERSE_SKIP_COMPONENTS;
4173 // Flatten a block.
4175 void
4176 Gogo::flatten_block(Named_object* function, Block* block)
4178 Flatten flatten(this, function);
4179 block->traverse(&flatten);
4182 // Flatten an expression. INSERTER may be NULL, in which case the
4183 // expression had better not need to create any temporaries.
4185 void
4186 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
4187 Expression** pexpr)
4189 Flatten flatten(this, function);
4190 if (inserter != NULL)
4191 flatten.set_inserter(inserter);
4192 flatten.expression(pexpr);
4195 void
4196 Gogo::flatten()
4198 Flatten flatten(this, NULL);
4199 this->traverse(&flatten);
4202 // Traversal to convert calls to the predeclared recover function to
4203 // pass in an argument indicating whether it can recover from a panic
4204 // or not.
4206 class Convert_recover : public Traverse
4208 public:
4209 Convert_recover(Named_object* arg)
4210 : Traverse(traverse_expressions),
4211 arg_(arg)
4214 protected:
4216 expression(Expression**);
4218 private:
4219 // The argument to pass to the function.
4220 Named_object* arg_;
4223 // Convert calls to recover.
4226 Convert_recover::expression(Expression** pp)
4228 Call_expression* ce = (*pp)->call_expression();
4229 if (ce != NULL && ce->is_recover_call())
4230 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4231 ce->location()));
4232 return TRAVERSE_CONTINUE;
4235 // Traversal for build_recover_thunks.
4237 class Build_recover_thunks : public Traverse
4239 public:
4240 Build_recover_thunks(Gogo* gogo)
4241 : Traverse(traverse_functions),
4242 gogo_(gogo)
4246 function(Named_object*);
4248 private:
4249 Expression*
4250 can_recover_arg(Location);
4252 // General IR.
4253 Gogo* gogo_;
4256 // If this function calls recover, turn it into a thunk.
4259 Build_recover_thunks::function(Named_object* orig_no)
4261 Function* orig_func = orig_no->func_value();
4262 if (!orig_func->calls_recover()
4263 || orig_func->is_recover_thunk()
4264 || orig_func->has_recover_thunk())
4265 return TRAVERSE_CONTINUE;
4267 Gogo* gogo = this->gogo_;
4268 Location location = orig_func->location();
4270 static int count;
4271 char buf[50];
4273 Function_type* orig_fntype = orig_func->type();
4274 Typed_identifier_list* new_params = new Typed_identifier_list();
4275 std::string receiver_name;
4276 if (orig_fntype->is_method())
4278 const Typed_identifier* receiver = orig_fntype->receiver();
4279 snprintf(buf, sizeof buf, "rt.%u", count);
4280 ++count;
4281 receiver_name = buf;
4282 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4283 receiver->location()));
4285 const Typed_identifier_list* orig_params = orig_fntype->parameters();
4286 if (orig_params != NULL && !orig_params->empty())
4288 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4289 p != orig_params->end();
4290 ++p)
4292 snprintf(buf, sizeof buf, "pt.%u", count);
4293 ++count;
4294 new_params->push_back(Typed_identifier(buf, p->type(),
4295 p->location()));
4298 snprintf(buf, sizeof buf, "pr.%u", count);
4299 ++count;
4300 std::string can_recover_name = buf;
4301 new_params->push_back(Typed_identifier(can_recover_name,
4302 Type::lookup_bool_type(),
4303 orig_fntype->location()));
4305 const Typed_identifier_list* orig_results = orig_fntype->results();
4306 Typed_identifier_list* new_results;
4307 if (orig_results == NULL || orig_results->empty())
4308 new_results = NULL;
4309 else
4311 new_results = new Typed_identifier_list();
4312 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4313 p != orig_results->end();
4314 ++p)
4315 new_results->push_back(Typed_identifier("", p->type(), p->location()));
4318 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4319 new_results,
4320 orig_fntype->location());
4321 if (orig_fntype->is_varargs())
4322 new_fntype->set_is_varargs();
4324 Type* rtype = NULL;
4325 if (orig_fntype->is_method())
4326 rtype = orig_fntype->receiver()->type();
4327 std::string name(gogo->recover_thunk_name(orig_no->name(), rtype));
4328 Named_object *new_no = gogo->start_function(name, new_fntype, false,
4329 location);
4330 Function *new_func = new_no->func_value();
4331 if (orig_func->enclosing() != NULL)
4332 new_func->set_enclosing(orig_func->enclosing());
4334 // We build the code for the original function attached to the new
4335 // function, and then swap the original and new function bodies.
4336 // This means that existing references to the original function will
4337 // then refer to the new function. That makes this code a little
4338 // confusing, in that the reference to NEW_NO really refers to the
4339 // other function, not the one we are building.
4341 Expression* closure = NULL;
4342 if (orig_func->needs_closure())
4344 // For the new function we are creating, declare a new parameter
4345 // variable NEW_CLOSURE_NO and set it to be the closure variable
4346 // of the function. This will be set to the closure value
4347 // passed in by the caller. Then pass a reference to this
4348 // variable as the closure value when calling the original
4349 // function. In other words, simply pass the closure value
4350 // through the thunk we are creating.
4351 Named_object* orig_closure_no = orig_func->closure_var();
4352 Variable* orig_closure_var = orig_closure_no->var_value();
4353 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4354 false, false, location);
4355 new_var->set_is_closure();
4356 snprintf(buf, sizeof buf, "closure.%u", count);
4357 ++count;
4358 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4359 new_var);
4360 new_func->set_closure_var(new_closure_no);
4361 closure = Expression::make_var_reference(new_closure_no, location);
4364 Expression* fn = Expression::make_func_reference(new_no, closure, location);
4366 Expression_list* args = new Expression_list();
4367 if (new_params != NULL)
4369 // Note that we skip the last parameter, which is the boolean
4370 // indicating whether recover can succed.
4371 for (Typed_identifier_list::const_iterator p = new_params->begin();
4372 p + 1 != new_params->end();
4373 ++p)
4375 Named_object* p_no = gogo->lookup(p->name(), NULL);
4376 go_assert(p_no != NULL
4377 && p_no->is_variable()
4378 && p_no->var_value()->is_parameter());
4379 args->push_back(Expression::make_var_reference(p_no, location));
4382 args->push_back(this->can_recover_arg(location));
4384 gogo->start_block(location);
4386 Call_expression* call = Expression::make_call(fn, args, false, location);
4388 // Any varargs call has already been lowered.
4389 call->set_varargs_are_lowered();
4391 Statement* s = Statement::make_return_from_call(call, location);
4392 s->determine_types();
4393 gogo->add_statement(s);
4395 Block* b = gogo->finish_block(location);
4397 gogo->add_block(b, location);
4399 // Lower the call in case it returns multiple results.
4400 gogo->lower_block(new_no, b);
4402 gogo->finish_function(location);
4404 // Swap the function bodies and types.
4405 new_func->swap_for_recover(orig_func);
4406 orig_func->set_is_recover_thunk();
4407 new_func->set_calls_recover();
4408 new_func->set_has_recover_thunk();
4410 Bindings* orig_bindings = orig_func->block()->bindings();
4411 Bindings* new_bindings = new_func->block()->bindings();
4412 if (orig_fntype->is_method())
4414 // We changed the receiver to be a regular parameter. We have
4415 // to update the binding accordingly in both functions.
4416 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4417 go_assert(orig_rec_no != NULL
4418 && orig_rec_no->is_variable()
4419 && !orig_rec_no->var_value()->is_receiver());
4420 orig_rec_no->var_value()->set_is_receiver();
4422 std::string new_receiver_name(orig_fntype->receiver()->name());
4423 if (new_receiver_name.empty())
4425 // Find the receiver. It was named "r.NNN" in
4426 // Gogo::start_function.
4427 for (Bindings::const_definitions_iterator p =
4428 new_bindings->begin_definitions();
4429 p != new_bindings->end_definitions();
4430 ++p)
4432 const std::string& pname((*p)->name());
4433 if (pname[0] == 'r' && pname[1] == '.')
4435 new_receiver_name = pname;
4436 break;
4439 go_assert(!new_receiver_name.empty());
4441 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4442 if (new_rec_no == NULL)
4443 go_assert(saw_errors());
4444 else
4446 go_assert(new_rec_no->is_variable()
4447 && new_rec_no->var_value()->is_receiver());
4448 new_rec_no->var_value()->set_is_not_receiver();
4452 // Because we flipped blocks but not types, the can_recover
4453 // parameter appears in the (now) old bindings as a parameter.
4454 // Change it to a local variable, whereupon it will be discarded.
4455 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4456 go_assert(can_recover_no != NULL
4457 && can_recover_no->is_variable()
4458 && can_recover_no->var_value()->is_parameter());
4459 orig_bindings->remove_binding(can_recover_no);
4461 // Add the can_recover argument to the (now) new bindings, and
4462 // attach it to any recover statements.
4463 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4464 false, true, false, location);
4465 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4466 can_recover_var);
4467 Convert_recover convert_recover(can_recover_no);
4468 new_func->traverse(&convert_recover);
4470 // Update the function pointers in any named results.
4471 new_func->update_result_variables();
4472 orig_func->update_result_variables();
4474 return TRAVERSE_CONTINUE;
4477 // Return the expression to pass for the .can_recover parameter to the
4478 // new function. This indicates whether a call to recover may return
4479 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4481 Expression*
4482 Build_recover_thunks::can_recover_arg(Location location)
4484 static Named_object* builtin_return_address;
4485 if (builtin_return_address == NULL)
4486 builtin_return_address =
4487 Gogo::declare_builtin_rf_address("__builtin_return_address");
4489 static Named_object* can_recover;
4490 if (can_recover == NULL)
4492 const Location bloc = Linemap::predeclared_location();
4493 Typed_identifier_list* param_types = new Typed_identifier_list();
4494 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4495 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
4496 Type* boolean_type = Type::lookup_bool_type();
4497 Typed_identifier_list* results = new Typed_identifier_list();
4498 results->push_back(Typed_identifier("", boolean_type, bloc));
4499 Function_type* fntype = Type::make_function_type(NULL, param_types,
4500 results, bloc);
4501 can_recover =
4502 Named_object::make_function_declaration("runtime_canrecover",
4503 NULL, fntype, bloc);
4504 can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4507 Expression* fn = Expression::make_func_reference(builtin_return_address,
4508 NULL, location);
4510 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4511 Expression_list *args = new Expression_list();
4512 args->push_back(zexpr);
4514 Expression* call = Expression::make_call(fn, args, false, location);
4516 args = new Expression_list();
4517 args->push_back(call);
4519 fn = Expression::make_func_reference(can_recover, NULL, location);
4520 return Expression::make_call(fn, args, false, location);
4523 // Build thunks for functions which call recover. We build a new
4524 // function with an extra parameter, which is whether a call to
4525 // recover can succeed. We then move the body of this function to
4526 // that one. We then turn this function into a thunk which calls the
4527 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4528 // The function will be marked as not splitting the stack. This will
4529 // cooperate with the implementation of defer to make recover do the
4530 // right thing.
4532 void
4533 Gogo::build_recover_thunks()
4535 Build_recover_thunks build_recover_thunks(this);
4536 this->traverse(&build_recover_thunks);
4539 // Return a declaration for __builtin_return_address or
4540 // __builtin_frame_address.
4542 Named_object*
4543 Gogo::declare_builtin_rf_address(const char* name)
4545 const Location bloc = Linemap::predeclared_location();
4547 Typed_identifier_list* param_types = new Typed_identifier_list();
4548 Type* uint32_type = Type::lookup_integer_type("uint32");
4549 param_types->push_back(Typed_identifier("l", uint32_type, bloc));
4551 Typed_identifier_list* return_types = new Typed_identifier_list();
4552 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4553 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
4555 Function_type* fntype = Type::make_function_type(NULL, param_types,
4556 return_types, bloc);
4557 Named_object* ret = Named_object::make_function_declaration(name, NULL,
4558 fntype, bloc);
4559 ret->func_declaration_value()->set_asm_name(name);
4560 return ret;
4563 // Build a call to the runtime error function.
4565 Expression*
4566 Gogo::runtime_error(int code, Location location)
4568 Type* int32_type = Type::lookup_integer_type("int32");
4569 Expression* code_expr = Expression::make_integer_ul(code, int32_type,
4570 location);
4571 return Runtime::make_call(Runtime::RUNTIME_ERROR, location, 1, code_expr);
4574 // Look for named types to see whether we need to create an interface
4575 // method table.
4577 class Build_method_tables : public Traverse
4579 public:
4580 Build_method_tables(Gogo* gogo,
4581 const std::vector<Interface_type*>& interfaces)
4582 : Traverse(traverse_types),
4583 gogo_(gogo), interfaces_(interfaces)
4587 type(Type*);
4589 private:
4590 // The IR.
4591 Gogo* gogo_;
4592 // A list of locally defined interfaces which have hidden methods.
4593 const std::vector<Interface_type*>& interfaces_;
4596 // Build all required interface method tables for types. We need to
4597 // ensure that we have an interface method table for every interface
4598 // which has a hidden method, for every named type which implements
4599 // that interface. Normally we can just build interface method tables
4600 // as we need them. However, in some cases we can require an
4601 // interface method table for an interface defined in a different
4602 // package for a type defined in that package. If that interface and
4603 // type both use a hidden method, that is OK. However, we will not be
4604 // able to build that interface method table when we need it, because
4605 // the type's hidden method will be static. So we have to build it
4606 // here, and just refer it from other packages as needed.
4608 void
4609 Gogo::build_interface_method_tables()
4611 if (saw_errors())
4612 return;
4614 std::vector<Interface_type*> hidden_interfaces;
4615 hidden_interfaces.reserve(this->interface_types_.size());
4616 for (std::vector<Interface_type*>::const_iterator pi =
4617 this->interface_types_.begin();
4618 pi != this->interface_types_.end();
4619 ++pi)
4621 const Typed_identifier_list* methods = (*pi)->methods();
4622 if (methods == NULL)
4623 continue;
4624 for (Typed_identifier_list::const_iterator pm = methods->begin();
4625 pm != methods->end();
4626 ++pm)
4628 if (Gogo::is_hidden_name(pm->name()))
4630 hidden_interfaces.push_back(*pi);
4631 break;
4636 if (!hidden_interfaces.empty())
4638 // Now traverse the tree looking for all named types.
4639 Build_method_tables bmt(this, hidden_interfaces);
4640 this->traverse(&bmt);
4643 // We no longer need the list of interfaces.
4645 this->interface_types_.clear();
4648 // This is called for each type. For a named type, for each of the
4649 // interfaces with hidden methods that it implements, create the
4650 // method table.
4653 Build_method_tables::type(Type* type)
4655 Named_type* nt = type->named_type();
4656 Struct_type* st = type->struct_type();
4657 if (nt != NULL || st != NULL)
4659 Translate_context context(this->gogo_, NULL, NULL, NULL);
4660 for (std::vector<Interface_type*>::const_iterator p =
4661 this->interfaces_.begin();
4662 p != this->interfaces_.end();
4663 ++p)
4665 // We ask whether a pointer to the named type implements the
4666 // interface, because a pointer can implement more methods
4667 // than a value.
4668 if (nt != NULL)
4670 if ((*p)->implements_interface(Type::make_pointer_type(nt),
4671 NULL))
4673 nt->interface_method_table(*p, false)->get_backend(&context);
4674 nt->interface_method_table(*p, true)->get_backend(&context);
4677 else
4679 if ((*p)->implements_interface(Type::make_pointer_type(st),
4680 NULL))
4682 st->interface_method_table(*p, false)->get_backend(&context);
4683 st->interface_method_table(*p, true)->get_backend(&context);
4688 return TRAVERSE_CONTINUE;
4691 // Return an expression which allocates memory to hold values of type TYPE.
4693 Expression*
4694 Gogo::allocate_memory(Type* type, Location location)
4696 Expression* td = Expression::make_type_descriptor(type, location);
4697 return Runtime::make_call(Runtime::NEW, location, 1, td);
4700 // Traversal class used to check for return statements.
4702 class Check_return_statements_traverse : public Traverse
4704 public:
4705 Check_return_statements_traverse()
4706 : Traverse(traverse_functions)
4710 function(Named_object*);
4713 // Check that a function has a return statement if it needs one.
4716 Check_return_statements_traverse::function(Named_object* no)
4718 Function* func = no->func_value();
4719 const Function_type* fntype = func->type();
4720 const Typed_identifier_list* results = fntype->results();
4722 // We only need a return statement if there is a return value.
4723 if (results == NULL || results->empty())
4724 return TRAVERSE_CONTINUE;
4726 if (func->block()->may_fall_through())
4727 go_error_at(func->block()->end_location(),
4728 "missing return at end of function");
4730 return TRAVERSE_CONTINUE;
4733 // Check return statements.
4735 void
4736 Gogo::check_return_statements()
4738 Check_return_statements_traverse traverse;
4739 this->traverse(&traverse);
4742 // Traversal class to decide whether a function body is less than the
4743 // inlining budget. This adjusts *available as it goes, and stops the
4744 // traversal if it goes negative.
4746 class Inline_within_budget : public Traverse
4748 public:
4749 Inline_within_budget(int* available)
4750 : Traverse(traverse_statements
4751 | traverse_expressions),
4752 available_(available)
4756 statement(Block*, size_t*, Statement*);
4759 expression(Expression**);
4761 private:
4762 // Pointer to remaining budget.
4763 int* available_;
4766 // Adjust the budget for the inlining cost of a statement.
4769 Inline_within_budget::statement(Block*, size_t*, Statement* s)
4771 if (*this->available_ < 0)
4772 return TRAVERSE_EXIT;
4773 *this->available_ -= s->inlining_cost();
4774 return TRAVERSE_CONTINUE;
4777 // Adjust the budget for the inlining cost of an expression.
4780 Inline_within_budget::expression(Expression** pexpr)
4782 if (*this->available_ < 0)
4783 return TRAVERSE_EXIT;
4784 *this->available_ -= (*pexpr)->inlining_cost();
4785 return TRAVERSE_CONTINUE;
4788 // Traversal class to find functions whose body should be exported for
4789 // inlining by other packages.
4791 class Mark_inline_candidates : public Traverse
4793 public:
4794 Mark_inline_candidates()
4795 : Traverse(traverse_functions
4796 | traverse_types)
4800 function(Named_object*);
4803 type(Type*);
4805 private:
4806 // We traverse the function body trying to determine how expensive
4807 // it is for inlining. We start with a budget, and decrease that
4808 // budget for each statement and expression. If the budget goes
4809 // negative, we do not export the function body. The value of this
4810 // budget is a heuristic. In the usual GCC spirit, we could
4811 // consider setting this via a command line option.
4812 const int budget_heuristic = 80;
4815 // Mark a function if it is an inline candidate.
4818 Mark_inline_candidates::function(Named_object* no)
4820 Function* func = no->func_value();
4821 int budget = budget_heuristic;
4822 Inline_within_budget iwb(&budget);
4823 func->block()->traverse(&iwb);
4824 if (budget >= 0)
4825 func->set_export_for_inlining();
4826 return TRAVERSE_CONTINUE;
4829 // Mark methods if they are inline candidates.
4832 Mark_inline_candidates::type(Type* t)
4834 Named_type* nt = t->named_type();
4835 if (nt == NULL || nt->is_alias())
4836 return TRAVERSE_CONTINUE;
4837 const Bindings* methods = nt->local_methods();
4838 if (methods == NULL)
4839 return TRAVERSE_CONTINUE;
4840 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
4841 p != methods->end_definitions();
4842 ++p)
4844 Named_object* no = *p;
4845 go_assert(no->is_function());
4846 Function *func = no->func_value();
4847 int budget = budget_heuristic;
4848 Inline_within_budget iwb(&budget);
4849 func->block()->traverse(&iwb);
4850 if (budget >= 0)
4851 func->set_export_for_inlining();
4853 return TRAVERSE_CONTINUE;
4856 // Export identifiers as requested.
4858 void
4859 Gogo::do_exports()
4861 // Mark any functions whose body should be exported for inlining by
4862 // other packages.
4863 Mark_inline_candidates mic;
4864 this->traverse(&mic);
4866 // For now we always stream to a section. Later we may want to
4867 // support streaming to a separate file.
4868 Stream_to_section stream(this->backend());
4870 // Write out either the prefix or pkgpath depending on how we were
4871 // invoked.
4872 std::string prefix;
4873 std::string pkgpath;
4874 if (this->pkgpath_from_option_)
4875 pkgpath = this->pkgpath_;
4876 else if (this->prefix_from_option_)
4877 prefix = this->prefix_;
4878 else if (this->is_main_package())
4879 pkgpath = "main";
4880 else
4881 prefix = "go";
4883 Export exp(&stream);
4884 exp.register_builtin_types(this);
4885 exp.export_globals(this->package_name(),
4886 prefix,
4887 pkgpath,
4888 this->packages_,
4889 this->imports_,
4890 (this->need_init_fn_ && !this->is_main_package()
4891 ? this->get_init_fn_name()
4892 : ""),
4893 this->imported_init_fns_,
4894 this->package_->bindings());
4896 if (!this->c_header_.empty() && !saw_errors())
4897 this->write_c_header();
4900 // Write the top level named struct types in C format to a C header
4901 // file. This is used when building the runtime package, to share
4902 // struct definitions between C and Go.
4904 void
4905 Gogo::write_c_header()
4907 std::ofstream out;
4908 out.open(this->c_header_.c_str());
4909 if (out.fail())
4911 go_error_at(Linemap::unknown_location(),
4912 "cannot open %s: %m", this->c_header_.c_str());
4913 return;
4916 std::list<Named_object*> types;
4917 Bindings* top = this->package_->bindings();
4918 for (Bindings::const_definitions_iterator p = top->begin_definitions();
4919 p != top->end_definitions();
4920 ++p)
4922 Named_object* no = *p;
4924 // Skip names that start with underscore followed by something
4925 // other than an uppercase letter, as when compiling the runtime
4926 // package they are mostly types defined by mkrsysinfo.sh based
4927 // on the C system header files. We don't need to translate
4928 // types to C and back to Go. But do accept the special cases
4929 // _defer and _panic.
4930 std::string name = Gogo::unpack_hidden_name(no->name());
4931 if (name[0] == '_'
4932 && (name[1] < 'A' || name[1] > 'Z')
4933 && (name != "_defer" && name != "_panic"))
4934 continue;
4936 if (no->is_type() && no->type_value()->struct_type() != NULL)
4937 types.push_back(no);
4938 if (no->is_const()
4939 && no->const_value()->type()->integer_type() != NULL
4940 && !no->const_value()->is_sink())
4942 Numeric_constant nc;
4943 unsigned long val;
4944 if (no->const_value()->expr()->numeric_constant_value(&nc)
4945 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
4947 out << "#define " << no->message_name() << ' ' << val
4948 << std::endl;
4953 std::vector<const Named_object*> written;
4954 int loop = 0;
4955 while (!types.empty())
4957 Named_object* no = types.front();
4958 types.pop_front();
4960 std::vector<const Named_object*> requires;
4961 std::vector<const Named_object*> declare;
4962 if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
4963 &declare))
4964 continue;
4966 bool ok = true;
4967 for (std::vector<const Named_object*>::const_iterator pr
4968 = requires.begin();
4969 pr != requires.end() && ok;
4970 ++pr)
4972 for (std::list<Named_object*>::const_iterator pt = types.begin();
4973 pt != types.end() && ok;
4974 ++pt)
4975 if (*pr == *pt)
4976 ok = false;
4978 if (!ok)
4980 ++loop;
4981 if (loop > 10000)
4983 // This should be impossible since the code parsed and
4984 // type checked.
4985 go_unreachable();
4988 types.push_back(no);
4989 continue;
4992 for (std::vector<const Named_object*>::const_iterator pd
4993 = declare.begin();
4994 pd != declare.end();
4995 ++pd)
4997 if (*pd == no)
4998 continue;
5000 std::vector<const Named_object*> drequires;
5001 std::vector<const Named_object*> ddeclare;
5002 if (!(*pd)->type_value()->struct_type()->
5003 can_write_to_c_header(&drequires, &ddeclare))
5004 continue;
5006 bool done = false;
5007 for (std::vector<const Named_object*>::const_iterator pw
5008 = written.begin();
5009 pw != written.end();
5010 ++pw)
5012 if (*pw == *pd)
5014 done = true;
5015 break;
5018 if (!done)
5020 out << std::endl;
5021 out << "struct " << (*pd)->message_name() << ";" << std::endl;
5022 written.push_back(*pd);
5026 out << std::endl;
5027 out << "struct " << no->message_name() << " {" << std::endl;
5028 no->type_value()->struct_type()->write_to_c_header(out);
5029 out << "};" << std::endl;
5030 written.push_back(no);
5033 out.close();
5034 if (out.fail())
5035 go_error_at(Linemap::unknown_location(),
5036 "error writing to %s: %m", this->c_header_.c_str());
5039 // Find the blocks in order to convert named types defined in blocks.
5041 class Convert_named_types : public Traverse
5043 public:
5044 Convert_named_types(Gogo* gogo)
5045 : Traverse(traverse_blocks),
5046 gogo_(gogo)
5049 protected:
5051 block(Block* block);
5053 private:
5054 Gogo* gogo_;
5058 Convert_named_types::block(Block* block)
5060 this->gogo_->convert_named_types_in_bindings(block->bindings());
5061 return TRAVERSE_CONTINUE;
5064 // Convert all named types to the backend representation. Since named
5065 // types can refer to other types, this needs to be done in the right
5066 // sequence, which is handled by Named_type::convert. Here we arrange
5067 // to call that for each named type.
5069 void
5070 Gogo::convert_named_types()
5072 this->convert_named_types_in_bindings(this->globals_);
5073 for (Packages::iterator p = this->packages_.begin();
5074 p != this->packages_.end();
5075 ++p)
5077 Package* package = p->second;
5078 this->convert_named_types_in_bindings(package->bindings());
5081 Convert_named_types cnt(this);
5082 this->traverse(&cnt);
5084 // Make all the builtin named types used for type descriptors, and
5085 // then convert them. They will only be written out if they are
5086 // needed.
5087 Type::make_type_descriptor_type();
5088 Type::make_type_descriptor_ptr_type();
5089 Function_type::make_function_type_descriptor_type();
5090 Pointer_type::make_pointer_type_descriptor_type();
5091 Struct_type::make_struct_type_descriptor_type();
5092 Array_type::make_array_type_descriptor_type();
5093 Array_type::make_slice_type_descriptor_type();
5094 Map_type::make_map_type_descriptor_type();
5095 Channel_type::make_chan_type_descriptor_type();
5096 Interface_type::make_interface_type_descriptor_type();
5097 Expression::make_func_descriptor_type();
5098 Type::convert_builtin_named_types(this);
5100 Runtime::convert_types(this);
5102 this->named_types_are_converted_ = true;
5104 Type::finish_pointer_types(this);
5107 // Convert all names types in a set of bindings.
5109 void
5110 Gogo::convert_named_types_in_bindings(Bindings* bindings)
5112 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5113 p != bindings->end_definitions();
5114 ++p)
5116 if ((*p)->is_type())
5117 (*p)->type_value()->convert(this);
5121 // Class Function.
5123 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
5124 Location location)
5125 : type_(type), enclosing_(enclosing), results_(NULL),
5126 closure_var_(NULL), block_(block), location_(location), labels_(),
5127 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
5128 pragmas_(0), nested_functions_(0), is_sink_(false),
5129 results_are_named_(false), is_unnamed_type_stub_method_(false),
5130 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5131 calls_defer_retaddr_(false), is_type_specific_function_(false),
5132 in_unique_section_(false), export_for_inlining_(false),
5133 is_inline_only_(false)
5137 // Create the named result variables.
5139 void
5140 Function::create_result_variables(Gogo* gogo)
5142 const Typed_identifier_list* results = this->type_->results();
5143 if (results == NULL || results->empty())
5144 return;
5146 if (!results->front().name().empty())
5147 this->results_are_named_ = true;
5149 this->results_ = new Results();
5150 this->results_->reserve(results->size());
5152 Block* block = this->block_;
5153 int index = 0;
5154 for (Typed_identifier_list::const_iterator p = results->begin();
5155 p != results->end();
5156 ++p, ++index)
5158 std::string name = p->name();
5159 if (name.empty() || Gogo::is_sink_name(name))
5161 static int result_counter;
5162 char buf[100];
5163 snprintf(buf, sizeof buf, "$ret%d", result_counter);
5164 ++result_counter;
5165 name = gogo->pack_hidden_name(buf, false);
5167 Result_variable* result = new Result_variable(p->type(), this, index,
5168 p->location());
5169 Named_object* no = block->bindings()->add_result_variable(name, result);
5170 if (no->is_result_variable())
5171 this->results_->push_back(no);
5172 else
5174 static int dummy_result_count;
5175 char buf[100];
5176 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
5177 ++dummy_result_count;
5178 name = gogo->pack_hidden_name(buf, false);
5179 no = block->bindings()->add_result_variable(name, result);
5180 go_assert(no->is_result_variable());
5181 this->results_->push_back(no);
5186 // Update the named result variables when cloning a function which
5187 // calls recover.
5189 void
5190 Function::update_result_variables()
5192 if (this->results_ == NULL)
5193 return;
5195 for (Results::iterator p = this->results_->begin();
5196 p != this->results_->end();
5197 ++p)
5198 (*p)->result_var_value()->set_function(this);
5201 // Whether this method should not be included in the type descriptor.
5203 bool
5204 Function::nointerface() const
5206 go_assert(this->is_method());
5207 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
5210 // Record that this method should not be included in the type
5211 // descriptor.
5213 void
5214 Function::set_nointerface()
5216 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
5219 // Return the closure variable, creating it if necessary.
5221 Named_object*
5222 Function::closure_var()
5224 if (this->closure_var_ == NULL)
5226 go_assert(this->descriptor_ == NULL);
5227 // We don't know the type of the variable yet. We add fields as
5228 // we find them.
5229 Location loc = this->type_->location();
5230 Struct_field_list* sfl = new Struct_field_list;
5231 Struct_type* struct_type = Type::make_struct_type(sfl, loc);
5232 struct_type->set_is_struct_incomparable();
5233 Variable* var = new Variable(Type::make_pointer_type(struct_type),
5234 NULL, false, false, false, loc);
5235 var->set_is_used();
5236 var->set_is_closure();
5237 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
5238 // Note that the new variable is not in any binding contour.
5240 return this->closure_var_;
5243 // Set the type of the closure variable.
5245 void
5246 Function::set_closure_type()
5248 if (this->closure_var_ == NULL)
5249 return;
5250 Named_object* closure = this->closure_var_;
5251 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
5253 // The first field of a closure is always a pointer to the function
5254 // code.
5255 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
5256 st->push_field(Struct_field(Typed_identifier(".f", voidptr_type,
5257 this->location_)));
5259 unsigned int index = 1;
5260 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
5261 p != this->closure_fields_.end();
5262 ++p, ++index)
5264 Named_object* no = p->first;
5265 char buf[20];
5266 snprintf(buf, sizeof buf, "%u", index);
5267 std::string n = no->name() + buf;
5268 Type* var_type;
5269 if (no->is_variable())
5270 var_type = no->var_value()->type();
5271 else
5272 var_type = no->result_var_value()->type();
5273 Type* field_type = Type::make_pointer_type(var_type);
5274 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
5278 // Return whether this function is a method.
5280 bool
5281 Function::is_method() const
5283 return this->type_->is_method();
5286 // Add a label definition.
5288 Label*
5289 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
5290 Location location)
5292 Label* lnull = NULL;
5293 std::pair<Labels::iterator, bool> ins =
5294 this->labels_.insert(std::make_pair(label_name, lnull));
5295 Label* label;
5296 if (label_name == "_")
5298 label = Label::create_dummy_label();
5299 if (ins.second)
5300 ins.first->second = label;
5302 else if (ins.second)
5304 // This is a new label.
5305 label = new Label(label_name);
5306 ins.first->second = label;
5308 else
5310 // The label was already in the hash table.
5311 label = ins.first->second;
5312 if (label->is_defined())
5314 go_error_at(location, "label %qs already defined",
5315 Gogo::message_name(label_name).c_str());
5316 go_inform(label->location(), "previous definition of %qs was here",
5317 Gogo::message_name(label_name).c_str());
5318 return new Label(label_name);
5322 label->define(location, gogo->bindings_snapshot(location));
5324 // Issue any errors appropriate for any previous goto's to this
5325 // label.
5326 const std::vector<Bindings_snapshot*>& refs(label->refs());
5327 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
5328 p != refs.end();
5329 ++p)
5330 (*p)->check_goto_to(gogo->current_block());
5331 label->clear_refs();
5333 return label;
5336 // Add a reference to a label.
5338 Label*
5339 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5340 Location location, bool issue_goto_errors)
5342 Label* lnull = NULL;
5343 std::pair<Labels::iterator, bool> ins =
5344 this->labels_.insert(std::make_pair(label_name, lnull));
5345 Label* label;
5346 if (!ins.second)
5348 // The label was already in the hash table.
5349 label = ins.first->second;
5351 else
5353 go_assert(ins.first->second == NULL);
5354 label = new Label(label_name);
5355 ins.first->second = label;
5358 label->set_is_used();
5360 if (issue_goto_errors)
5362 Bindings_snapshot* snapshot = label->snapshot();
5363 if (snapshot != NULL)
5364 snapshot->check_goto_from(gogo->current_block(), location);
5365 else
5366 label->add_snapshot_ref(gogo->bindings_snapshot(location));
5369 return label;
5372 // Warn about labels that are defined but not used.
5374 void
5375 Function::check_labels() const
5377 for (Labels::const_iterator p = this->labels_.begin();
5378 p != this->labels_.end();
5379 p++)
5381 Label* label = p->second;
5382 if (!label->is_used())
5383 go_error_at(label->location(), "label %qs defined and not used",
5384 Gogo::message_name(label->name()).c_str());
5388 // Swap one function with another. This is used when building the
5389 // thunk we use to call a function which calls recover. It may not
5390 // work for any other case.
5392 void
5393 Function::swap_for_recover(Function *x)
5395 go_assert(this->enclosing_ == x->enclosing_);
5396 std::swap(this->results_, x->results_);
5397 std::swap(this->closure_var_, x->closure_var_);
5398 std::swap(this->block_, x->block_);
5399 go_assert(this->location_ == x->location_);
5400 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5401 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5404 // Traverse the tree.
5407 Function::traverse(Traverse* traverse)
5409 unsigned int traverse_mask = traverse->traverse_mask();
5411 if ((traverse_mask
5412 & (Traverse::traverse_types | Traverse::traverse_expressions))
5413 != 0)
5415 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5416 return TRAVERSE_EXIT;
5419 // FIXME: We should check traverse_functions here if nested
5420 // functions are stored in block bindings.
5421 if (this->block_ != NULL
5422 && (traverse_mask
5423 & (Traverse::traverse_variables
5424 | Traverse::traverse_constants
5425 | Traverse::traverse_blocks
5426 | Traverse::traverse_statements
5427 | Traverse::traverse_expressions
5428 | Traverse::traverse_types)) != 0)
5430 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5431 return TRAVERSE_EXIT;
5434 return TRAVERSE_CONTINUE;
5437 // Work out types for unspecified variables and constants.
5439 void
5440 Function::determine_types()
5442 if (this->block_ != NULL)
5443 this->block_->determine_types();
5446 // Return the function descriptor, the value you get when you refer to
5447 // the function in Go code without calling it.
5449 Expression*
5450 Function::descriptor(Gogo*, Named_object* no)
5452 go_assert(!this->is_method());
5453 go_assert(this->closure_var_ == NULL);
5454 if (this->descriptor_ == NULL)
5455 this->descriptor_ = Expression::make_func_descriptor(no);
5456 return this->descriptor_;
5459 // Get a pointer to the variable representing the defer stack for this
5460 // function, making it if necessary. The value of the variable is set
5461 // by the runtime routines to true if the function is returning,
5462 // rather than panicing through. A pointer to this variable is used
5463 // as a marker for the functions on the defer stack associated with
5464 // this function. A function-specific variable permits inlining a
5465 // function which uses defer.
5467 Expression*
5468 Function::defer_stack(Location location)
5470 if (this->defer_stack_ == NULL)
5472 Type* t = Type::lookup_bool_type();
5473 Expression* n = Expression::make_boolean(false, location);
5474 this->defer_stack_ = Statement::make_temporary(t, n, location);
5475 this->defer_stack_->set_is_address_taken();
5477 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5478 location);
5479 return Expression::make_unary(OPERATOR_AND, ref, location);
5482 // Export the function.
5484 void
5485 Function::export_func(Export* exp, const std::string& name) const
5487 Block* block = NULL;
5488 if (this->export_for_inlining())
5489 block = this->block_;
5490 Function::export_func_with_type(exp, name, this->type_, this->results_,
5491 this->is_method() && this->nointerface(),
5492 block, this->location_);
5495 // Export a function with a type.
5497 void
5498 Function::export_func_with_type(Export* exp, const std::string& name,
5499 const Function_type* fntype,
5500 Function::Results* result_vars,
5501 bool nointerface, Block* block, Location loc)
5503 exp->write_c_string("func ");
5505 if (nointerface)
5507 go_assert(fntype->is_method());
5508 exp->write_c_string("/*nointerface*/ ");
5511 if (fntype->is_method())
5513 exp->write_c_string("(");
5514 const Typed_identifier* receiver = fntype->receiver();
5515 exp->write_name(receiver->name());
5516 exp->write_escape(receiver->note());
5517 exp->write_c_string(" ");
5518 exp->write_type(receiver->type());
5519 exp->write_c_string(") ");
5522 exp->write_string(name);
5524 exp->write_c_string(" (");
5525 const Typed_identifier_list* parameters = fntype->parameters();
5526 if (parameters != NULL)
5528 size_t i = 0;
5529 bool is_varargs = fntype->is_varargs();
5530 bool first = true;
5531 for (Typed_identifier_list::const_iterator p = parameters->begin();
5532 p != parameters->end();
5533 ++p, ++i)
5535 if (first)
5536 first = false;
5537 else
5538 exp->write_c_string(", ");
5539 exp->write_name(p->name());
5540 exp->write_escape(p->note());
5541 exp->write_c_string(" ");
5542 if (!is_varargs || p + 1 != parameters->end())
5543 exp->write_type(p->type());
5544 else
5546 exp->write_c_string("...");
5547 exp->write_type(p->type()->array_type()->element_type());
5551 exp->write_c_string(")");
5553 const Typed_identifier_list* result_decls = fntype->results();
5554 if (result_decls != NULL)
5556 if (result_decls->size() == 1
5557 && result_decls->begin()->name().empty()
5558 && block == NULL)
5560 exp->write_c_string(" ");
5561 exp->write_type(result_decls->begin()->type());
5563 else
5565 exp->write_c_string(" (");
5566 bool first = true;
5567 Results::const_iterator pr;
5568 if (result_vars != NULL)
5569 pr = result_vars->begin();
5570 for (Typed_identifier_list::const_iterator pd = result_decls->begin();
5571 pd != result_decls->end();
5572 ++pd)
5574 if (first)
5575 first = false;
5576 else
5577 exp->write_c_string(", ");
5578 // We only use pr->name, which may be artificial, if
5579 // need it for inlining.
5580 if (block == NULL || result_vars == NULL)
5581 exp->write_name(pd->name());
5582 else
5583 exp->write_name((*pr)->name());
5584 exp->write_escape(pd->note());
5585 exp->write_c_string(" ");
5586 exp->write_type(pd->type());
5587 if (result_vars != NULL)
5588 ++pr;
5590 if (result_vars != NULL)
5591 go_assert(pr == result_vars->end());
5592 exp->write_c_string(")");
5596 if (block == NULL)
5597 exp->write_c_string("\n");
5598 else
5600 int indent = 1;
5601 if (fntype->is_method())
5602 indent++;
5604 Export_function_body efb(exp, indent);
5606 efb.indent();
5607 efb.write_c_string("// ");
5608 efb.write_string(Linemap::location_to_file(block->start_location()));
5609 efb.write_char(':');
5610 char buf[100];
5611 snprintf(buf, sizeof buf, "%d", Linemap::location_to_line(loc));
5612 efb.write_c_string(buf);
5613 efb.write_char('\n');
5614 block->export_block(&efb);
5616 const std::string& body(efb.body());
5618 snprintf(buf, sizeof buf, " <inl:%lu>\n",
5619 static_cast<unsigned long>(body.length()));
5620 exp->write_c_string(buf);
5622 exp->write_string(body);
5626 // Import a function.
5628 void
5629 Function::import_func(Import* imp, std::string* pname,
5630 Typed_identifier** preceiver,
5631 Typed_identifier_list** pparameters,
5632 Typed_identifier_list** presults,
5633 bool* is_varargs,
5634 bool* nointerface,
5635 std::string* body)
5637 imp->require_c_string("func ");
5639 *nointerface = false;
5640 if (imp->match_c_string("/*"))
5642 imp->require_c_string("/*nointerface*/ ");
5643 *nointerface = true;
5645 // Only a method can be nointerface.
5646 go_assert(imp->peek_char() == '(');
5649 *preceiver = NULL;
5650 if (imp->peek_char() == '(')
5652 imp->require_c_string("(");
5653 std::string name = imp->read_name();
5654 std::string escape_note = imp->read_escape();
5655 imp->require_c_string(" ");
5656 Type* rtype = imp->read_type();
5657 *preceiver = new Typed_identifier(name, rtype, imp->location());
5658 (*preceiver)->set_note(escape_note);
5659 imp->require_c_string(") ");
5662 *pname = imp->read_identifier();
5664 Typed_identifier_list* parameters;
5665 *is_varargs = false;
5666 imp->require_c_string(" (");
5667 if (imp->peek_char() == ')')
5668 parameters = NULL;
5669 else
5671 parameters = new Typed_identifier_list();
5672 while (true)
5674 std::string name = imp->read_name();
5675 std::string escape_note = imp->read_escape();
5676 imp->require_c_string(" ");
5678 if (imp->match_c_string("..."))
5680 imp->advance(3);
5681 *is_varargs = true;
5684 Type* ptype = imp->read_type();
5685 if (*is_varargs)
5686 ptype = Type::make_array_type(ptype, NULL);
5687 Typed_identifier t = Typed_identifier(name, ptype, imp->location());
5688 t.set_note(escape_note);
5689 parameters->push_back(t);
5690 if (imp->peek_char() != ',')
5691 break;
5692 go_assert(!*is_varargs);
5693 imp->require_c_string(", ");
5696 imp->require_c_string(")");
5697 *pparameters = parameters;
5699 Typed_identifier_list* results;
5700 if (imp->peek_char() != ' ' || imp->match_c_string(" <inl"))
5701 results = NULL;
5702 else
5704 results = new Typed_identifier_list();
5705 imp->require_c_string(" ");
5706 if (imp->peek_char() != '(')
5708 Type* rtype = imp->read_type();
5709 results->push_back(Typed_identifier("", rtype, imp->location()));
5711 else
5713 imp->require_c_string("(");
5714 while (true)
5716 std::string name = imp->read_name();
5717 std::string note = imp->read_escape();
5718 imp->require_c_string(" ");
5719 Type* rtype = imp->read_type();
5720 Typed_identifier t = Typed_identifier(name, rtype,
5721 imp->location());
5722 t.set_note(note);
5723 results->push_back(t);
5724 if (imp->peek_char() != ',')
5725 break;
5726 imp->require_c_string(", ");
5728 imp->require_c_string(")");
5731 *presults = results;
5733 if (!imp->match_c_string(" <inl:"))
5735 imp->require_semicolon_if_old_version();
5736 imp->require_c_string("\n");
5737 body->clear();
5739 else
5741 imp->require_c_string(" <inl:");
5742 std::string lenstr;
5743 int c;
5744 while (true)
5746 c = imp->peek_char();
5747 if (c < '0' || c > '9')
5748 break;
5749 lenstr += c;
5750 imp->get_char();
5752 imp->require_c_string(">\n");
5754 errno = 0;
5755 char* end;
5756 long llen = strtol(lenstr.c_str(), &end, 10);
5757 if (*end != '\0'
5758 || llen < 0
5759 || (llen == LONG_MAX && errno == ERANGE))
5761 go_error_at(imp->location(), "invalid inline function length %s",
5762 lenstr.c_str());
5763 return;
5766 *body = imp->read(static_cast<size_t>(llen));
5770 // Get the backend representation.
5772 Bfunction*
5773 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
5775 if (this->fndecl_ == NULL)
5777 unsigned int flags = 0;
5778 bool is_init_fn = false;
5779 if (no->package() != NULL)
5781 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
5783 else if (Gogo::unpack_hidden_name(no->name()) == "init"
5784 && !this->type_->is_method())
5786 else if (no->name() == gogo->get_init_fn_name())
5788 flags |= Backend::function_is_visible;
5789 is_init_fn = true;
5791 else if (Gogo::unpack_hidden_name(no->name()) == "main"
5792 && gogo->is_main_package())
5793 flags |= Backend::function_is_visible;
5794 // Methods have to be public even if they are hidden because
5795 // they can be pulled into type descriptors when using
5796 // anonymous fields.
5797 else if (!Gogo::is_hidden_name(no->name())
5798 || this->type_->is_method())
5800 if (!this->is_unnamed_type_stub_method_)
5801 flags |= Backend::function_is_visible;
5804 Type* rtype = NULL;
5805 if (this->type_->is_method())
5806 rtype = this->type_->receiver()->type();
5808 std::string asm_name;
5809 if (!this->asm_name_.empty())
5811 asm_name = this->asm_name_;
5813 // If an assembler name is explicitly specified, there must
5814 // be some reason to refer to the symbol from a different
5815 // object file.
5816 flags |= Backend::function_is_visible;
5818 else if (is_init_fn)
5820 // These names appear in the export data and are used
5821 // directly in the assembler code. If we change this here
5822 // we need to change Gogo::init_imports.
5823 asm_name = no->name();
5825 else
5826 asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
5828 // If a function calls the predeclared recover function, we
5829 // can't inline it, because recover behaves differently in a
5830 // function passed directly to defer. If this is a recover
5831 // thunk that we built to test whether a function can be
5832 // recovered, we can't inline it, because that will mess up
5833 // our return address comparison.
5834 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
5836 // If a function calls __go_set_defer_retaddr, then mark it as
5837 // uninlinable. This prevents the GCC backend from splitting
5838 // the function; splitting the function is a bad idea because we
5839 // want the return address label to be in the same function as
5840 // the call.
5841 if (this->calls_defer_retaddr_)
5842 is_inlinable = false;
5844 // Check the //go:noinline compiler directive.
5845 if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
5846 is_inlinable = false;
5848 if (is_inlinable)
5849 flags |= Backend::function_is_inlinable;
5851 // If this is a thunk created to call a function which calls
5852 // the predeclared recover function, we need to disable
5853 // stack splitting for the thunk.
5854 bool disable_split_stack = this->is_recover_thunk_;
5856 // Check the //go:nosplit compiler directive.
5857 if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
5858 disable_split_stack = true;
5860 if (disable_split_stack)
5861 flags |= Backend::function_no_split_stack;
5863 // This should go into a unique section if that has been
5864 // requested elsewhere, or if this is a nointerface function.
5865 // We want to put a nointerface function into a unique section
5866 // because there is a good chance that the linker garbage
5867 // collection can discard it.
5868 if (this->in_unique_section_
5869 || (this->is_method() && this->nointerface()))
5870 flags |= Backend::function_in_unique_section;
5872 if (this->is_inline_only_)
5873 flags |= Backend::function_only_inline;
5875 Btype* functype = this->type_->get_backend_fntype(gogo);
5876 this->fndecl_ =
5877 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5878 flags, this->location());
5880 return this->fndecl_;
5883 // Get the backend representation.
5885 Bfunction*
5886 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
5888 if (this->fndecl_ == NULL)
5890 unsigned int flags =
5891 (Backend::function_is_visible
5892 | Backend::function_is_declaration
5893 | Backend::function_is_inlinable);
5895 // Let Go code use an asm declaration to pick up a builtin
5896 // function.
5897 if (!this->asm_name_.empty())
5899 Bfunction* builtin_decl =
5900 gogo->backend()->lookup_builtin(this->asm_name_);
5901 if (builtin_decl != NULL)
5903 this->fndecl_ = builtin_decl;
5904 return this->fndecl_;
5907 if (this->asm_name_ == "runtime.gopanic"
5908 || this->asm_name_ == "__go_runtime_error")
5909 flags |= Backend::function_does_not_return;
5912 std::string asm_name;
5913 if (this->asm_name_.empty())
5915 Type* rtype = NULL;
5916 if (this->fntype_->is_method())
5917 rtype = this->fntype_->receiver()->type();
5918 asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
5920 else if (go_id_needs_encoding(no->get_id(gogo)))
5921 asm_name = go_encode_id(no->get_id(gogo));
5923 Btype* functype = this->fntype_->get_backend_fntype(gogo);
5924 this->fndecl_ =
5925 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5926 flags, this->location());
5929 return this->fndecl_;
5932 // Build the descriptor for a function declaration. This won't
5933 // necessarily happen if the package has just a declaration for the
5934 // function and no other reference to it, but we may still need the
5935 // descriptor for references from other packages.
5936 void
5937 Function_declaration::build_backend_descriptor(Gogo* gogo)
5939 if (this->descriptor_ != NULL)
5941 Translate_context context(gogo, NULL, NULL, NULL);
5942 this->descriptor_->get_backend(&context);
5946 // Check that the types used in this declaration's signature are defined.
5947 // Reports errors for any undefined type.
5949 void
5950 Function_declaration::check_types() const
5952 // Calling Type::base will give errors for any undefined types.
5953 Function_type* fntype = this->type();
5954 if (fntype->receiver() != NULL)
5955 fntype->receiver()->type()->base();
5956 if (fntype->parameters() != NULL)
5958 const Typed_identifier_list* params = fntype->parameters();
5959 for (Typed_identifier_list::const_iterator p = params->begin();
5960 p != params->end();
5961 ++p)
5962 p->type()->base();
5966 // Return the function's decl after it has been built.
5968 Bfunction*
5969 Function::get_decl() const
5971 go_assert(this->fndecl_ != NULL);
5972 return this->fndecl_;
5975 // Build the backend representation for the function code.
5977 void
5978 Function::build(Gogo* gogo, Named_object* named_function)
5980 Translate_context context(gogo, named_function, NULL, NULL);
5982 // A list of parameter variables for this function.
5983 std::vector<Bvariable*> param_vars;
5985 // Variables that need to be declared for this function and their
5986 // initial values.
5987 std::vector<Bvariable*> vars;
5988 std::vector<Bexpression*> var_inits;
5989 std::vector<Statement*> var_decls_stmts;
5990 for (Bindings::const_definitions_iterator p =
5991 this->block_->bindings()->begin_definitions();
5992 p != this->block_->bindings()->end_definitions();
5993 ++p)
5995 Location loc = (*p)->location();
5996 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
5998 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5999 Bvariable* parm_bvar = bvar;
6001 // We always pass the receiver to a method as a pointer. If
6002 // the receiver is declared as a non-pointer type, then we
6003 // copy the value into a local variable.
6004 if ((*p)->var_value()->is_receiver()
6005 && (*p)->var_value()->type()->points_to() == NULL)
6007 std::string name = (*p)->name() + ".pointer";
6008 Type* var_type = (*p)->var_value()->type();
6009 Variable* parm_var =
6010 new Variable(Type::make_pointer_type(var_type), NULL, false,
6011 true, false, loc);
6012 Named_object* parm_no =
6013 Named_object::make_variable(name, NULL, parm_var);
6014 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6016 vars.push_back(bvar);
6017 Expression* parm_ref =
6018 Expression::make_var_reference(parm_no, loc);
6019 parm_ref =
6020 Expression::make_dereference(parm_ref,
6021 Expression::NIL_CHECK_NEEDED,
6022 loc);
6023 if ((*p)->var_value()->is_in_heap())
6024 parm_ref = Expression::make_heap_expression(parm_ref, loc);
6025 var_inits.push_back(parm_ref->get_backend(&context));
6027 else if ((*p)->var_value()->is_in_heap())
6029 // If we take the address of a parameter, then we need
6030 // to copy it into the heap.
6031 std::string parm_name = (*p)->name() + ".param";
6032 Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
6033 false, true, false, loc);
6034 Named_object* parm_no =
6035 Named_object::make_variable(parm_name, NULL, parm_var);
6036 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6038 vars.push_back(bvar);
6039 Expression* var_ref =
6040 Expression::make_var_reference(parm_no, loc);
6041 var_ref = Expression::make_heap_expression(var_ref, loc);
6042 var_inits.push_back(var_ref->get_backend(&context));
6044 param_vars.push_back(parm_bvar);
6046 else if ((*p)->is_result_variable())
6048 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6050 Type* type = (*p)->result_var_value()->type();
6051 Bexpression* init;
6052 if (!(*p)->result_var_value()->is_in_heap())
6054 Btype* btype = type->get_backend(gogo);
6055 init = gogo->backend()->zero_expression(btype);
6057 else
6058 init = Expression::make_allocation(type,
6059 loc)->get_backend(&context);
6061 vars.push_back(bvar);
6062 var_inits.push_back(init);
6064 else if (this->defer_stack_ != NULL
6065 && (*p)->is_variable()
6066 && (*p)->var_value()->is_non_escaping_address_taken()
6067 && !(*p)->var_value()->is_in_heap())
6069 // Local variable captured by deferred closure needs to be live
6070 // until the end of the function. We create a top-level
6071 // declaration for it.
6072 // TODO: we don't need to do this if the variable is not captured
6073 // by the defer closure. There is no easy way to check it here,
6074 // so we do this for all address-taken variables for now.
6075 Variable* var = (*p)->var_value();
6076 Temporary_statement* ts =
6077 Statement::make_temporary(var->type(), NULL, var->location());
6078 ts->set_is_address_taken();
6079 var->set_toplevel_decl(ts);
6080 var_decls_stmts.push_back(ts);
6083 if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
6085 go_assert(saw_errors());
6086 return;
6089 // If we need a closure variable, make sure to create it.
6090 // It gets installed in the function as a side effect of creation.
6091 if (this->closure_var_ != NULL)
6093 go_assert(this->closure_var_->var_value()->is_closure());
6094 this->closure_var_->get_backend_variable(gogo, named_function);
6097 if (this->block_ != NULL)
6099 // Declare variables if necessary.
6100 Bblock* var_decls = NULL;
6101 std::vector<Bstatement*> var_decls_bstmt_list;
6102 Bstatement* defer_init = NULL;
6103 if (!vars.empty() || this->defer_stack_ != NULL)
6105 var_decls =
6106 gogo->backend()->block(this->fndecl_, NULL, vars,
6107 this->block_->start_location(),
6108 this->block_->end_location());
6110 if (this->defer_stack_ != NULL)
6112 Translate_context dcontext(gogo, named_function, this->block_,
6113 var_decls);
6114 defer_init = this->defer_stack_->get_backend(&dcontext);
6115 var_decls_bstmt_list.push_back(defer_init);
6116 for (std::vector<Statement*>::iterator p = var_decls_stmts.begin();
6117 p != var_decls_stmts.end();
6118 ++p)
6120 Bstatement* bstmt = (*p)->get_backend(&dcontext);
6121 var_decls_bstmt_list.push_back(bstmt);
6126 // Build the backend representation for all the statements in the
6127 // function.
6128 Translate_context context(gogo, named_function, NULL, NULL);
6129 Bblock* code_block = this->block_->get_backend(&context);
6131 // Initialize variables if necessary.
6132 std::vector<Bstatement*> init;
6133 go_assert(vars.size() == var_inits.size());
6134 for (size_t i = 0; i < vars.size(); ++i)
6136 Bstatement* init_stmt =
6137 gogo->backend()->init_statement(this->fndecl_, vars[i],
6138 var_inits[i]);
6139 init.push_back(init_stmt);
6141 Bstatement* var_init = gogo->backend()->statement_list(init);
6143 // Initialize all variables before executing this code block.
6144 Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
6145 code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
6147 // If we have a defer stack, initialize it at the start of a
6148 // function.
6149 Bstatement* except = NULL;
6150 Bstatement* fini = NULL;
6151 if (defer_init != NULL)
6153 // Clean up the defer stack when we leave the function.
6154 this->build_defer_wrapper(gogo, named_function, &except, &fini);
6156 // Wrap the code for this function in an exception handler to handle
6157 // defer calls.
6158 code_stmt =
6159 gogo->backend()->exception_handler_statement(code_stmt,
6160 except, fini,
6161 this->location_);
6164 // Stick the code into the block we built for the receiver, if
6165 // we built one.
6166 if (var_decls != NULL)
6168 var_decls_bstmt_list.push_back(code_stmt);
6169 gogo->backend()->block_add_statements(var_decls, var_decls_bstmt_list);
6170 code_stmt = gogo->backend()->block_statement(var_decls);
6173 if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
6175 go_assert(saw_errors());
6176 return;
6180 // If we created a descriptor for the function, make sure we emit it.
6181 if (this->descriptor_ != NULL)
6183 Translate_context context(gogo, NULL, NULL, NULL);
6184 this->descriptor_->get_backend(&context);
6188 // Build the wrappers around function code needed if the function has
6189 // any defer statements. This sets *EXCEPT to an exception handler
6190 // and *FINI to a finally handler.
6192 void
6193 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
6194 Bstatement** except, Bstatement** fini)
6196 Location end_loc = this->block_->end_location();
6198 // Add an exception handler. This is used if a panic occurs. Its
6199 // purpose is to stop the stack unwinding if a deferred function
6200 // calls recover. There are more details in
6201 // libgo/runtime/go-unwind.c.
6203 std::vector<Bstatement*> stmts;
6204 Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6205 this->defer_stack(end_loc));
6206 Translate_context context(gogo, named_function, NULL, NULL);
6207 Bexpression* defer = call->get_backend(&context);
6208 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
6210 Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
6211 if (ret_bstmt != NULL)
6212 stmts.push_back(ret_bstmt);
6214 go_assert(*except == NULL);
6215 *except = gogo->backend()->statement_list(stmts);
6217 call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6218 this->defer_stack(end_loc));
6219 defer = call->get_backend(&context);
6221 call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
6222 this->defer_stack(end_loc));
6223 Bexpression* undefer = call->get_backend(&context);
6224 Bstatement* function_defer =
6225 gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
6226 end_loc);
6227 stmts = std::vector<Bstatement*>(1, function_defer);
6228 if (this->type_->results() != NULL
6229 && !this->type_->results()->empty()
6230 && !this->type_->results()->front().name().empty())
6232 // If the result variables are named, and we are returning from
6233 // this function rather than panicing through it, we need to
6234 // return them again, because they might have been changed by a
6235 // defer function. The runtime routines set the defer_stack
6236 // variable to true if we are returning from this function.
6238 ret_bstmt = this->return_value(gogo, named_function, end_loc);
6239 Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
6240 Bexpression* ret =
6241 gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
6242 Expression* ref =
6243 Expression::make_temporary_reference(this->defer_stack_, end_loc);
6244 Bexpression* bref = ref->get_backend(&context);
6245 ret = gogo->backend()->conditional_expression(this->fndecl_,
6246 NULL, bref, ret, NULL,
6247 end_loc);
6248 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
6251 go_assert(*fini == NULL);
6252 *fini = gogo->backend()->statement_list(stmts);
6255 // Return the statement that assigns values to this function's result struct.
6257 Bstatement*
6258 Function::return_value(Gogo* gogo, Named_object* named_function,
6259 Location location) const
6261 const Typed_identifier_list* results = this->type_->results();
6262 if (results == NULL || results->empty())
6263 return NULL;
6265 go_assert(this->results_ != NULL);
6266 if (this->results_->size() != results->size())
6268 go_assert(saw_errors());
6269 return gogo->backend()->error_statement();
6272 std::vector<Bexpression*> vals(results->size());
6273 for (size_t i = 0; i < vals.size(); ++i)
6275 Named_object* no = (*this->results_)[i];
6276 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
6277 Bexpression* val = gogo->backend()->var_expression(bvar, location);
6278 if (no->result_var_value()->is_in_heap())
6280 Btype* bt = no->result_var_value()->type()->get_backend(gogo);
6281 val = gogo->backend()->indirect_expression(bt, val, true, location);
6283 vals[i] = val;
6285 return gogo->backend()->return_statement(this->fndecl_, vals, location);
6288 // Class Block.
6290 Block::Block(Block* enclosing, Location location)
6291 : enclosing_(enclosing), statements_(),
6292 bindings_(new Bindings(enclosing == NULL
6293 ? NULL
6294 : enclosing->bindings())),
6295 start_location_(location),
6296 end_location_(Linemap::unknown_location())
6300 // Add a statement to a block.
6302 void
6303 Block::add_statement(Statement* statement)
6305 this->statements_.push_back(statement);
6308 // Add a statement to the front of a block. This is slow but is only
6309 // used for reference counts of parameters.
6311 void
6312 Block::add_statement_at_front(Statement* statement)
6314 this->statements_.insert(this->statements_.begin(), statement);
6317 // Replace a statement in a block.
6319 void
6320 Block::replace_statement(size_t index, Statement* s)
6322 go_assert(index < this->statements_.size());
6323 this->statements_[index] = s;
6326 // Add a statement before another statement.
6328 void
6329 Block::insert_statement_before(size_t index, Statement* s)
6331 go_assert(index < this->statements_.size());
6332 this->statements_.insert(this->statements_.begin() + index, s);
6335 // Add a statement after another statement.
6337 void
6338 Block::insert_statement_after(size_t index, Statement* s)
6340 go_assert(index < this->statements_.size());
6341 this->statements_.insert(this->statements_.begin() + index + 1, s);
6344 // Traverse the tree.
6347 Block::traverse(Traverse* traverse)
6349 unsigned int traverse_mask = traverse->traverse_mask();
6351 if ((traverse_mask & Traverse::traverse_blocks) != 0)
6353 int t = traverse->block(this);
6354 if (t == TRAVERSE_EXIT)
6355 return TRAVERSE_EXIT;
6356 else if (t == TRAVERSE_SKIP_COMPONENTS)
6357 return TRAVERSE_CONTINUE;
6360 if ((traverse_mask
6361 & (Traverse::traverse_variables
6362 | Traverse::traverse_constants
6363 | Traverse::traverse_expressions
6364 | Traverse::traverse_types)) != 0)
6366 const unsigned int e_or_t = (Traverse::traverse_expressions
6367 | Traverse::traverse_types);
6368 const unsigned int e_or_t_or_s = (e_or_t
6369 | Traverse::traverse_statements);
6370 for (Bindings::const_definitions_iterator pb =
6371 this->bindings_->begin_definitions();
6372 pb != this->bindings_->end_definitions();
6373 ++pb)
6375 int t = TRAVERSE_CONTINUE;
6376 switch ((*pb)->classification())
6378 case Named_object::NAMED_OBJECT_CONST:
6379 if ((traverse_mask & Traverse::traverse_constants) != 0)
6380 t = traverse->constant(*pb, false);
6381 if (t == TRAVERSE_CONTINUE
6382 && (traverse_mask & e_or_t) != 0)
6384 Type* tc = (*pb)->const_value()->type();
6385 if (tc != NULL
6386 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
6387 return TRAVERSE_EXIT;
6388 t = (*pb)->const_value()->traverse_expression(traverse);
6390 break;
6392 case Named_object::NAMED_OBJECT_VAR:
6393 case Named_object::NAMED_OBJECT_RESULT_VAR:
6394 if ((traverse_mask & Traverse::traverse_variables) != 0)
6395 t = traverse->variable(*pb);
6396 if (t == TRAVERSE_CONTINUE
6397 && (traverse_mask & e_or_t) != 0)
6399 if ((*pb)->is_result_variable()
6400 || (*pb)->var_value()->has_type())
6402 Type* tv = ((*pb)->is_variable()
6403 ? (*pb)->var_value()->type()
6404 : (*pb)->result_var_value()->type());
6405 if (tv != NULL
6406 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
6407 return TRAVERSE_EXIT;
6410 if (t == TRAVERSE_CONTINUE
6411 && (traverse_mask & e_or_t_or_s) != 0
6412 && (*pb)->is_variable())
6413 t = (*pb)->var_value()->traverse_expression(traverse,
6414 traverse_mask);
6415 break;
6417 case Named_object::NAMED_OBJECT_FUNC:
6418 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
6419 go_unreachable();
6421 case Named_object::NAMED_OBJECT_TYPE:
6422 if ((traverse_mask & e_or_t) != 0)
6423 t = Type::traverse((*pb)->type_value(), traverse);
6424 break;
6426 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
6427 case Named_object::NAMED_OBJECT_UNKNOWN:
6428 case Named_object::NAMED_OBJECT_ERRONEOUS:
6429 break;
6431 case Named_object::NAMED_OBJECT_PACKAGE:
6432 case Named_object::NAMED_OBJECT_SINK:
6433 go_unreachable();
6435 default:
6436 go_unreachable();
6439 if (t == TRAVERSE_EXIT)
6440 return TRAVERSE_EXIT;
6444 // No point in checking traverse_mask here--if we got here we always
6445 // want to walk the statements. The traversal can insert new
6446 // statements before or after the current statement. Inserting
6447 // statements before the current statement requires updating I via
6448 // the pointer; those statements will not be traversed. Any new
6449 // statements inserted after the current statement will be traversed
6450 // in their turn.
6451 for (size_t i = 0; i < this->statements_.size(); ++i)
6453 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
6454 return TRAVERSE_EXIT;
6457 return TRAVERSE_CONTINUE;
6460 // Work out types for unspecified variables and constants.
6462 void
6463 Block::determine_types()
6465 for (Bindings::const_definitions_iterator pb =
6466 this->bindings_->begin_definitions();
6467 pb != this->bindings_->end_definitions();
6468 ++pb)
6470 if ((*pb)->is_variable())
6471 (*pb)->var_value()->determine_type();
6472 else if ((*pb)->is_const())
6473 (*pb)->const_value()->determine_type();
6476 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6477 ps != this->statements_.end();
6478 ++ps)
6479 (*ps)->determine_types();
6482 // Return true if the statements in this block may fall through.
6484 bool
6485 Block::may_fall_through() const
6487 if (this->statements_.empty())
6488 return true;
6489 return this->statements_.back()->may_fall_through();
6492 // Write export data for a block.
6494 void
6495 Block::export_block(Export_function_body* efb)
6497 for (Block::iterator p = this->begin();
6498 p != this->end();
6499 ++p)
6501 efb->indent();
6503 efb->increment_indent();
6504 (*p)->export_statement(efb);
6505 efb->decrement_indent();
6507 Location loc = (*p)->location();
6508 if ((*p)->is_block_statement())
6510 // For a block we put the start location on the first brace
6511 // in Block_statement::do_export_statement. Here we put the
6512 // end location on the final brace.
6513 loc = (*p)->block_statement()->block()->end_location();
6515 char buf[50];
6516 snprintf(buf, sizeof buf, " //%d\n", Linemap::location_to_line(loc));
6517 efb->write_c_string(buf);
6521 // Add exported block data to SET, reading from BODY starting at OFF.
6522 // Returns whether the import succeeded.
6524 bool
6525 Block::import_block(Block* set, Import_function_body *ifb, Location loc)
6527 Location eloc = ifb->location();
6528 Location sloc = loc;
6529 const std::string& body(ifb->body());
6530 size_t off = ifb->off();
6531 while (off < body.length())
6533 int indent = ifb->indent();
6534 if (off + indent >= body.length())
6536 go_error_at(eloc,
6537 "invalid export data for %qs: insufficient indentation",
6538 ifb->name().c_str());
6539 return false;
6541 for (int i = 0; i < indent - 1; i++)
6543 if (body[off + i] != ' ')
6545 go_error_at(eloc,
6546 "invalid export data for %qs: bad indentation",
6547 ifb->name().c_str());
6548 return false;
6552 bool at_end = false;
6553 if (body[off + indent - 1] == '}')
6554 at_end = true;
6555 else if (body[off + indent - 1] != ' ')
6557 go_error_at(eloc,
6558 "invalid export data for %qs: bad indentation",
6559 ifb->name().c_str());
6560 return false;
6563 off += indent;
6565 size_t nl = body.find('\n', off);
6566 if (nl == std::string::npos)
6568 go_error_at(eloc, "invalid export data for %qs: missing newline",
6569 ifb->name().c_str());
6570 return false;
6573 size_t lineno_pos = body.find(" //", off);
6574 if (lineno_pos == std::string::npos || lineno_pos >= nl)
6576 go_error_at(eloc, "invalid export data for %qs: missing line number",
6577 ifb->name().c_str());
6578 return false;
6581 unsigned int lineno = 0;
6582 for (size_t i = lineno_pos + 3; i < nl; ++i)
6584 char c = body[i];
6585 if (c < '0' || c > '9')
6587 go_error_at(loc,
6588 "invalid export data for %qs: invalid line number",
6589 ifb->name().c_str());
6590 return false;
6592 lineno = lineno * 10 + c - '0';
6595 ifb->gogo()->linemap()->start_line(lineno, 1);
6596 sloc = ifb->gogo()->linemap()->get_location(0);
6598 if (at_end)
6600 off = nl + 1;
6601 break;
6604 ifb->set_off(off);
6605 Statement* s = Statement::import_statement(ifb, sloc);
6606 if (s == NULL)
6607 return false;
6609 set->add_statement(s);
6611 size_t at = ifb->off();
6612 if (at < nl + 1)
6613 off = nl + 1;
6614 else
6615 off = at;
6618 ifb->set_off(off);
6619 set->set_end_location(sloc);
6620 return true;
6623 // Convert a block to the backend representation.
6625 Bblock*
6626 Block::get_backend(Translate_context* context)
6628 Gogo* gogo = context->gogo();
6629 Named_object* function = context->function();
6630 std::vector<Bvariable*> vars;
6631 vars.reserve(this->bindings_->size_definitions());
6632 for (Bindings::const_definitions_iterator pv =
6633 this->bindings_->begin_definitions();
6634 pv != this->bindings_->end_definitions();
6635 ++pv)
6637 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
6638 vars.push_back((*pv)->get_backend_variable(gogo, function));
6641 go_assert(function != NULL);
6642 Bfunction* bfunction =
6643 function->func_value()->get_or_make_decl(gogo, function);
6644 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
6645 vars, this->start_location_,
6646 this->end_location_);
6648 Translate_context subcontext(gogo, function, this, ret);
6649 std::vector<Bstatement*> bstatements;
6650 bstatements.reserve(this->statements_.size());
6651 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
6652 p != this->statements_.end();
6653 ++p)
6654 bstatements.push_back((*p)->get_backend(&subcontext));
6656 context->backend()->block_add_statements(ret, bstatements);
6658 return ret;
6661 // Class Bindings_snapshot.
6663 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
6664 : block_(b), counts_(), location_(location)
6666 while (b != NULL)
6668 this->counts_.push_back(b->bindings()->size_definitions());
6669 b = b->enclosing();
6673 // Report errors appropriate for a goto from B to this.
6675 void
6676 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
6678 size_t dummy;
6679 if (!this->check_goto_block(loc, b, this->block_, &dummy))
6680 return;
6681 this->check_goto_defs(loc, this->block_,
6682 this->block_->bindings()->size_definitions(),
6683 this->counts_[0]);
6686 // Report errors appropriate for a goto from this to B.
6688 void
6689 Bindings_snapshot::check_goto_to(const Block* b)
6691 size_t index;
6692 if (!this->check_goto_block(this->location_, this->block_, b, &index))
6693 return;
6694 this->check_goto_defs(this->location_, b, this->counts_[index],
6695 b->bindings()->size_definitions());
6698 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6699 // Return true if all is well, false if we reported an error. If this
6700 // returns true, it sets *PINDEX to the number of blocks BTO is above
6701 // BFROM.
6703 bool
6704 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
6705 const Block* bto, size_t* pindex)
6707 // It is an error if BTO is not either BFROM or above BFROM.
6708 size_t index = 0;
6709 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
6711 if (pb == NULL)
6713 go_error_at(loc, "goto jumps into block");
6714 go_inform(bto->start_location(), "goto target block starts here");
6715 return false;
6718 *pindex = index;
6719 return true;
6722 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6723 // CFROM is the number of names defined at the point of the goto and
6724 // CTO is the number of names defined at the point of the label.
6726 void
6727 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
6728 size_t cfrom, size_t cto)
6730 if (cfrom < cto)
6732 Bindings::const_definitions_iterator p =
6733 block->bindings()->begin_definitions();
6734 for (size_t i = 0; i < cfrom; ++i)
6736 go_assert(p != block->bindings()->end_definitions());
6737 ++p;
6739 go_assert(p != block->bindings()->end_definitions());
6741 for (; p != block->bindings()->end_definitions(); ++p)
6743 if ((*p)->is_variable())
6745 std::string n = (*p)->message_name();
6746 go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
6747 go_inform((*p)->location(), "%qs defined here", n.c_str());
6753 // Class Function_declaration.
6755 // Whether this declares a method.
6757 bool
6758 Function_declaration::is_method() const
6760 return this->fntype_->is_method();
6763 // Whether this method should not be included in the type descriptor.
6765 bool
6766 Function_declaration::nointerface() const
6768 go_assert(this->is_method());
6769 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
6772 // Record that this method should not be included in the type
6773 // descriptor.
6775 void
6776 Function_declaration::set_nointerface()
6778 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
6781 // Import an inlinable function. This is used for an inlinable
6782 // function whose body is recorded in the export data. Parse the
6783 // export data into a Block and create a regular function using that
6784 // Block as its body. Redeclare this function declaration as the
6785 // function.
6787 void
6788 Function_declaration::import_function_body(Gogo* gogo, Named_object* no)
6790 go_assert(no->func_declaration_value() == this);
6791 go_assert(no->package() != NULL);
6792 const std::string& body(this->imported_body_);
6793 go_assert(!body.empty());
6795 // Read the "//FILE:LINE" comment starts the export data.
6797 size_t indent = 1;
6798 if (this->is_method())
6799 indent = 2;
6800 size_t i = 0;
6801 for (; i < indent; i++)
6803 if (body.at(i) != ' ')
6805 go_error_at(this->location_,
6806 "invalid export body for %qs: bad initial indentation",
6807 no->message_name().c_str());
6808 return;
6812 if (body.substr(i, 2) != "//")
6814 go_error_at(this->location_,
6815 "invalid export body for %qs: missing file comment",
6816 no->message_name().c_str());
6817 return;
6820 size_t colon = body.find(':', i + 2);
6821 size_t nl = body.find('\n', i + 2);
6822 if (nl == std::string::npos)
6824 go_error_at(this->location_,
6825 "invalid export body for %qs: missing file name",
6826 no->message_name().c_str());
6827 return;
6829 if (colon == std::string::npos || nl < colon)
6831 go_error_at(this->location_,
6832 "invalid export body for %qs: missing initial line number",
6833 no->message_name().c_str());
6834 return;
6837 std::string file = body.substr(i + 2, colon - (i + 2));
6838 std::string linestr = body.substr(colon + 1, nl - (colon + 1));
6839 char* end;
6840 long linenol = strtol(linestr.c_str(), &end, 10);
6841 if (*end != '\0')
6843 go_error_at(this->location_,
6844 "invalid export body for %qs: invalid initial line number",
6845 no->message_name().c_str());
6846 return;
6848 unsigned int lineno = static_cast<unsigned int>(linenol);
6850 // Turn the file/line into a location.
6852 char* alc = new char[file.length() + 1];
6853 memcpy(alc, file.data(), file.length());
6854 alc[file.length()] = '\0';
6855 gogo->linemap()->start_file(alc, lineno);
6856 gogo->linemap()->start_line(lineno, 1);
6857 Location start_loc = gogo->linemap()->get_location(0);
6859 // Define the function with an outer block that declares the
6860 // parameters.
6862 Function_type* fntype = this->fntype_;
6864 Block* outer = new Block(NULL, start_loc);
6866 Function* fn = new Function(fntype, NULL, outer, start_loc);
6867 fn->set_is_inline_only();
6869 if (fntype->is_method())
6871 const Typed_identifier* receiver = fntype->receiver();
6872 Variable* recv_param = new Variable(receiver->type(), NULL, false,
6873 true, true, start_loc);
6874 outer->bindings()->add_variable(receiver->name(), NULL, recv_param);
6877 const Typed_identifier_list* params = fntype->parameters();
6878 bool is_varargs = fntype->is_varargs();
6879 if (params != NULL)
6881 for (Typed_identifier_list::const_iterator p = params->begin();
6882 p != params->end();
6883 ++p)
6885 Variable* param = new Variable(p->type(), NULL, false, true, false,
6886 start_loc);
6887 if (is_varargs && p + 1 == params->end())
6888 param->set_is_varargs_parameter();
6889 outer->bindings()->add_variable(p->name(), NULL, param);
6893 fn->create_result_variables(gogo);
6895 if (!fntype->is_method())
6897 const Package* package = no->package();
6898 no = package->bindings()->add_function(no->name(), package, fn);
6900 else
6902 Named_type* rtype = fntype->receiver()->type()->deref()->named_type();
6903 go_assert(rtype != NULL);
6904 no = rtype->add_method(no->name(), fn);
6907 Import_function_body ifb(gogo, this->imp_, no, body, nl + 1, outer, indent);
6909 if (!Block::import_block(outer, &ifb, start_loc))
6910 return;
6912 gogo->lower_block(no, outer);
6914 gogo->add_imported_inline_function(no);
6917 // Return the function descriptor.
6919 Expression*
6920 Function_declaration::descriptor(Gogo*, Named_object* no)
6922 go_assert(!this->fntype_->is_method());
6923 if (this->descriptor_ == NULL)
6924 this->descriptor_ = Expression::make_func_descriptor(no);
6925 return this->descriptor_;
6928 // Class Variable.
6930 Variable::Variable(Type* type, Expression* init, bool is_global,
6931 bool is_parameter, bool is_receiver,
6932 Location location)
6933 : type_(type), init_(init), preinit_(NULL), location_(location),
6934 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
6935 is_closure_(false), is_receiver_(is_receiver),
6936 is_varargs_parameter_(false), is_used_(false),
6937 is_address_taken_(false), is_non_escaping_address_taken_(false),
6938 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6939 type_from_init_tuple_(false), type_from_range_index_(false),
6940 type_from_range_value_(false), type_from_chan_element_(false),
6941 is_type_switch_var_(false), determined_type_(false),
6942 in_unique_section_(false), escapes_(true),
6943 toplevel_decl_(NULL)
6945 go_assert(type != NULL || init != NULL);
6946 go_assert(!is_parameter || init == NULL);
6949 // Traverse the initializer expression.
6952 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
6954 if (this->preinit_ != NULL)
6956 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
6957 return TRAVERSE_EXIT;
6959 if (this->init_ != NULL
6960 && ((traverse_mask
6961 & (Traverse::traverse_expressions | Traverse::traverse_types))
6962 != 0))
6964 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
6965 return TRAVERSE_EXIT;
6967 return TRAVERSE_CONTINUE;
6970 // Lower the initialization expression after parsing is complete.
6972 void
6973 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
6974 Statement_inserter* inserter)
6976 Named_object* dep = gogo->var_depends_on(this);
6977 if (dep != NULL && dep->is_variable())
6978 dep->var_value()->lower_init_expression(gogo, function, inserter);
6980 if (this->init_ != NULL && !this->init_is_lowered_)
6982 if (this->seen_)
6984 // We will give an error elsewhere, this is just to prevent
6985 // an infinite loop.
6986 return;
6988 this->seen_ = true;
6990 Statement_inserter global_inserter;
6991 if (this->is_global_)
6993 global_inserter = Statement_inserter(gogo, this);
6994 inserter = &global_inserter;
6997 gogo->lower_expression(function, inserter, &this->init_);
6999 this->seen_ = false;
7001 this->init_is_lowered_ = true;
7005 // Flatten the initialization expression after ordering evaluations.
7007 void
7008 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
7009 Statement_inserter* inserter)
7011 Named_object* dep = gogo->var_depends_on(this);
7012 if (dep != NULL && dep->is_variable())
7013 dep->var_value()->flatten_init_expression(gogo, function, inserter);
7015 if (this->init_ != NULL && !this->init_is_flattened_)
7017 if (this->seen_)
7019 // We will give an error elsewhere, this is just to prevent
7020 // an infinite loop.
7021 return;
7023 this->seen_ = true;
7025 Statement_inserter global_inserter;
7026 if (this->is_global_)
7028 global_inserter = Statement_inserter(gogo, this);
7029 inserter = &global_inserter;
7032 gogo->flatten_expression(function, inserter, &this->init_);
7034 // If an interface conversion is needed, we need a temporary
7035 // variable.
7036 if (this->type_ != NULL
7037 && !Type::are_identical(this->type_, this->init_->type(),
7038 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
7039 NULL)
7040 && this->init_->type()->interface_type() != NULL
7041 && !this->init_->is_variable())
7043 Temporary_statement* temp =
7044 Statement::make_temporary(NULL, this->init_, this->location_);
7045 inserter->insert(temp);
7046 this->init_ = Expression::make_temporary_reference(temp,
7047 this->location_);
7050 this->seen_ = false;
7051 this->init_is_flattened_ = true;
7055 // Get the preinit block.
7057 Block*
7058 Variable::preinit_block(Gogo* gogo)
7060 go_assert(this->is_global_);
7061 if (this->preinit_ == NULL)
7062 this->preinit_ = new Block(NULL, this->location());
7064 // If a global variable has a preinitialization statement, then we
7065 // need to have an initialization function.
7066 gogo->set_need_init_fn();
7068 return this->preinit_;
7071 // Add a statement to be run before the initialization expression.
7073 void
7074 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
7076 Block* b = this->preinit_block(gogo);
7077 b->add_statement(s);
7078 b->set_end_location(s->location());
7081 // Whether this variable has a type.
7083 bool
7084 Variable::has_type() const
7086 if (this->type_ == NULL)
7087 return false;
7089 // A variable created in a type switch case nil does not actually
7090 // have a type yet. It will be changed to use the initializer's
7091 // type in determine_type.
7092 if (this->is_type_switch_var_
7093 && this->type_->is_nil_constant_as_type())
7094 return false;
7096 return true;
7099 // In an assignment which sets a variable to a tuple of EXPR, return
7100 // the type of the first element of the tuple.
7102 Type*
7103 Variable::type_from_tuple(Expression* expr, bool report_error) const
7105 if (expr->map_index_expression() != NULL)
7107 Map_type* mt = expr->map_index_expression()->get_map_type();
7108 if (mt == NULL)
7109 return Type::make_error_type();
7110 return mt->val_type();
7112 else if (expr->receive_expression() != NULL)
7114 Expression* channel = expr->receive_expression()->channel();
7115 Type* channel_type = channel->type();
7116 if (channel_type->channel_type() == NULL)
7117 return Type::make_error_type();
7118 return channel_type->channel_type()->element_type();
7120 else
7122 if (report_error)
7123 go_error_at(this->location(), "invalid tuple definition");
7124 return Type::make_error_type();
7128 // Given EXPR used in a range clause, return either the index type or
7129 // the value type of the range, depending upon GET_INDEX_TYPE.
7131 Type*
7132 Variable::type_from_range(Expression* expr, bool get_index_type,
7133 bool report_error) const
7135 Type* t = expr->type();
7136 if (t->array_type() != NULL
7137 || (t->points_to() != NULL
7138 && t->points_to()->array_type() != NULL
7139 && !t->points_to()->is_slice_type()))
7141 if (get_index_type)
7142 return Type::lookup_integer_type("int");
7143 else
7144 return t->deref()->array_type()->element_type();
7146 else if (t->is_string_type())
7148 if (get_index_type)
7149 return Type::lookup_integer_type("int");
7150 else
7151 return Type::lookup_integer_type("int32");
7153 else if (t->map_type() != NULL)
7155 if (get_index_type)
7156 return t->map_type()->key_type();
7157 else
7158 return t->map_type()->val_type();
7160 else if (t->channel_type() != NULL)
7162 if (get_index_type)
7163 return t->channel_type()->element_type();
7164 else
7166 if (report_error)
7167 go_error_at(this->location(),
7168 ("invalid definition of value variable "
7169 "for channel range"));
7170 return Type::make_error_type();
7173 else
7175 if (report_error)
7176 go_error_at(this->location(), "invalid type for range clause");
7177 return Type::make_error_type();
7181 // EXPR should be a channel. Return the channel's element type.
7183 Type*
7184 Variable::type_from_chan_element(Expression* expr, bool report_error) const
7186 Type* t = expr->type();
7187 if (t->channel_type() != NULL)
7188 return t->channel_type()->element_type();
7189 else
7191 if (report_error)
7192 go_error_at(this->location(), "expected channel");
7193 return Type::make_error_type();
7197 // Return the type of the Variable. This may be called before
7198 // Variable::determine_type is called, which means that we may need to
7199 // get the type from the initializer. FIXME: If we combine lowering
7200 // with type determination, then this should be unnecessary.
7202 Type*
7203 Variable::type()
7205 // A variable in a type switch with a nil case will have the wrong
7206 // type here. This gets fixed up in determine_type, below.
7207 Type* type = this->type_;
7208 Expression* init = this->init_;
7209 if (this->is_type_switch_var_
7210 && type != NULL
7211 && this->type_->is_nil_constant_as_type())
7213 Type_guard_expression* tge = this->init_->type_guard_expression();
7214 go_assert(tge != NULL);
7215 init = tge->expr();
7216 type = NULL;
7219 if (this->seen_)
7221 if (this->type_ == NULL || !this->type_->is_error_type())
7223 go_error_at(this->location_, "variable initializer refers to itself");
7224 this->type_ = Type::make_error_type();
7226 return this->type_;
7229 this->seen_ = true;
7231 if (type != NULL)
7233 else if (this->type_from_init_tuple_)
7234 type = this->type_from_tuple(init, false);
7235 else if (this->type_from_range_index_ || this->type_from_range_value_)
7236 type = this->type_from_range(init, this->type_from_range_index_, false);
7237 else if (this->type_from_chan_element_)
7238 type = this->type_from_chan_element(init, false);
7239 else
7241 go_assert(init != NULL);
7242 type = init->type();
7243 go_assert(type != NULL);
7245 // Variables should not have abstract types.
7246 if (type->is_abstract())
7247 type = type->make_non_abstract_type();
7249 if (type->is_void_type())
7250 type = Type::make_error_type();
7253 this->seen_ = false;
7255 return type;
7258 // Fetch the type from a const pointer, in which case it should have
7259 // been set already.
7261 Type*
7262 Variable::type() const
7264 go_assert(this->type_ != NULL);
7265 return this->type_;
7268 // Set the type if necessary.
7270 void
7271 Variable::determine_type()
7273 if (this->determined_type_)
7274 return;
7275 this->determined_type_ = true;
7277 if (this->preinit_ != NULL)
7278 this->preinit_->determine_types();
7280 // A variable in a type switch with a nil case will have the wrong
7281 // type here. It will have an initializer which is a type guard.
7282 // We want to initialize it to the value without the type guard, and
7283 // use the type of that value as well.
7284 if (this->is_type_switch_var_
7285 && this->type_ != NULL
7286 && this->type_->is_nil_constant_as_type())
7288 Type_guard_expression* tge = this->init_->type_guard_expression();
7289 go_assert(tge != NULL);
7290 this->type_ = NULL;
7291 this->init_ = tge->expr();
7294 if (this->init_ == NULL)
7295 go_assert(this->type_ != NULL && !this->type_->is_abstract());
7296 else if (this->type_from_init_tuple_)
7298 Expression *init = this->init_;
7299 init->determine_type_no_context();
7300 this->type_ = this->type_from_tuple(init, true);
7301 this->init_ = NULL;
7303 else if (this->type_from_range_index_ || this->type_from_range_value_)
7305 Expression* init = this->init_;
7306 init->determine_type_no_context();
7307 this->type_ = this->type_from_range(init, this->type_from_range_index_,
7308 true);
7309 this->init_ = NULL;
7311 else if (this->type_from_chan_element_)
7313 Expression* init = this->init_;
7314 init->determine_type_no_context();
7315 this->type_ = this->type_from_chan_element(init, true);
7316 this->init_ = NULL;
7318 else
7320 Type_context context(this->type_, false);
7321 this->init_->determine_type(&context);
7322 if (this->type_ == NULL)
7324 Type* type = this->init_->type();
7325 go_assert(type != NULL);
7326 if (type->is_abstract())
7327 type = type->make_non_abstract_type();
7329 if (type->is_void_type())
7331 go_error_at(this->location_, "variable has no type");
7332 type = Type::make_error_type();
7334 else if (type->is_nil_type())
7336 go_error_at(this->location_, "variable defined to nil type");
7337 type = Type::make_error_type();
7339 else if (type->is_call_multiple_result_type())
7341 go_error_at(this->location_,
7342 "single variable set to multiple-value function call");
7343 type = Type::make_error_type();
7346 this->type_ = type;
7351 // Get the initial value of a variable. This does not
7352 // consider whether the variable is in the heap--it returns the
7353 // initial value as though it were always stored in the stack.
7355 Bexpression*
7356 Variable::get_init(Gogo* gogo, Named_object* function)
7358 go_assert(this->preinit_ == NULL);
7359 Location loc = this->location();
7360 if (this->init_ == NULL)
7362 go_assert(!this->is_parameter_);
7363 if (this->is_global_ || this->is_in_heap())
7364 return NULL;
7365 Btype* btype = this->type()->get_backend(gogo);
7366 return gogo->backend()->zero_expression(btype);
7368 else
7370 Translate_context context(gogo, function, NULL, NULL);
7371 Expression* init = Expression::make_cast(this->type(), this->init_, loc);
7372 return init->get_backend(&context);
7376 // Get the initial value of a variable when a block is required.
7377 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7379 Bstatement*
7380 Variable::get_init_block(Gogo* gogo, Named_object* function,
7381 Bvariable* var_decl)
7383 go_assert(this->preinit_ != NULL);
7385 // We want to add the variable assignment to the end of the preinit
7386 // block.
7388 Translate_context context(gogo, function, NULL, NULL);
7389 Bblock* bblock = this->preinit_->get_backend(&context);
7390 Bfunction* bfunction =
7391 function->func_value()->get_or_make_decl(gogo, function);
7393 // It's possible to have pre-init statements without an initializer
7394 // if the pre-init statements set the variable.
7395 Bstatement* decl_init = NULL;
7396 if (this->init_ != NULL)
7398 if (var_decl == NULL)
7400 Bexpression* init_bexpr = this->init_->get_backend(&context);
7401 decl_init = gogo->backend()->expression_statement(bfunction,
7402 init_bexpr);
7404 else
7406 Location loc = this->location();
7407 Expression* val_expr =
7408 Expression::make_cast(this->type(), this->init_, loc);
7409 Bexpression* val = val_expr->get_backend(&context);
7410 Bexpression* var_ref =
7411 gogo->backend()->var_expression(var_decl, loc);
7412 decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
7413 val, loc);
7416 Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
7417 if (decl_init != NULL)
7418 block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
7419 return block_stmt;
7422 // Export the variable
7424 void
7425 Variable::export_var(Export* exp, const std::string& name) const
7427 go_assert(this->is_global_);
7428 exp->write_c_string("var ");
7429 exp->write_string(name);
7430 exp->write_c_string(" ");
7431 exp->write_type(this->type());
7432 exp->write_c_string("\n");
7435 // Import a variable.
7437 void
7438 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
7440 imp->require_c_string("var ");
7441 *pname = imp->read_identifier();
7442 imp->require_c_string(" ");
7443 *ptype = imp->read_type();
7444 imp->require_semicolon_if_old_version();
7445 imp->require_c_string("\n");
7448 // Convert a variable to the backend representation.
7450 Bvariable*
7451 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
7452 const Package* package, const std::string& name)
7454 if (this->backend_ == NULL)
7456 Backend* backend = gogo->backend();
7457 Type* type = this->type_;
7458 if (type->is_error_type()
7459 || (type->is_undefined()
7460 && (!this->is_global_ || package == NULL)))
7461 this->backend_ = backend->error_variable();
7462 else
7464 bool is_parameter = this->is_parameter_;
7465 if (this->is_receiver_ && type->points_to() == NULL)
7466 is_parameter = false;
7467 if (this->is_in_heap())
7469 is_parameter = false;
7470 type = Type::make_pointer_type(type);
7473 const std::string n = Gogo::unpack_hidden_name(name);
7474 Btype* btype = type->get_backend(gogo);
7476 Bvariable* bvar;
7477 if (Map_type::is_zero_value(this))
7478 bvar = Map_type::backend_zero_value(gogo);
7479 else if (this->is_global_)
7481 std::string var_name(package != NULL
7482 ? package->package_name()
7483 : gogo->package_name());
7484 var_name.push_back('.');
7485 var_name.append(n);
7487 std::string asm_name(gogo->global_var_asm_name(name, package));
7489 bool is_hidden = Gogo::is_hidden_name(name);
7490 // Hack to export runtime.writeBarrier. FIXME.
7491 // This is because go:linkname doesn't work on variables.
7492 if (gogo->compiling_runtime()
7493 && var_name == "runtime.writeBarrier")
7494 is_hidden = false;
7496 bvar = backend->global_variable(var_name,
7497 asm_name,
7498 btype,
7499 package != NULL,
7500 is_hidden,
7501 this->in_unique_section_,
7502 this->location_);
7504 else if (function == NULL)
7506 go_assert(saw_errors());
7507 bvar = backend->error_variable();
7509 else
7511 Bfunction* bfunction = function->func_value()->get_decl();
7512 bool is_address_taken = (this->is_non_escaping_address_taken_
7513 && !this->is_in_heap());
7514 if (this->is_closure())
7515 bvar = backend->static_chain_variable(bfunction, n, btype,
7516 this->location_);
7517 else if (is_parameter)
7518 bvar = backend->parameter_variable(bfunction, n, btype,
7519 is_address_taken,
7520 this->location_);
7521 else
7523 Bvariable* bvar_decl = NULL;
7524 if (this->toplevel_decl_ != NULL)
7526 Translate_context context(gogo, NULL, NULL, NULL);
7527 bvar_decl = this->toplevel_decl_->temporary_statement()
7528 ->get_backend_variable(&context);
7530 bvar = backend->local_variable(bfunction, n, btype,
7531 bvar_decl,
7532 is_address_taken,
7533 this->location_);
7536 this->backend_ = bvar;
7539 return this->backend_;
7542 // Class Result_variable.
7544 // Convert a result variable to the backend representation.
7546 Bvariable*
7547 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
7548 const std::string& name)
7550 if (this->backend_ == NULL)
7552 Backend* backend = gogo->backend();
7553 Type* type = this->type_;
7554 if (type->is_error())
7555 this->backend_ = backend->error_variable();
7556 else
7558 if (this->is_in_heap())
7559 type = Type::make_pointer_type(type);
7560 Btype* btype = type->get_backend(gogo);
7561 Bfunction* bfunction = function->func_value()->get_decl();
7562 std::string n = Gogo::unpack_hidden_name(name);
7563 bool is_address_taken = (this->is_non_escaping_address_taken_
7564 && !this->is_in_heap());
7565 this->backend_ = backend->local_variable(bfunction, n, btype,
7566 NULL, is_address_taken,
7567 this->location_);
7570 return this->backend_;
7573 // Class Named_constant.
7575 // Set the type of a named constant. This is only used to set the
7576 // type to an error type.
7578 void
7579 Named_constant::set_type(Type* t)
7581 go_assert(this->type_ == NULL || t->is_error_type());
7582 this->type_ = t;
7585 // Traverse the initializer expression.
7588 Named_constant::traverse_expression(Traverse* traverse)
7590 return Expression::traverse(&this->expr_, traverse);
7593 // Determine the type of the constant.
7595 void
7596 Named_constant::determine_type()
7598 if (this->type_ != NULL)
7600 Type_context context(this->type_, false);
7601 this->expr_->determine_type(&context);
7603 else
7605 // A constant may have an abstract type.
7606 Type_context context(NULL, true);
7607 this->expr_->determine_type(&context);
7608 this->type_ = this->expr_->type();
7609 go_assert(this->type_ != NULL);
7613 // Indicate that we found and reported an error for this constant.
7615 void
7616 Named_constant::set_error()
7618 this->type_ = Type::make_error_type();
7619 this->expr_ = Expression::make_error(this->location_);
7622 // Export a constant.
7624 void
7625 Named_constant::export_const(Export* exp, const std::string& name) const
7627 exp->write_c_string("const ");
7628 exp->write_string(name);
7629 exp->write_c_string(" ");
7630 if (!this->type_->is_abstract())
7632 exp->write_type(this->type_);
7633 exp->write_c_string(" ");
7635 exp->write_c_string("= ");
7637 Export_function_body efb(exp, 0);
7638 if (!this->type_->is_abstract())
7639 efb.set_type_context(this->type_);
7640 this->expr()->export_expression(&efb);
7641 exp->write_string(efb.body());
7643 exp->write_c_string("\n");
7646 // Import a constant.
7648 void
7649 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
7650 Expression** pexpr)
7652 imp->require_c_string("const ");
7653 *pname = imp->read_identifier();
7654 imp->require_c_string(" ");
7655 if (imp->peek_char() == '=')
7656 *ptype = NULL;
7657 else
7659 *ptype = imp->read_type();
7660 imp->require_c_string(" ");
7662 imp->require_c_string("= ");
7663 *pexpr = Expression::import_expression(imp, imp->location());
7664 imp->require_semicolon_if_old_version();
7665 imp->require_c_string("\n");
7668 // Get the backend representation.
7670 Bexpression*
7671 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
7673 if (this->bconst_ == NULL)
7675 Translate_context subcontext(gogo, NULL, NULL, NULL);
7676 Type* type = this->type();
7677 Location loc = this->location();
7679 Expression* const_ref = Expression::make_const_reference(const_no, loc);
7680 Bexpression* const_decl = const_ref->get_backend(&subcontext);
7681 if (type != NULL && type->is_numeric_type())
7683 Btype* btype = type->get_backend(gogo);
7684 std::string name = const_no->get_id(gogo);
7685 const_decl =
7686 gogo->backend()->named_constant_expression(btype, name,
7687 const_decl, loc);
7689 this->bconst_ = const_decl;
7691 return this->bconst_;
7694 // Add a method.
7696 Named_object*
7697 Type_declaration::add_method(const std::string& name, Function* function)
7699 Named_object* ret = Named_object::make_function(name, NULL, function);
7700 this->methods_.push_back(ret);
7701 return ret;
7704 // Add a method declaration.
7706 Named_object*
7707 Type_declaration::add_method_declaration(const std::string& name,
7708 Package* package,
7709 Function_type* type,
7710 Location location)
7712 Named_object* ret = Named_object::make_function_declaration(name, package,
7713 type, location);
7714 this->methods_.push_back(ret);
7715 return ret;
7718 // Return whether any methods are defined.
7720 bool
7721 Type_declaration::has_methods() const
7723 return !this->methods_.empty();
7726 // Define methods for the real type.
7728 void
7729 Type_declaration::define_methods(Named_type* nt)
7731 if (this->methods_.empty())
7732 return;
7734 while (nt->is_alias())
7736 Type *t = nt->real_type()->forwarded();
7737 if (t->named_type() != NULL)
7738 nt = t->named_type();
7739 else if (t->forward_declaration_type() != NULL)
7741 Named_object* no = t->forward_declaration_type()->named_object();
7742 Type_declaration* td = no->type_declaration_value();
7743 td->methods_.insert(td->methods_.end(), this->methods_.begin(),
7744 this->methods_.end());
7745 this->methods_.clear();
7746 return;
7748 else
7750 for (std::vector<Named_object*>::const_iterator p =
7751 this->methods_.begin();
7752 p != this->methods_.end();
7753 ++p)
7754 go_error_at((*p)->location(),
7755 ("invalid receiver type "
7756 "(receiver must be a named type"));
7757 return;
7761 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
7762 p != this->methods_.end();
7763 ++p)
7765 if (!(*p)->func_value()->is_sink())
7766 nt->add_existing_method(*p);
7770 // We are using the type. Return true if we should issue a warning.
7772 bool
7773 Type_declaration::using_type()
7775 bool ret = !this->issued_warning_;
7776 this->issued_warning_ = true;
7777 return ret;
7780 // Class Unknown_name.
7782 // Set the real named object.
7784 void
7785 Unknown_name::set_real_named_object(Named_object* no)
7787 go_assert(this->real_named_object_ == NULL);
7788 go_assert(!no->is_unknown());
7789 this->real_named_object_ = no;
7792 // Class Named_object.
7794 Named_object::Named_object(const std::string& name,
7795 const Package* package,
7796 Classification classification)
7797 : name_(name), package_(package), classification_(classification),
7798 is_redefinition_(false)
7800 if (Gogo::is_sink_name(name))
7801 go_assert(classification == NAMED_OBJECT_SINK);
7804 // Make an unknown name. This is used by the parser. The name must
7805 // be resolved later. Unknown names are only added in the current
7806 // package.
7808 Named_object*
7809 Named_object::make_unknown_name(const std::string& name,
7810 Location location)
7812 Named_object* named_object = new Named_object(name, NULL,
7813 NAMED_OBJECT_UNKNOWN);
7814 Unknown_name* value = new Unknown_name(location);
7815 named_object->u_.unknown_value = value;
7816 return named_object;
7819 // Make a constant.
7821 Named_object*
7822 Named_object::make_constant(const Typed_identifier& tid,
7823 const Package* package, Expression* expr,
7824 int iota_value)
7826 Named_object* named_object = new Named_object(tid.name(), package,
7827 NAMED_OBJECT_CONST);
7828 Named_constant* named_constant = new Named_constant(tid.type(), expr,
7829 iota_value,
7830 tid.location());
7831 named_object->u_.const_value = named_constant;
7832 return named_object;
7835 // Make a named type.
7837 Named_object*
7838 Named_object::make_type(const std::string& name, const Package* package,
7839 Type* type, Location location)
7841 Named_object* named_object = new Named_object(name, package,
7842 NAMED_OBJECT_TYPE);
7843 Named_type* named_type = Type::make_named_type(named_object, type, location);
7844 named_object->u_.type_value = named_type;
7845 return named_object;
7848 // Make a type declaration.
7850 Named_object*
7851 Named_object::make_type_declaration(const std::string& name,
7852 const Package* package,
7853 Location location)
7855 Named_object* named_object = new Named_object(name, package,
7856 NAMED_OBJECT_TYPE_DECLARATION);
7857 Type_declaration* type_declaration = new Type_declaration(location);
7858 named_object->u_.type_declaration = type_declaration;
7859 return named_object;
7862 // Make a variable.
7864 Named_object*
7865 Named_object::make_variable(const std::string& name, const Package* package,
7866 Variable* variable)
7868 Named_object* named_object = new Named_object(name, package,
7869 NAMED_OBJECT_VAR);
7870 named_object->u_.var_value = variable;
7871 return named_object;
7874 // Make a result variable.
7876 Named_object*
7877 Named_object::make_result_variable(const std::string& name,
7878 Result_variable* result)
7880 Named_object* named_object = new Named_object(name, NULL,
7881 NAMED_OBJECT_RESULT_VAR);
7882 named_object->u_.result_var_value = result;
7883 return named_object;
7886 // Make a sink. This is used for the special blank identifier _.
7888 Named_object*
7889 Named_object::make_sink()
7891 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
7894 // Make a named function.
7896 Named_object*
7897 Named_object::make_function(const std::string& name, const Package* package,
7898 Function* function)
7900 Named_object* named_object = new Named_object(name, package,
7901 NAMED_OBJECT_FUNC);
7902 named_object->u_.func_value = function;
7903 return named_object;
7906 // Make a function declaration.
7908 Named_object*
7909 Named_object::make_function_declaration(const std::string& name,
7910 const Package* package,
7911 Function_type* fntype,
7912 Location location)
7914 Named_object* named_object = new Named_object(name, package,
7915 NAMED_OBJECT_FUNC_DECLARATION);
7916 Function_declaration *func_decl = new Function_declaration(fntype, location);
7917 named_object->u_.func_declaration_value = func_decl;
7918 return named_object;
7921 // Make a package.
7923 Named_object*
7924 Named_object::make_package(const std::string& alias, Package* package)
7926 Named_object* named_object = new Named_object(alias, NULL,
7927 NAMED_OBJECT_PACKAGE);
7928 named_object->u_.package_value = package;
7929 return named_object;
7932 // Return the name to use in an error message.
7934 std::string
7935 Named_object::message_name() const
7937 if (this->package_ == NULL)
7938 return Gogo::message_name(this->name_);
7939 std::string ret;
7940 if (this->package_->has_package_name())
7941 ret = this->package_->package_name();
7942 else
7943 ret = this->package_->pkgpath();
7944 ret = Gogo::message_name(ret);
7945 ret += '.';
7946 ret += Gogo::message_name(this->name_);
7947 return ret;
7950 // Set the type when a declaration is defined.
7952 void
7953 Named_object::set_type_value(Named_type* named_type)
7955 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
7956 Type_declaration* td = this->u_.type_declaration;
7957 td->define_methods(named_type);
7958 unsigned int index;
7959 Named_object* in_function = td->in_function(&index);
7960 if (in_function != NULL)
7961 named_type->set_in_function(in_function, index);
7962 delete td;
7963 this->classification_ = NAMED_OBJECT_TYPE;
7964 this->u_.type_value = named_type;
7967 // Define a function which was previously declared.
7969 void
7970 Named_object::set_function_value(Function* function)
7972 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
7973 if (this->func_declaration_value()->has_descriptor())
7975 Expression* descriptor =
7976 this->func_declaration_value()->descriptor(NULL, NULL);
7977 function->set_descriptor(descriptor);
7979 this->classification_ = NAMED_OBJECT_FUNC;
7980 // FIXME: We should free the old value.
7981 this->u_.func_value = function;
7984 // Declare an unknown object as a type declaration.
7986 void
7987 Named_object::declare_as_type()
7989 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
7990 Unknown_name* unk = this->u_.unknown_value;
7991 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
7992 this->u_.type_declaration = new Type_declaration(unk->location());
7993 delete unk;
7996 // Return the location of a named object.
7998 Location
7999 Named_object::location() const
8001 switch (this->classification_)
8003 default:
8004 case NAMED_OBJECT_UNINITIALIZED:
8005 go_unreachable();
8007 case NAMED_OBJECT_ERRONEOUS:
8008 return Linemap::unknown_location();
8010 case NAMED_OBJECT_UNKNOWN:
8011 return this->unknown_value()->location();
8013 case NAMED_OBJECT_CONST:
8014 return this->const_value()->location();
8016 case NAMED_OBJECT_TYPE:
8017 return this->type_value()->location();
8019 case NAMED_OBJECT_TYPE_DECLARATION:
8020 return this->type_declaration_value()->location();
8022 case NAMED_OBJECT_VAR:
8023 return this->var_value()->location();
8025 case NAMED_OBJECT_RESULT_VAR:
8026 return this->result_var_value()->location();
8028 case NAMED_OBJECT_SINK:
8029 go_unreachable();
8031 case NAMED_OBJECT_FUNC:
8032 return this->func_value()->location();
8034 case NAMED_OBJECT_FUNC_DECLARATION:
8035 return this->func_declaration_value()->location();
8037 case NAMED_OBJECT_PACKAGE:
8038 return this->package_value()->location();
8042 // Export a named object.
8044 void
8045 Named_object::export_named_object(Export* exp) const
8047 switch (this->classification_)
8049 default:
8050 case NAMED_OBJECT_UNINITIALIZED:
8051 case NAMED_OBJECT_UNKNOWN:
8052 go_unreachable();
8054 case NAMED_OBJECT_ERRONEOUS:
8055 break;
8057 case NAMED_OBJECT_CONST:
8058 this->const_value()->export_const(exp, this->name_);
8059 break;
8061 case NAMED_OBJECT_TYPE:
8062 // Types are handled by export::write_types.
8063 go_unreachable();
8065 case NAMED_OBJECT_TYPE_DECLARATION:
8066 go_error_at(this->type_declaration_value()->location(),
8067 "attempt to export %<%s%> which was declared but not defined",
8068 this->message_name().c_str());
8069 break;
8071 case NAMED_OBJECT_FUNC_DECLARATION:
8072 this->func_declaration_value()->export_func(exp, this->name_);
8073 break;
8075 case NAMED_OBJECT_VAR:
8076 this->var_value()->export_var(exp, this->name_);
8077 break;
8079 case NAMED_OBJECT_RESULT_VAR:
8080 case NAMED_OBJECT_SINK:
8081 go_unreachable();
8083 case NAMED_OBJECT_FUNC:
8084 this->func_value()->export_func(exp, this->name_);
8085 break;
8089 // Convert a variable to the backend representation.
8091 Bvariable*
8092 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
8094 if (this->classification_ == NAMED_OBJECT_VAR)
8095 return this->var_value()->get_backend_variable(gogo, function,
8096 this->package_, this->name_);
8097 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
8098 return this->result_var_value()->get_backend_variable(gogo, function,
8099 this->name_);
8100 else
8101 go_unreachable();
8104 // Return the external identifier for this object.
8106 std::string
8107 Named_object::get_id(Gogo* gogo)
8109 go_assert(!this->is_variable()
8110 && !this->is_result_variable()
8111 && !this->is_type());
8112 std::string decl_name;
8113 if (this->is_function_declaration()
8114 && !this->func_declaration_value()->asm_name().empty())
8115 decl_name = this->func_declaration_value()->asm_name();
8116 else
8118 std::string package_name;
8119 if (this->package_ == NULL)
8120 package_name = gogo->package_name();
8121 else
8122 package_name = this->package_->package_name();
8124 // Note that this will be misleading if this is an unexported
8125 // method generated for an embedded imported type. In that case
8126 // the unexported method should have the package name of the
8127 // package from which it is imported, but we are going to give
8128 // it our package name. Fixing this would require knowing the
8129 // package name, but we only know the package path. It might be
8130 // better to use package paths here anyhow. This doesn't affect
8131 // the assembler code, because we always set that name in
8132 // Function::get_or_make_decl anyhow. FIXME.
8134 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
8136 Function_type* fntype;
8137 if (this->is_function())
8138 fntype = this->func_value()->type();
8139 else if (this->is_function_declaration())
8140 fntype = this->func_declaration_value()->type();
8141 else
8142 fntype = NULL;
8143 if (fntype != NULL && fntype->is_method())
8145 decl_name.push_back('.');
8146 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
8149 return decl_name;
8152 // Get the backend representation for this named object.
8154 void
8155 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
8156 std::vector<Btype*>& type_decls,
8157 std::vector<Bfunction*>& func_decls)
8159 // If this is a definition, avoid trying to get the backend
8160 // representation, as that can crash.
8161 if (this->is_redefinition_)
8163 go_assert(saw_errors());
8164 return;
8167 switch (this->classification_)
8169 case NAMED_OBJECT_CONST:
8170 if (!Gogo::is_erroneous_name(this->name_))
8171 const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
8172 break;
8174 case NAMED_OBJECT_TYPE:
8176 Named_type* named_type = this->u_.type_value;
8177 if (!Gogo::is_erroneous_name(this->name_) && !named_type->is_alias())
8178 type_decls.push_back(named_type->get_backend(gogo));
8180 // We need to produce a type descriptor for every named
8181 // type, and for a pointer to every named type, since
8182 // other files or packages might refer to them. We need
8183 // to do this even for hidden types, because they might
8184 // still be returned by some function. Simply calling the
8185 // type_descriptor method is enough to create the type
8186 // descriptor, even though we don't do anything with it.
8187 if (this->package_ == NULL && !saw_errors())
8189 named_type->
8190 type_descriptor_pointer(gogo, Linemap::predeclared_location());
8191 named_type->gc_symbol_pointer(gogo);
8192 Type* pn = Type::make_pointer_type(named_type);
8193 pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
8194 pn->gc_symbol_pointer(gogo);
8197 break;
8199 case NAMED_OBJECT_TYPE_DECLARATION:
8200 go_error_at(Linemap::unknown_location(),
8201 "reference to undefined type %qs",
8202 this->message_name().c_str());
8203 return;
8205 case NAMED_OBJECT_VAR:
8206 case NAMED_OBJECT_RESULT_VAR:
8207 case NAMED_OBJECT_SINK:
8208 go_unreachable();
8210 case NAMED_OBJECT_FUNC:
8212 Function* func = this->u_.func_value;
8213 if (!Gogo::is_erroneous_name(this->name_))
8214 func_decls.push_back(func->get_or_make_decl(gogo, this));
8216 if (func->block() != NULL)
8217 func->build(gogo, this);
8219 break;
8221 case NAMED_OBJECT_ERRONEOUS:
8222 break;
8224 default:
8225 go_unreachable();
8229 // Class Bindings.
8231 Bindings::Bindings(Bindings* enclosing)
8232 : enclosing_(enclosing), named_objects_(), bindings_()
8236 // Clear imports.
8238 void
8239 Bindings::clear_file_scope(Gogo* gogo)
8241 Contour::iterator p = this->bindings_.begin();
8242 while (p != this->bindings_.end())
8244 bool keep;
8245 if (p->second->package() != NULL)
8246 keep = false;
8247 else if (p->second->is_package())
8248 keep = false;
8249 else if (p->second->is_function()
8250 && !p->second->func_value()->type()->is_method()
8251 && Gogo::unpack_hidden_name(p->second->name()) == "init")
8252 keep = false;
8253 else
8254 keep = true;
8256 if (keep)
8257 ++p;
8258 else
8260 gogo->add_file_block_name(p->second->name(), p->second->location());
8261 p = this->bindings_.erase(p);
8266 // Look up a symbol.
8268 Named_object*
8269 Bindings::lookup(const std::string& name) const
8271 Contour::const_iterator p = this->bindings_.find(name);
8272 if (p != this->bindings_.end())
8273 return p->second->resolve();
8274 else if (this->enclosing_ != NULL)
8275 return this->enclosing_->lookup(name);
8276 else
8277 return NULL;
8280 // Look up a symbol locally.
8282 Named_object*
8283 Bindings::lookup_local(const std::string& name) const
8285 Contour::const_iterator p = this->bindings_.find(name);
8286 if (p == this->bindings_.end())
8287 return NULL;
8288 return p->second;
8291 // Remove an object from a set of bindings. This is used for a
8292 // special case in thunks for functions which call recover.
8294 void
8295 Bindings::remove_binding(Named_object* no)
8297 Contour::iterator pb = this->bindings_.find(no->name());
8298 go_assert(pb != this->bindings_.end());
8299 this->bindings_.erase(pb);
8300 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
8301 pn != this->named_objects_.end();
8302 ++pn)
8304 if (*pn == no)
8306 this->named_objects_.erase(pn);
8307 return;
8310 go_unreachable();
8313 // Add a method to the list of objects. This is not added to the
8314 // lookup table. This is so that we have a single list of objects
8315 // declared at the top level, which we walk through when it's time to
8316 // convert to trees.
8318 void
8319 Bindings::add_method(Named_object* method)
8321 this->named_objects_.push_back(method);
8324 // Add a generic Named_object to a Contour.
8326 Named_object*
8327 Bindings::add_named_object_to_contour(Contour* contour,
8328 Named_object* named_object)
8330 go_assert(named_object == named_object->resolve());
8331 const std::string& name(named_object->name());
8332 go_assert(!Gogo::is_sink_name(name));
8334 std::pair<Contour::iterator, bool> ins =
8335 contour->insert(std::make_pair(name, named_object));
8336 if (!ins.second)
8338 // The name was already there.
8339 if (named_object->package() != NULL
8340 && ins.first->second->package() == named_object->package()
8341 && (ins.first->second->classification()
8342 == named_object->classification()))
8344 // This is a second import of the same object.
8345 return ins.first->second;
8347 ins.first->second = this->new_definition(ins.first->second,
8348 named_object);
8349 return ins.first->second;
8351 else
8353 // Don't push declarations on the list. We push them on when
8354 // and if we find the definitions. That way we genericize the
8355 // functions in order.
8356 if (!named_object->is_type_declaration()
8357 && !named_object->is_function_declaration()
8358 && !named_object->is_unknown())
8359 this->named_objects_.push_back(named_object);
8360 return named_object;
8364 // We had an existing named object OLD_OBJECT, and we've seen a new
8365 // one NEW_OBJECT with the same name. FIXME: This does not free the
8366 // new object when we don't need it.
8368 Named_object*
8369 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
8371 if (new_object->is_erroneous() && !old_object->is_erroneous())
8372 return new_object;
8374 std::string reason;
8375 switch (old_object->classification())
8377 default:
8378 case Named_object::NAMED_OBJECT_UNINITIALIZED:
8379 go_unreachable();
8381 case Named_object::NAMED_OBJECT_ERRONEOUS:
8382 return old_object;
8384 case Named_object::NAMED_OBJECT_UNKNOWN:
8386 Named_object* real = old_object->unknown_value()->real_named_object();
8387 if (real != NULL)
8388 return this->new_definition(real, new_object);
8389 go_assert(!new_object->is_unknown());
8390 old_object->unknown_value()->set_real_named_object(new_object);
8391 if (!new_object->is_type_declaration()
8392 && !new_object->is_function_declaration())
8393 this->named_objects_.push_back(new_object);
8394 return new_object;
8397 case Named_object::NAMED_OBJECT_CONST:
8398 break;
8400 case Named_object::NAMED_OBJECT_TYPE:
8401 if (new_object->is_type_declaration())
8402 return old_object;
8403 break;
8405 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8406 if (new_object->is_type_declaration())
8407 return old_object;
8408 if (new_object->is_type())
8410 old_object->set_type_value(new_object->type_value());
8411 new_object->type_value()->set_named_object(old_object);
8412 this->named_objects_.push_back(old_object);
8413 return old_object;
8415 break;
8417 case Named_object::NAMED_OBJECT_VAR:
8418 case Named_object::NAMED_OBJECT_RESULT_VAR:
8419 // We have already given an error in the parser for cases where
8420 // one parameter or result variable redeclares another one.
8421 if ((new_object->is_variable()
8422 && new_object->var_value()->is_parameter())
8423 || new_object->is_result_variable())
8424 return old_object;
8425 break;
8427 case Named_object::NAMED_OBJECT_SINK:
8428 go_unreachable();
8430 case Named_object::NAMED_OBJECT_FUNC:
8431 break;
8433 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8435 // We declare the hash and equality functions before defining
8436 // them, because we sometimes see that we need the declaration
8437 // while we are in the middle of a different function.
8439 // We declare the main function before the user defines it, to
8440 // give better error messages.
8442 // We declare inline functions before we define them, as we
8443 // only define them if we need them.
8444 if (new_object->is_function()
8445 && ((Linemap::is_predeclared_location(old_object->location())
8446 && Linemap::is_predeclared_location(new_object->location()))
8447 || (Gogo::unpack_hidden_name(old_object->name()) == "main"
8448 && Linemap::is_unknown_location(old_object->location()))
8449 || (new_object->package() != NULL
8450 && old_object->func_declaration_value()->has_imported_body()
8451 && new_object->func_value()->is_inline_only())))
8453 Function_type* old_type =
8454 old_object->func_declaration_value()->type();
8455 Function_type* new_type = new_object->func_value()->type();
8456 if (old_type->is_valid_redeclaration(new_type, &reason))
8458 Function_declaration* fd =
8459 old_object->func_declaration_value();
8460 go_assert(fd->asm_name().empty());
8461 old_object->set_function_value(new_object->func_value());
8462 this->named_objects_.push_back(old_object);
8463 return old_object;
8467 break;
8469 case Named_object::NAMED_OBJECT_PACKAGE:
8470 break;
8473 std::string n = old_object->message_name();
8474 if (reason.empty())
8475 go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
8476 else
8477 go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
8478 reason.c_str());
8479 old_object->set_is_redefinition();
8480 new_object->set_is_redefinition();
8482 if (!Linemap::is_unknown_location(old_object->location())
8483 && !Linemap::is_predeclared_location(old_object->location()))
8484 go_inform(old_object->location(), "previous definition of %qs was here",
8485 n.c_str());
8487 return old_object;
8490 // Add a named type.
8492 Named_object*
8493 Bindings::add_named_type(Named_type* named_type)
8495 return this->add_named_object(named_type->named_object());
8498 // Add a function.
8500 Named_object*
8501 Bindings::add_function(const std::string& name, const Package* package,
8502 Function* function)
8504 return this->add_named_object(Named_object::make_function(name, package,
8505 function));
8508 // Add a function declaration.
8510 Named_object*
8511 Bindings::add_function_declaration(const std::string& name,
8512 const Package* package,
8513 Function_type* type,
8514 Location location)
8516 Named_object* no = Named_object::make_function_declaration(name, package,
8517 type, location);
8518 return this->add_named_object(no);
8521 // Define a type which was previously declared.
8523 void
8524 Bindings::define_type(Named_object* no, Named_type* type)
8526 no->set_type_value(type);
8527 this->named_objects_.push_back(no);
8530 // Mark all local variables as used. This is used for some types of
8531 // parse error.
8533 void
8534 Bindings::mark_locals_used()
8536 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
8537 p != this->named_objects_.end();
8538 ++p)
8539 if ((*p)->is_variable())
8540 (*p)->var_value()->set_is_used();
8543 // Traverse bindings.
8546 Bindings::traverse(Traverse* traverse, bool is_global)
8548 unsigned int traverse_mask = traverse->traverse_mask();
8550 // We don't use an iterator because we permit the traversal to add
8551 // new global objects.
8552 const unsigned int e_or_t = (Traverse::traverse_expressions
8553 | Traverse::traverse_types);
8554 const unsigned int e_or_t_or_s = (e_or_t
8555 | Traverse::traverse_statements);
8556 for (size_t i = 0; i < this->named_objects_.size(); ++i)
8558 Named_object* p = this->named_objects_[i];
8559 int t = TRAVERSE_CONTINUE;
8560 switch (p->classification())
8562 case Named_object::NAMED_OBJECT_CONST:
8563 if ((traverse_mask & Traverse::traverse_constants) != 0)
8564 t = traverse->constant(p, is_global);
8565 if (t == TRAVERSE_CONTINUE
8566 && (traverse_mask & e_or_t) != 0)
8568 Type* tc = p->const_value()->type();
8569 if (tc != NULL
8570 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
8571 return TRAVERSE_EXIT;
8572 t = p->const_value()->traverse_expression(traverse);
8574 break;
8576 case Named_object::NAMED_OBJECT_VAR:
8577 case Named_object::NAMED_OBJECT_RESULT_VAR:
8578 if ((traverse_mask & Traverse::traverse_variables) != 0)
8579 t = traverse->variable(p);
8580 if (t == TRAVERSE_CONTINUE
8581 && (traverse_mask & e_or_t) != 0)
8583 if (p->is_result_variable()
8584 || p->var_value()->has_type())
8586 Type* tv = (p->is_variable()
8587 ? p->var_value()->type()
8588 : p->result_var_value()->type());
8589 if (tv != NULL
8590 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
8591 return TRAVERSE_EXIT;
8594 if (t == TRAVERSE_CONTINUE
8595 && (traverse_mask & e_or_t_or_s) != 0
8596 && p->is_variable())
8597 t = p->var_value()->traverse_expression(traverse, traverse_mask);
8598 break;
8600 case Named_object::NAMED_OBJECT_FUNC:
8601 if ((traverse_mask & Traverse::traverse_functions) != 0)
8602 t = traverse->function(p);
8604 if (t == TRAVERSE_CONTINUE
8605 && (traverse_mask
8606 & (Traverse::traverse_variables
8607 | Traverse::traverse_constants
8608 | Traverse::traverse_functions
8609 | Traverse::traverse_blocks
8610 | Traverse::traverse_statements
8611 | Traverse::traverse_expressions
8612 | Traverse::traverse_types)) != 0)
8613 t = p->func_value()->traverse(traverse);
8614 break;
8616 case Named_object::NAMED_OBJECT_PACKAGE:
8617 // These are traversed in Gogo::traverse.
8618 go_assert(is_global);
8619 break;
8621 case Named_object::NAMED_OBJECT_TYPE:
8622 if ((traverse_mask & e_or_t) != 0)
8623 t = Type::traverse(p->type_value(), traverse);
8624 break;
8626 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8627 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8628 case Named_object::NAMED_OBJECT_UNKNOWN:
8629 case Named_object::NAMED_OBJECT_ERRONEOUS:
8630 break;
8632 case Named_object::NAMED_OBJECT_SINK:
8633 default:
8634 go_unreachable();
8637 if (t == TRAVERSE_EXIT)
8638 return TRAVERSE_EXIT;
8641 // If we need to traverse types, check the function declarations,
8642 // which have types. Also check any methods of a type declaration.
8643 if ((traverse_mask & e_or_t) != 0)
8645 for (Bindings::const_declarations_iterator p =
8646 this->begin_declarations();
8647 p != this->end_declarations();
8648 ++p)
8650 if (p->second->is_function_declaration())
8652 if (Type::traverse(p->second->func_declaration_value()->type(),
8653 traverse)
8654 == TRAVERSE_EXIT)
8655 return TRAVERSE_EXIT;
8657 else if (p->second->is_type_declaration())
8659 const std::vector<Named_object*>* methods =
8660 p->second->type_declaration_value()->methods();
8661 for (std::vector<Named_object*>::const_iterator pm =
8662 methods->begin();
8663 pm != methods->end();
8664 pm++)
8666 Named_object* no = *pm;
8667 Type *t;
8668 if (no->is_function())
8669 t = no->func_value()->type();
8670 else if (no->is_function_declaration())
8671 t = no->func_declaration_value()->type();
8672 else
8673 continue;
8674 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
8675 return TRAVERSE_EXIT;
8681 // Traverse function declarations when needed.
8682 if ((traverse_mask & Traverse::traverse_func_declarations) != 0)
8684 for (Bindings::const_declarations_iterator p = this->begin_declarations();
8685 p != this->end_declarations();
8686 ++p)
8688 if (p->second->is_function_declaration())
8690 if (traverse->function_declaration(p->second) == TRAVERSE_EXIT)
8691 return TRAVERSE_EXIT;
8696 return TRAVERSE_CONTINUE;
8699 // Class Label.
8701 // Clear any references to this label.
8703 void
8704 Label::clear_refs()
8706 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
8707 p != this->refs_.end();
8708 ++p)
8709 delete *p;
8710 this->refs_.clear();
8713 // Get the backend representation for a label.
8715 Blabel*
8716 Label::get_backend_label(Translate_context* context)
8718 if (this->blabel_ == NULL)
8720 Function* function = context->function()->func_value();
8721 Bfunction* bfunction = function->get_decl();
8722 this->blabel_ = context->backend()->label(bfunction, this->name_,
8723 this->location_);
8725 return this->blabel_;
8728 // Return an expression for the address of this label.
8730 Bexpression*
8731 Label::get_addr(Translate_context* context, Location location)
8733 Blabel* label = this->get_backend_label(context);
8734 return context->backend()->label_address(label, location);
8737 // Return the dummy label that represents any instance of the blank label.
8739 Label*
8740 Label::create_dummy_label()
8742 static Label* dummy_label;
8743 if (dummy_label == NULL)
8745 dummy_label = new Label("_");
8746 dummy_label->set_is_used();
8748 return dummy_label;
8751 // Class Unnamed_label.
8753 // Get the backend representation for an unnamed label.
8755 Blabel*
8756 Unnamed_label::get_blabel(Translate_context* context)
8758 if (this->blabel_ == NULL)
8760 Function* function = context->function()->func_value();
8761 Bfunction* bfunction = function->get_decl();
8762 this->blabel_ = context->backend()->label(bfunction, "",
8763 this->location_);
8765 return this->blabel_;
8768 // Return a statement which defines this unnamed label.
8770 Bstatement*
8771 Unnamed_label::get_definition(Translate_context* context)
8773 Blabel* blabel = this->get_blabel(context);
8774 return context->backend()->label_definition_statement(blabel);
8777 // Return a goto statement to this unnamed label.
8779 Bstatement*
8780 Unnamed_label::get_goto(Translate_context* context, Location location)
8782 Blabel* blabel = this->get_blabel(context);
8783 return context->backend()->goto_statement(blabel, location);
8786 // Class Package.
8788 Package::Package(const std::string& pkgpath,
8789 const std::string& pkgpath_symbol, Location location)
8790 : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
8791 package_name_(), bindings_(new Bindings(NULL)),
8792 location_(location)
8794 go_assert(!pkgpath.empty());
8797 // Set the package name.
8799 void
8800 Package::set_package_name(const std::string& package_name, Location location)
8802 go_assert(!package_name.empty());
8803 if (this->package_name_.empty())
8804 this->package_name_ = package_name;
8805 else if (this->package_name_ != package_name)
8806 go_error_at(location,
8807 ("saw two different packages with "
8808 "the same package path %s: %s, %s"),
8809 this->pkgpath_.c_str(), this->package_name_.c_str(),
8810 package_name.c_str());
8813 // Return the pkgpath symbol, which is a prefix for symbols defined in
8814 // this package.
8816 std::string
8817 Package::pkgpath_symbol() const
8819 if (this->pkgpath_symbol_.empty())
8820 return Gogo::pkgpath_for_symbol(this->pkgpath_);
8821 return this->pkgpath_symbol_;
8824 // Set the package path symbol.
8826 void
8827 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
8829 go_assert(!pkgpath_symbol.empty());
8830 if (this->pkgpath_symbol_.empty())
8831 this->pkgpath_symbol_ = pkgpath_symbol;
8832 else
8833 go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
8836 // Note that symbol from this package was and qualified by ALIAS.
8838 void
8839 Package::note_usage(const std::string& alias) const
8841 Aliases::const_iterator p = this->aliases_.find(alias);
8842 go_assert(p != this->aliases_.end());
8843 p->second->note_usage();
8846 // Forget a given usage. If forgetting this usage means this package becomes
8847 // unused, report that error.
8849 void
8850 Package::forget_usage(Expression* usage) const
8852 if (this->fake_uses_.empty())
8853 return;
8855 std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
8856 go_assert(p != this->fake_uses_.end());
8857 this->fake_uses_.erase(p);
8859 if (this->fake_uses_.empty())
8860 go_error_at(this->location(), "imported and not used: %s",
8861 Gogo::message_name(this->package_name()).c_str());
8864 // Clear the used field for the next file. If the only usages of this package
8865 // are possibly fake, keep the fake usages for lowering.
8867 void
8868 Package::clear_used()
8870 std::string dot_alias = "." + this->package_name();
8871 Aliases::const_iterator p = this->aliases_.find(dot_alias);
8872 if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
8873 this->fake_uses_.clear();
8875 this->aliases_.clear();
8878 Package_alias*
8879 Package::add_alias(const std::string& alias, Location location)
8881 Aliases::const_iterator p = this->aliases_.find(alias);
8882 if (p == this->aliases_.end())
8884 std::pair<Aliases::iterator, bool> ret;
8885 ret = this->aliases_.insert(std::make_pair(alias,
8886 new Package_alias(location)));
8887 p = ret.first;
8889 return p->second;
8892 // Determine types of constants. Everything else in a package
8893 // (variables, function declarations) should already have a fixed
8894 // type. Constants may have abstract types.
8896 void
8897 Package::determine_types()
8899 Bindings* bindings = this->bindings_;
8900 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
8901 p != bindings->end_definitions();
8902 ++p)
8904 if ((*p)->is_const())
8905 (*p)->const_value()->determine_type();
8909 // Class Traverse.
8911 // Destructor.
8913 Traverse::~Traverse()
8915 if (this->types_seen_ != NULL)
8916 delete this->types_seen_;
8917 if (this->expressions_seen_ != NULL)
8918 delete this->expressions_seen_;
8921 // Record that we are looking at a type, and return true if we have
8922 // already seen it.
8924 bool
8925 Traverse::remember_type(const Type* type)
8927 if (type->is_error_type())
8928 return true;
8929 go_assert((this->traverse_mask() & traverse_types) != 0
8930 || (this->traverse_mask() & traverse_expressions) != 0);
8931 // We mostly only have to remember named types. But it turns out
8932 // that an interface type can refer to itself without using a name
8933 // by relying on interface inheritance, as in
8935 // type I interface { F() interface{I} }
8937 // Similarly it is possible for array types to refer to themselves
8938 // without a name, e.g.
8940 // var x [uintptr(unsafe.Sizeof(&x))]byte
8942 if (type->classification() != Type::TYPE_NAMED
8943 && type->classification() != Type::TYPE_ARRAY
8944 && type->classification() != Type::TYPE_INTERFACE)
8945 return false;
8946 if (this->types_seen_ == NULL)
8947 this->types_seen_ = new Types_seen();
8948 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
8949 return !ins.second;
8952 // Record that we are looking at an expression, and return true if we
8953 // have already seen it. NB: this routine used to assert if the traverse
8954 // mask did not include expressions/types -- this is no longer the case,
8955 // since it can be useful to remember specific expressions during
8956 // walks that only cover statements.
8958 bool
8959 Traverse::remember_expression(const Expression* expression)
8961 if (this->expressions_seen_ == NULL)
8962 this->expressions_seen_ = new Expressions_seen();
8963 std::pair<Expressions_seen::iterator, bool> ins =
8964 this->expressions_seen_->insert(expression);
8965 return !ins.second;
8968 // The default versions of these functions should never be called: the
8969 // traversal mask indicates which functions may be called.
8972 Traverse::variable(Named_object*)
8974 go_unreachable();
8978 Traverse::constant(Named_object*, bool)
8980 go_unreachable();
8984 Traverse::function(Named_object*)
8986 go_unreachable();
8990 Traverse::block(Block*)
8992 go_unreachable();
8996 Traverse::statement(Block*, size_t*, Statement*)
8998 go_unreachable();
9002 Traverse::expression(Expression**)
9004 go_unreachable();
9008 Traverse::type(Type*)
9010 go_unreachable();
9014 Traverse::function_declaration(Named_object*)
9016 go_unreachable();
9019 // Class Statement_inserter.
9021 void
9022 Statement_inserter::insert(Statement* s)
9024 if (this->statements_added_ != NULL)
9025 this->statements_added_->insert(s);
9027 if (this->block_ != NULL)
9029 go_assert(this->pindex_ != NULL);
9030 this->block_->insert_statement_before(*this->pindex_, s);
9031 ++*this->pindex_;
9033 else if (this->var_ != NULL)
9034 this->var_->add_preinit_statement(this->gogo_, s);
9035 else
9036 go_assert(saw_errors());