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.
13 #include "statements.h"
14 #include "expressions.h"
24 Gogo::Gogo(Backend* backend, int int_type_size, int pointer_size)
28 globals_(new Bindings(NULL)),
30 imported_unsafe_(false),
37 unique_prefix_specified_(false),
39 named_types_are_converted_(false)
41 const source_location loc = BUILTINS_LOCATION;
43 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
44 RUNTIME_TYPE_KIND_UINT8);
45 this->add_named_type(uint8_type);
46 this->add_named_type(Type::make_integer_type("uint16", true, 16,
47 RUNTIME_TYPE_KIND_UINT16));
48 this->add_named_type(Type::make_integer_type("uint32", true, 32,
49 RUNTIME_TYPE_KIND_UINT32));
50 this->add_named_type(Type::make_integer_type("uint64", true, 64,
51 RUNTIME_TYPE_KIND_UINT64));
53 this->add_named_type(Type::make_integer_type("int8", false, 8,
54 RUNTIME_TYPE_KIND_INT8));
55 this->add_named_type(Type::make_integer_type("int16", false, 16,
56 RUNTIME_TYPE_KIND_INT16));
57 this->add_named_type(Type::make_integer_type("int32", false, 32,
58 RUNTIME_TYPE_KIND_INT32));
59 this->add_named_type(Type::make_integer_type("int64", false, 64,
60 RUNTIME_TYPE_KIND_INT64));
62 this->add_named_type(Type::make_float_type("float32", 32,
63 RUNTIME_TYPE_KIND_FLOAT32));
64 this->add_named_type(Type::make_float_type("float64", 64,
65 RUNTIME_TYPE_KIND_FLOAT64));
67 this->add_named_type(Type::make_complex_type("complex64", 64,
68 RUNTIME_TYPE_KIND_COMPLEX64));
69 this->add_named_type(Type::make_complex_type("complex128", 128,
70 RUNTIME_TYPE_KIND_COMPLEX128));
72 if (int_type_size < 32)
74 this->add_named_type(Type::make_integer_type("uint", true,
76 RUNTIME_TYPE_KIND_UINT));
77 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
78 RUNTIME_TYPE_KIND_INT);
79 this->add_named_type(int_type);
81 // "byte" is an alias for "uint8". Construct a Named_object which
82 // points to UINT8_TYPE. Note that this breaks the normal pairing
83 // in which a Named_object points to a Named_type which points back
84 // to the same Named_object.
85 Named_object* byte_type = this->declare_type("byte", loc);
86 byte_type->set_type_value(uint8_type);
88 this->add_named_type(Type::make_integer_type("uintptr", true,
90 RUNTIME_TYPE_KIND_UINTPTR));
92 this->add_named_type(Type::make_named_bool_type());
94 this->add_named_type(Type::make_named_string_type());
96 this->globals_->add_constant(Typed_identifier("true",
97 Type::make_boolean_type(),
100 Expression::make_boolean(true, loc),
102 this->globals_->add_constant(Typed_identifier("false",
103 Type::make_boolean_type(),
106 Expression::make_boolean(false, loc),
109 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
112 Expression::make_nil(loc),
115 Type* abstract_int_type = Type::make_abstract_integer_type();
116 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
119 Expression::make_iota(),
122 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
123 new_type->set_is_varargs();
124 new_type->set_is_builtin();
125 this->globals_->add_function_declaration("new", NULL, new_type, loc);
127 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
128 make_type->set_is_varargs();
129 make_type->set_is_builtin();
130 this->globals_->add_function_declaration("make", NULL, make_type, loc);
132 Typed_identifier_list* len_result = new Typed_identifier_list();
133 len_result->push_back(Typed_identifier("", int_type, loc));
134 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
136 len_type->set_is_builtin();
137 this->globals_->add_function_declaration("len", NULL, len_type, loc);
139 Typed_identifier_list* cap_result = new Typed_identifier_list();
140 cap_result->push_back(Typed_identifier("", int_type, loc));
141 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
143 cap_type->set_is_builtin();
144 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
146 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
147 print_type->set_is_varargs();
148 print_type->set_is_builtin();
149 this->globals_->add_function_declaration("print", NULL, print_type, loc);
151 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
152 print_type->set_is_varargs();
153 print_type->set_is_builtin();
154 this->globals_->add_function_declaration("println", NULL, print_type, loc);
156 Type *empty = Type::make_interface_type(NULL, loc);
157 Typed_identifier_list* panic_parms = new Typed_identifier_list();
158 panic_parms->push_back(Typed_identifier("e", empty, loc));
159 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
161 panic_type->set_is_builtin();
162 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
164 Typed_identifier_list* recover_result = new Typed_identifier_list();
165 recover_result->push_back(Typed_identifier("", empty, loc));
166 Function_type* recover_type = Type::make_function_type(NULL, NULL,
169 recover_type->set_is_builtin();
170 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
172 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
173 close_type->set_is_varargs();
174 close_type->set_is_builtin();
175 this->globals_->add_function_declaration("close", NULL, close_type, loc);
177 Typed_identifier_list* copy_result = new Typed_identifier_list();
178 copy_result->push_back(Typed_identifier("", int_type, loc));
179 Function_type* copy_type = Type::make_function_type(NULL, NULL,
181 copy_type->set_is_varargs();
182 copy_type->set_is_builtin();
183 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
185 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
186 append_type->set_is_varargs();
187 append_type->set_is_builtin();
188 this->globals_->add_function_declaration("append", NULL, append_type, loc);
190 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
191 complex_type->set_is_varargs();
192 complex_type->set_is_builtin();
193 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
195 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
196 real_type->set_is_varargs();
197 real_type->set_is_builtin();
198 this->globals_->add_function_declaration("real", NULL, real_type, loc);
200 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
201 imag_type->set_is_varargs();
202 imag_type->set_is_builtin();
203 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
206 // Munge name for use in an error message.
209 Gogo::message_name(const std::string& name)
211 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
214 // Get the package name.
217 Gogo::package_name() const
219 go_assert(this->package_ != NULL);
220 return this->package_->name();
223 // Set the package name.
226 Gogo::set_package_name(const std::string& package_name,
227 source_location location)
229 if (this->package_ != NULL && this->package_->name() != package_name)
231 error_at(location, "expected package %<%s%>",
232 Gogo::message_name(this->package_->name()).c_str());
236 // If the user did not specify a unique prefix, we always use "go".
237 // This in effect requires that the package name be unique.
238 if (this->unique_prefix_.empty())
239 this->unique_prefix_ = "go";
241 this->package_ = this->register_package(package_name, this->unique_prefix_,
244 // We used to permit people to qualify symbols with the current
245 // package name (e.g., P.x), but we no longer do.
246 // this->globals_->add_package(package_name, this->package_);
248 if (this->is_main_package())
250 // Declare "main" as a function which takes no parameters and
252 this->declare_function("main",
253 Type::make_function_type(NULL, NULL, NULL,
259 // Return whether this is the "main" package. This is not true if
260 // -fgo-prefix was used.
263 Gogo::is_main_package() const
265 return this->package_name() == "main" && !this->unique_prefix_specified_;
271 Gogo::import_package(const std::string& filename,
272 const std::string& local_name,
273 bool is_local_name_exported,
274 source_location location)
276 if (filename == "unsafe")
278 this->import_unsafe(local_name, is_local_name_exported, location);
282 Imports::const_iterator p = this->imports_.find(filename);
283 if (p != this->imports_.end())
285 Package* package = p->second;
286 package->set_location(location);
287 package->set_is_imported();
288 std::string ln = local_name;
289 bool is_ln_exported = is_local_name_exported;
292 ln = package->name();
293 is_ln_exported = Lex::is_exported_name(ln);
297 Bindings* bindings = package->bindings();
298 for (Bindings::const_declarations_iterator p =
299 bindings->begin_declarations();
300 p != bindings->end_declarations();
302 this->add_named_object(p->second);
305 package->set_uses_sink_alias();
308 ln = this->pack_hidden_name(ln, is_ln_exported);
309 this->package_->bindings()->add_package(ln, package);
314 Import::Stream* stream = Import::open_package(filename, location);
317 error_at(location, "import file %qs not found", filename.c_str());
321 Import imp(stream, location);
322 imp.register_builtin_types(this);
323 Package* package = imp.import(this, local_name, is_local_name_exported);
326 if (package->name() == this->package_name()
327 && package->unique_prefix() == this->unique_prefix())
329 ("imported package uses same package name and prefix "
330 "as package being compiled (see -fgo-prefix option)"));
332 this->imports_.insert(std::make_pair(filename, package));
333 package->set_is_imported();
339 // Add an import control function for an imported package to the list.
342 Gogo::add_import_init_fn(const std::string& package_name,
343 const std::string& init_name, int prio)
345 for (std::set<Import_init>::const_iterator p =
346 this->imported_init_fns_.begin();
347 p != this->imported_init_fns_.end();
350 if (p->init_name() == init_name
351 && (p->package_name() != package_name || p->priority() != prio))
353 error("duplicate package initialization name %qs",
354 Gogo::message_name(init_name).c_str());
355 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
356 Gogo::message_name(p->package_name()).c_str(),
358 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
359 Gogo::message_name(package_name).c_str(), prio);
364 this->imported_init_fns_.insert(Import_init(package_name, init_name,
368 // Return whether we are at the global binding level.
371 Gogo::in_global_scope() const
373 return this->functions_.empty();
376 // Return the current binding contour.
379 Gogo::current_bindings()
381 if (!this->functions_.empty())
382 return this->functions_.back().blocks.back()->bindings();
383 else if (this->package_ != NULL)
384 return this->package_->bindings();
386 return this->globals_;
390 Gogo::current_bindings() const
392 if (!this->functions_.empty())
393 return this->functions_.back().blocks.back()->bindings();
394 else if (this->package_ != NULL)
395 return this->package_->bindings();
397 return this->globals_;
400 // Return the current block.
403 Gogo::current_block()
405 if (this->functions_.empty())
408 return this->functions_.back().blocks.back();
411 // Look up a name in the current binding contour. If PFUNCTION is not
412 // NULL, set it to the function in which the name is defined, or NULL
413 // if the name is defined in global scope.
416 Gogo::lookup(const std::string& name, Named_object** pfunction) const
418 if (pfunction != NULL)
421 if (Gogo::is_sink_name(name))
422 return Named_object::make_sink();
424 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
425 p != this->functions_.rend();
428 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
431 if (pfunction != NULL)
432 *pfunction = p->function;
437 if (this->package_ != NULL)
439 Named_object* ret = this->package_->bindings()->lookup(name);
442 if (ret->package() != NULL)
443 ret->package()->set_used();
448 // We do not look in the global namespace. If we did, the global
449 // namespace would effectively hide names which were defined in
450 // package scope which we have not yet seen. Instead,
451 // define_global_names is called after parsing is over to connect
452 // undefined names at package scope with names defined at global
458 // Look up a name in the current block, without searching enclosing
462 Gogo::lookup_in_block(const std::string& name) const
464 go_assert(!this->functions_.empty());
465 go_assert(!this->functions_.back().blocks.empty());
466 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
469 // Look up a name in the global namespace.
472 Gogo::lookup_global(const char* name) const
474 return this->globals_->lookup(name);
477 // Add an imported package.
480 Gogo::add_imported_package(const std::string& real_name,
481 const std::string& alias_arg,
482 bool is_alias_exported,
483 const std::string& unique_prefix,
484 source_location location,
485 bool* padd_to_globals)
487 // FIXME: Now that we compile packages as a whole, should we permit
488 // importing the current package?
489 if (this->package_name() == real_name
490 && this->unique_prefix() == unique_prefix)
492 *padd_to_globals = false;
493 if (!alias_arg.empty() && alias_arg != ".")
495 std::string alias = this->pack_hidden_name(alias_arg,
497 this->package_->bindings()->add_package(alias, this->package_);
499 return this->package_;
501 else if (alias_arg == ".")
503 *padd_to_globals = true;
504 return this->register_package(real_name, unique_prefix, location);
506 else if (alias_arg == "_")
508 Package* ret = this->register_package(real_name, unique_prefix, location);
509 ret->set_uses_sink_alias();
514 *padd_to_globals = false;
515 std::string alias = alias_arg;
519 is_alias_exported = Lex::is_exported_name(alias);
521 alias = this->pack_hidden_name(alias, is_alias_exported);
522 Named_object* no = this->add_package(real_name, alias, unique_prefix,
524 if (!no->is_package())
526 return no->package_value();
533 Gogo::add_package(const std::string& real_name, const std::string& alias,
534 const std::string& unique_prefix, source_location location)
536 go_assert(this->in_global_scope());
538 // Register the package. Note that we might have already seen it in
539 // an earlier import.
540 Package* package = this->register_package(real_name, unique_prefix, location);
542 return this->package_->bindings()->add_package(alias, package);
545 // Register a package. This package may or may not be imported. This
546 // returns the Package structure for the package, creating if it
550 Gogo::register_package(const std::string& package_name,
551 const std::string& unique_prefix,
552 source_location location)
554 go_assert(!unique_prefix.empty() && !package_name.empty());
555 std::string name = unique_prefix + '.' + package_name;
556 Package* package = NULL;
557 std::pair<Packages::iterator, bool> ins =
558 this->packages_.insert(std::make_pair(name, package));
561 // We have seen this package name before.
562 package = ins.first->second;
563 go_assert(package != NULL);
564 go_assert(package->name() == package_name
565 && package->unique_prefix() == unique_prefix);
566 if (package->location() == UNKNOWN_LOCATION)
567 package->set_location(location);
571 // First time we have seen this package name.
572 package = new Package(package_name, unique_prefix, location);
573 go_assert(ins.first->second == NULL);
574 ins.first->second = package;
580 // Start compiling a function.
583 Gogo::start_function(const std::string& name, Function_type* type,
584 bool add_method_to_type, source_location location)
586 bool at_top_level = this->functions_.empty();
588 Block* block = new Block(NULL, location);
590 Function* enclosing = (at_top_level
592 : this->functions_.back().function->func_value());
594 Function* function = new Function(type, enclosing, block, location);
596 if (type->is_method())
598 const Typed_identifier* receiver = type->receiver();
599 Variable* this_param = new Variable(receiver->type(), NULL, false,
600 true, true, location);
601 std::string name = receiver->name();
604 // We need to give receivers a name since they wind up in
605 // DECL_ARGUMENTS. FIXME.
606 static unsigned int count;
608 snprintf(buf, sizeof buf, "r.%u", count);
612 block->bindings()->add_variable(name, NULL, this_param);
615 const Typed_identifier_list* parameters = type->parameters();
616 bool is_varargs = type->is_varargs();
617 if (parameters != NULL)
619 for (Typed_identifier_list::const_iterator p = parameters->begin();
620 p != parameters->end();
623 Variable* param = new Variable(p->type(), NULL, false, true, false,
625 if (is_varargs && p + 1 == parameters->end())
626 param->set_is_varargs_parameter();
628 std::string name = p->name();
629 if (name.empty() || Gogo::is_sink_name(name))
631 // We need to give parameters a name since they wind up
632 // in DECL_ARGUMENTS. FIXME.
633 static unsigned int count;
635 snprintf(buf, sizeof buf, "p.%u", count);
639 block->bindings()->add_variable(name, NULL, param);
643 function->create_result_variables(this);
645 const std::string* pname;
646 std::string nested_name;
647 bool is_init = false;
648 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
650 if ((type->parameters() != NULL && !type->parameters()->empty())
651 || (type->results() != NULL && !type->results()->empty()))
653 "func init must have no arguments and no return values");
654 // There can be multiple "init" functions, so give them each a
656 static int init_count;
658 snprintf(buf, sizeof buf, ".$init%d", init_count);
661 pname = &nested_name;
664 else if (!name.empty())
668 // Invent a name for a nested function.
669 static int nested_count;
671 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
674 pname = &nested_name;
678 if (Gogo::is_sink_name(*pname))
680 static int sink_count;
682 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
684 ret = Named_object::make_function(buf, NULL, function);
686 else if (!type->is_method())
688 ret = this->package_->bindings()->add_function(*pname, NULL, function);
689 if (!ret->is_function() || ret->func_value() != function)
691 // Redefinition error. Invent a name to avoid knockon
693 static int redefinition_count;
695 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
696 ++redefinition_count;
697 ret = this->package_->bindings()->add_function(buf, NULL, function);
702 if (!add_method_to_type)
703 ret = Named_object::make_function(name, NULL, function);
706 go_assert(at_top_level);
707 Type* rtype = type->receiver()->type();
709 // We want to look through the pointer created by the
710 // parser, without getting an error if the type is not yet
712 if (rtype->classification() == Type::TYPE_POINTER)
713 rtype = rtype->points_to();
715 if (rtype->is_error_type())
716 ret = Named_object::make_function(name, NULL, function);
717 else if (rtype->named_type() != NULL)
719 ret = rtype->named_type()->add_method(name, function);
720 if (!ret->is_function())
722 // Redefinition error.
723 ret = Named_object::make_function(name, NULL, function);
726 else if (rtype->forward_declaration_type() != NULL)
728 Named_object* type_no =
729 rtype->forward_declaration_type()->named_object();
730 if (type_no->is_unknown())
732 // If we are seeing methods it really must be a
733 // type. Declare it as such. An alternative would
734 // be to support lists of methods for unknown
735 // expressions. Either way the error messages if
736 // this is not a type are going to get confusing.
737 Named_object* declared =
738 this->declare_package_type(type_no->name(),
739 type_no->location());
741 == type_no->unknown_value()->real_named_object());
743 ret = rtype->forward_declaration_type()->add_method(name,
749 this->package_->bindings()->add_method(ret);
752 this->functions_.resize(this->functions_.size() + 1);
753 Open_function& of(this->functions_.back());
755 of.blocks.push_back(block);
759 this->init_functions_.push_back(ret);
760 this->need_init_fn_ = true;
766 // Finish compiling a function.
769 Gogo::finish_function(source_location location)
771 this->finish_block(location);
772 go_assert(this->functions_.back().blocks.empty());
773 this->functions_.pop_back();
776 // Return the current function.
779 Gogo::current_function() const
781 go_assert(!this->functions_.empty());
782 return this->functions_.back().function;
785 // Start a new block.
788 Gogo::start_block(source_location location)
790 go_assert(!this->functions_.empty());
791 Block* block = new Block(this->current_block(), location);
792 this->functions_.back().blocks.push_back(block);
798 Gogo::finish_block(source_location location)
800 go_assert(!this->functions_.empty());
801 go_assert(!this->functions_.back().blocks.empty());
802 Block* block = this->functions_.back().blocks.back();
803 this->functions_.back().blocks.pop_back();
804 block->set_end_location(location);
808 // Add an unknown name.
811 Gogo::add_unknown_name(const std::string& name, source_location location)
813 return this->package_->bindings()->add_unknown_name(name, location);
816 // Declare a function.
819 Gogo::declare_function(const std::string& name, Function_type* type,
820 source_location location)
822 if (!type->is_method())
823 return this->current_bindings()->add_function_declaration(name, NULL, type,
827 // We don't bother to add this to the list of global
829 Type* rtype = type->receiver()->type();
831 // We want to look through the pointer created by the
832 // parser, without getting an error if the type is not yet
834 if (rtype->classification() == Type::TYPE_POINTER)
835 rtype = rtype->points_to();
837 if (rtype->is_error_type())
839 else if (rtype->named_type() != NULL)
840 return rtype->named_type()->add_method_declaration(name, NULL, type,
842 else if (rtype->forward_declaration_type() != NULL)
844 Forward_declaration_type* ftype = rtype->forward_declaration_type();
845 return ftype->add_method_declaration(name, type, location);
852 // Add a label definition.
855 Gogo::add_label_definition(const std::string& label_name,
856 source_location location)
858 go_assert(!this->functions_.empty());
859 Function* func = this->functions_.back().function->func_value();
860 Label* label = func->add_label_definition(label_name, location);
861 this->add_statement(Statement::make_label_statement(label, location));
865 // Add a label reference.
868 Gogo::add_label_reference(const std::string& label_name)
870 go_assert(!this->functions_.empty());
871 Function* func = this->functions_.back().function->func_value();
872 return func->add_label_reference(label_name);
878 Gogo::add_statement(Statement* statement)
880 go_assert(!this->functions_.empty()
881 && !this->functions_.back().blocks.empty());
882 this->functions_.back().blocks.back()->add_statement(statement);
888 Gogo::add_block(Block* block, source_location location)
890 go_assert(!this->functions_.empty()
891 && !this->functions_.back().blocks.empty());
892 Statement* statement = Statement::make_block_statement(block, location);
893 this->functions_.back().blocks.back()->add_statement(statement);
899 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
902 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
908 Gogo::add_type(const std::string& name, Type* type, source_location location)
910 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
912 if (!this->in_global_scope() && no->is_type())
913 no->type_value()->set_in_function(this->functions_.back().function);
919 Gogo::add_named_type(Named_type* type)
921 go_assert(this->in_global_scope());
922 this->current_bindings()->add_named_type(type);
928 Gogo::declare_type(const std::string& name, source_location location)
930 Bindings* bindings = this->current_bindings();
931 Named_object* no = bindings->add_type_declaration(name, NULL, location);
932 if (!this->in_global_scope() && no->is_type_declaration())
934 Named_object* f = this->functions_.back().function;
935 no->type_declaration_value()->set_in_function(f);
940 // Declare a type at the package level.
943 Gogo::declare_package_type(const std::string& name, source_location location)
945 return this->package_->bindings()->add_type_declaration(name, NULL, location);
948 // Define a type which was already declared.
951 Gogo::define_type(Named_object* no, Named_type* type)
953 this->current_bindings()->define_type(no, type);
959 Gogo::add_variable(const std::string& name, Variable* variable)
961 Named_object* no = this->current_bindings()->add_variable(name, NULL,
964 // In a function the middle-end wants to see a DECL_EXPR node.
967 && !no->var_value()->is_parameter()
968 && !this->functions_.empty())
969 this->add_statement(Statement::make_variable_declaration(no));
974 // Add a sink--a reference to the blank identifier _.
979 return Named_object::make_sink();
982 // Add a named object.
985 Gogo::add_named_object(Named_object* no)
987 this->current_bindings()->add_named_object(no);
990 // Record that we've seen an interface type.
993 Gogo::record_interface_type(Interface_type* itype)
995 this->interface_types_.push_back(itype);
998 // Return a name for a thunk object.
1003 static int thunk_count;
1004 char thunk_name[50];
1005 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1010 // Return whether a function is a thunk.
1013 Gogo::is_thunk(const Named_object* no)
1015 return no->name().compare(0, 6, "$thunk") == 0;
1018 // Define the global names. We do this only after parsing all the
1019 // input files, because the program might define the global names
1023 Gogo::define_global_names()
1025 for (Bindings::const_declarations_iterator p =
1026 this->globals_->begin_declarations();
1027 p != this->globals_->end_declarations();
1030 Named_object* global_no = p->second;
1031 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1032 Named_object* no = this->package_->bindings()->lookup(name);
1036 if (no->is_type_declaration())
1038 if (global_no->is_type())
1040 if (no->type_declaration_value()->has_methods())
1041 error_at(no->location(),
1042 "may not define methods for global type");
1043 no->set_type_value(global_no->type_value());
1047 error_at(no->location(), "expected type");
1048 Type* errtype = Type::make_error_type();
1049 Named_object* err = Named_object::make_type("error", NULL,
1052 no->set_type_value(err->type_value());
1055 else if (no->is_unknown())
1056 no->unknown_value()->set_real_named_object(global_no);
1060 // Clear out names in file scope.
1063 Gogo::clear_file_scope()
1065 this->package_->bindings()->clear_file_scope();
1067 // Warn about packages which were imported but not used.
1068 for (Packages::iterator p = this->packages_.begin();
1069 p != this->packages_.end();
1072 Package* package = p->second;
1073 if (package != this->package_
1074 && package->is_imported()
1076 && !package->uses_sink_alias()
1078 error_at(package->location(), "imported and not used: %s",
1079 Gogo::message_name(package->name()).c_str());
1080 package->clear_is_imported();
1081 package->clear_uses_sink_alias();
1082 package->clear_used();
1086 // Traverse the tree.
1089 Gogo::traverse(Traverse* traverse)
1091 // Traverse the current package first for consistency. The other
1092 // packages will only contain imported types, constants, and
1094 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1096 for (Packages::const_iterator p = this->packages_.begin();
1097 p != this->packages_.end();
1100 if (p->second != this->package_)
1102 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1108 // Traversal class used to verify types.
1110 class Verify_types : public Traverse
1114 : Traverse(traverse_types)
1121 // Verify that a type is correct.
1124 Verify_types::type(Type* t)
1127 return TRAVERSE_SKIP_COMPONENTS;
1128 return TRAVERSE_CONTINUE;
1131 // Verify that all types are correct.
1134 Gogo::verify_types()
1136 Verify_types traverse;
1137 this->traverse(&traverse);
1140 // Traversal class used to lower parse tree.
1142 class Lower_parse_tree : public Traverse
1145 Lower_parse_tree(Gogo* gogo, Named_object* function)
1146 : Traverse(traverse_variables
1147 | traverse_constants
1148 | traverse_functions
1149 | traverse_statements
1150 | traverse_expressions),
1151 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1155 set_inserter(const Statement_inserter* inserter)
1156 { this->inserter_ = *inserter; }
1159 variable(Named_object*);
1162 constant(Named_object*, bool);
1165 function(Named_object*);
1168 statement(Block*, size_t* pindex, Statement*);
1171 expression(Expression**);
1176 // The function we are traversing.
1177 Named_object* function_;
1178 // Value to use for the predeclared constant iota.
1180 // Current statement inserter for use by expressions.
1181 Statement_inserter inserter_;
1187 Lower_parse_tree::variable(Named_object* no)
1189 if (!no->is_variable())
1190 return TRAVERSE_CONTINUE;
1192 if (no->is_variable() && no->var_value()->is_global())
1194 // Global variables can have loops in their initialization
1195 // expressions. This is handled in lower_init_expression.
1196 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1198 return TRAVERSE_CONTINUE;
1201 // This is a local variable. We are going to return
1202 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1203 // initialization expression when we reach the variable declaration
1204 // statement. However, that means that we need to traverse the type
1206 if (no->var_value()->has_type())
1208 Type* type = no->var_value()->type();
1211 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1212 return TRAVERSE_EXIT;
1215 go_assert(!no->var_value()->has_pre_init());
1217 return TRAVERSE_SKIP_COMPONENTS;
1220 // Lower constants. We handle constants specially so that we can set
1221 // the right value for the predeclared constant iota. This works in
1222 // conjunction with the way we lower Const_expression objects.
1225 Lower_parse_tree::constant(Named_object* no, bool)
1227 Named_constant* nc = no->const_value();
1229 // Don't get into trouble if the constant's initializer expression
1230 // refers to the constant itself.
1232 return TRAVERSE_CONTINUE;
1235 go_assert(this->iota_value_ == -1);
1236 this->iota_value_ = nc->iota_value();
1237 nc->traverse_expression(this);
1238 this->iota_value_ = -1;
1240 nc->clear_lowering();
1242 // We will traverse the expression a second time, but that will be
1245 return TRAVERSE_CONTINUE;
1248 // Lower function closure types. Record the function while lowering
1249 // it, so that we can pass it down when lowering an expression.
1252 Lower_parse_tree::function(Named_object* no)
1254 no->func_value()->set_closure_type();
1256 go_assert(this->function_ == NULL);
1257 this->function_ = no;
1258 int t = no->func_value()->traverse(this);
1259 this->function_ = NULL;
1261 if (t == TRAVERSE_EXIT)
1263 return TRAVERSE_SKIP_COMPONENTS;
1266 // Lower statement parse trees.
1269 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1271 // Because we explicitly traverse the statement's contents
1272 // ourselves, we want to skip block statements here. There is
1273 // nothing to lower in a block statement.
1274 if (sorig->is_block_statement())
1275 return TRAVERSE_CONTINUE;
1277 Statement_inserter hold_inserter(this->inserter_);
1278 this->inserter_ = Statement_inserter(block, pindex);
1280 // Lower the expressions first.
1281 int t = sorig->traverse_contents(this);
1282 if (t == TRAVERSE_EXIT)
1284 this->inserter_ = hold_inserter;
1288 // Keep lowering until nothing changes.
1289 Statement* s = sorig;
1292 Statement* snew = s->lower(this->gogo_, this->function_, block,
1297 t = s->traverse_contents(this);
1298 if (t == TRAVERSE_EXIT)
1300 this->inserter_ = hold_inserter;
1306 block->replace_statement(*pindex, s);
1308 this->inserter_ = hold_inserter;
1309 return TRAVERSE_SKIP_COMPONENTS;
1312 // Lower expression parse trees.
1315 Lower_parse_tree::expression(Expression** pexpr)
1317 // We have to lower all subexpressions first, so that we can get
1318 // their type if necessary. This is awkward, because we don't have
1319 // a postorder traversal pass.
1320 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1321 return TRAVERSE_EXIT;
1322 // Keep lowering until nothing changes.
1325 Expression* e = *pexpr;
1326 Expression* enew = e->lower(this->gogo_, this->function_,
1327 &this->inserter_, this->iota_value_);
1332 return TRAVERSE_SKIP_COMPONENTS;
1335 // Lower the parse tree. This is called after the parse is complete,
1336 // when all names should be resolved.
1339 Gogo::lower_parse_tree()
1341 Lower_parse_tree lower_parse_tree(this, NULL);
1342 this->traverse(&lower_parse_tree);
1348 Gogo::lower_block(Named_object* function, Block* block)
1350 Lower_parse_tree lower_parse_tree(this, function);
1351 block->traverse(&lower_parse_tree);
1354 // Lower an expression. INSERTER may be NULL, in which case the
1355 // expression had better not need to create any temporaries.
1358 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1361 Lower_parse_tree lower_parse_tree(this, function);
1362 if (inserter != NULL)
1363 lower_parse_tree.set_inserter(inserter);
1364 lower_parse_tree.expression(pexpr);
1367 // Lower a constant. This is called when lowering a reference to a
1368 // constant. We have to make sure that the constant has already been
1372 Gogo::lower_constant(Named_object* no)
1374 go_assert(no->is_const());
1375 Lower_parse_tree lower(this, NULL);
1376 lower.constant(no, false);
1379 // Look for interface types to finalize methods of inherited
1382 class Finalize_methods : public Traverse
1385 Finalize_methods(Gogo* gogo)
1386 : Traverse(traverse_types),
1397 // Finalize the methods of an interface type.
1400 Finalize_methods::type(Type* t)
1402 // Check the classification so that we don't finalize the methods
1403 // twice for a named interface type.
1404 switch (t->classification())
1406 case Type::TYPE_INTERFACE:
1407 t->interface_type()->finalize_methods();
1410 case Type::TYPE_NAMED:
1412 // We have to finalize the methods of the real type first.
1413 // But if the real type is a struct type, then we only want to
1414 // finalize the methods of the field types, not of the struct
1415 // type itself. We don't want to add methods to the struct,
1416 // since it has a name.
1417 Type* rt = t->named_type()->real_type();
1418 if (rt->classification() != Type::TYPE_STRUCT)
1420 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1421 return TRAVERSE_EXIT;
1425 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1426 return TRAVERSE_EXIT;
1429 t->named_type()->finalize_methods(this->gogo_);
1431 return TRAVERSE_SKIP_COMPONENTS;
1434 case Type::TYPE_STRUCT:
1435 t->struct_type()->finalize_methods(this->gogo_);
1442 return TRAVERSE_CONTINUE;
1445 // Finalize method lists and build stub methods for types.
1448 Gogo::finalize_methods()
1450 Finalize_methods finalize(this);
1451 this->traverse(&finalize);
1454 // Set types for unspecified variables and constants.
1457 Gogo::determine_types()
1459 Bindings* bindings = this->current_bindings();
1460 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1461 p != bindings->end_definitions();
1464 if ((*p)->is_function())
1465 (*p)->func_value()->determine_types();
1466 else if ((*p)->is_variable())
1467 (*p)->var_value()->determine_type();
1468 else if ((*p)->is_const())
1469 (*p)->const_value()->determine_type();
1471 // See if a variable requires us to build an initialization
1472 // function. We know that we will see all global variables
1474 if (!this->need_init_fn_ && (*p)->is_variable())
1476 Variable* variable = (*p)->var_value();
1478 // If this is a global variable which requires runtime
1479 // initialization, we need an initialization function.
1480 if (!variable->is_global())
1482 else if (variable->init() == NULL)
1484 else if (variable->type()->interface_type() != NULL)
1485 this->need_init_fn_ = true;
1486 else if (variable->init()->is_constant())
1488 else if (!variable->init()->is_composite_literal())
1489 this->need_init_fn_ = true;
1490 else if (variable->init()->is_nonconstant_composite_literal())
1491 this->need_init_fn_ = true;
1493 // If this is a global variable which holds a pointer value,
1494 // then we need an initialization function to register it as a
1496 if (variable->is_global() && variable->type()->has_pointer())
1497 this->need_init_fn_ = true;
1501 // Determine the types of constants in packages.
1502 for (Packages::const_iterator p = this->packages_.begin();
1503 p != this->packages_.end();
1505 p->second->determine_types();
1508 // Traversal class used for type checking.
1510 class Check_types_traverse : public Traverse
1513 Check_types_traverse(Gogo* gogo)
1514 : Traverse(traverse_variables
1515 | traverse_constants
1516 | traverse_functions
1517 | traverse_statements
1518 | traverse_expressions),
1523 variable(Named_object*);
1526 constant(Named_object*, bool);
1529 function(Named_object*);
1532 statement(Block*, size_t* pindex, Statement*);
1535 expression(Expression**);
1542 // Check that a variable initializer has the right type.
1545 Check_types_traverse::variable(Named_object* named_object)
1547 if (named_object->is_variable())
1549 Variable* var = named_object->var_value();
1551 // Give error if variable type is not defined.
1552 var->type()->base();
1554 Expression* init = var->init();
1557 && !Type::are_assignable(var->type(), init->type(), &reason))
1560 error_at(var->location(), "incompatible type in initialization");
1562 error_at(var->location(),
1563 "incompatible type in initialization (%s)",
1568 return TRAVERSE_CONTINUE;
1571 // Check that a constant initializer has the right type.
1574 Check_types_traverse::constant(Named_object* named_object, bool)
1576 Named_constant* constant = named_object->const_value();
1577 Type* ctype = constant->type();
1578 if (ctype->integer_type() == NULL
1579 && ctype->float_type() == NULL
1580 && ctype->complex_type() == NULL
1581 && !ctype->is_boolean_type()
1582 && !ctype->is_string_type())
1584 if (ctype->is_nil_type())
1585 error_at(constant->location(), "const initializer cannot be nil");
1586 else if (!ctype->is_error())
1587 error_at(constant->location(), "invalid constant type");
1588 constant->set_error();
1590 else if (!constant->expr()->is_constant())
1592 error_at(constant->expr()->location(), "expression is not constant");
1593 constant->set_error();
1595 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1598 error_at(constant->location(),
1599 "initialization expression has wrong type");
1600 constant->set_error();
1602 return TRAVERSE_CONTINUE;
1605 // There are no types to check in a function, but this is where we
1606 // issue warnings about labels which are defined but not referenced.
1609 Check_types_traverse::function(Named_object* no)
1611 no->func_value()->check_labels();
1612 return TRAVERSE_CONTINUE;
1615 // Check that types are valid in a statement.
1618 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1620 s->check_types(this->gogo_);
1621 return TRAVERSE_CONTINUE;
1624 // Check that types are valid in an expression.
1627 Check_types_traverse::expression(Expression** expr)
1629 (*expr)->check_types(this->gogo_);
1630 return TRAVERSE_CONTINUE;
1633 // Check that types are valid.
1638 Check_types_traverse traverse(this);
1639 this->traverse(&traverse);
1642 // Check the types in a single block.
1645 Gogo::check_types_in_block(Block* block)
1647 Check_types_traverse traverse(this);
1648 block->traverse(&traverse);
1651 // A traversal class used to find a single shortcut operator within an
1654 class Find_shortcut : public Traverse
1658 : Traverse(traverse_blocks
1659 | traverse_statements
1660 | traverse_expressions),
1664 // A pointer to the expression which was found, or NULL if none was
1668 { return this->found_; }
1673 { return TRAVERSE_SKIP_COMPONENTS; }
1676 statement(Block*, size_t*, Statement*)
1677 { return TRAVERSE_SKIP_COMPONENTS; }
1680 expression(Expression**);
1683 Expression** found_;
1686 // Find a shortcut expression.
1689 Find_shortcut::expression(Expression** pexpr)
1691 Expression* expr = *pexpr;
1692 Binary_expression* be = expr->binary_expression();
1694 return TRAVERSE_CONTINUE;
1695 Operator op = be->op();
1696 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1697 return TRAVERSE_CONTINUE;
1698 go_assert(this->found_ == NULL);
1699 this->found_ = pexpr;
1700 return TRAVERSE_EXIT;
1703 // A traversal class used to turn shortcut operators into explicit if
1706 class Shortcuts : public Traverse
1709 Shortcuts(Gogo* gogo)
1710 : Traverse(traverse_variables
1711 | traverse_statements),
1717 variable(Named_object*);
1720 statement(Block*, size_t*, Statement*);
1723 // Convert a shortcut operator.
1725 convert_shortcut(Block* enclosing, Expression** pshortcut);
1731 // Remove shortcut operators in a single statement.
1734 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1736 // FIXME: This approach doesn't work for switch statements, because
1737 // we add the new statements before the whole switch when we need to
1738 // instead add them just before the switch expression. The right
1739 // fix is probably to lower switch statements with nonconstant cases
1740 // to a series of conditionals.
1741 if (s->switch_statement() != NULL)
1742 return TRAVERSE_CONTINUE;
1746 Find_shortcut find_shortcut;
1748 // If S is a variable declaration, then ordinary traversal won't
1749 // do anything. We want to explicitly traverse the
1750 // initialization expression if there is one.
1751 Variable_declaration_statement* vds = s->variable_declaration_statement();
1752 Expression* init = NULL;
1754 s->traverse_contents(&find_shortcut);
1757 init = vds->var()->var_value()->init();
1759 return TRAVERSE_CONTINUE;
1760 init->traverse(&init, &find_shortcut);
1762 Expression** pshortcut = find_shortcut.found();
1763 if (pshortcut == NULL)
1764 return TRAVERSE_CONTINUE;
1766 Statement* snew = this->convert_shortcut(block, pshortcut);
1767 block->insert_statement_before(*pindex, snew);
1770 if (pshortcut == &init)
1771 vds->var()->var_value()->set_init(init);
1775 // Remove shortcut operators in the initializer of a global variable.
1778 Shortcuts::variable(Named_object* no)
1780 if (no->is_result_variable())
1781 return TRAVERSE_CONTINUE;
1782 Variable* var = no->var_value();
1783 Expression* init = var->init();
1784 if (!var->is_global() || init == NULL)
1785 return TRAVERSE_CONTINUE;
1789 Find_shortcut find_shortcut;
1790 init->traverse(&init, &find_shortcut);
1791 Expression** pshortcut = find_shortcut.found();
1792 if (pshortcut == NULL)
1793 return TRAVERSE_CONTINUE;
1795 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1796 var->add_preinit_statement(this->gogo_, snew);
1797 if (pshortcut == &init)
1798 var->set_init(init);
1802 // Given an expression which uses a shortcut operator, return a
1803 // statement which implements it, and update *PSHORTCUT accordingly.
1806 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1808 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1809 Expression* left = shortcut->left();
1810 Expression* right = shortcut->right();
1811 source_location loc = shortcut->location();
1813 Block* retblock = new Block(enclosing, loc);
1814 retblock->set_end_location(loc);
1816 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
1818 retblock->add_statement(ts);
1820 Block* block = new Block(retblock, loc);
1821 block->set_end_location(loc);
1822 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1823 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1824 block->add_statement(assign);
1826 Expression* cond = Expression::make_temporary_reference(ts, loc);
1827 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1828 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1830 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1832 retblock->add_statement(if_statement);
1834 *pshortcut = Expression::make_temporary_reference(ts, loc);
1838 // Now convert any shortcut operators in LEFT and RIGHT.
1839 Shortcuts shortcuts(this->gogo_);
1840 retblock->traverse(&shortcuts);
1842 return Statement::make_block_statement(retblock, loc);
1845 // Turn shortcut operators into explicit if statements. Doing this
1846 // considerably simplifies the order of evaluation rules.
1849 Gogo::remove_shortcuts()
1851 Shortcuts shortcuts(this);
1852 this->traverse(&shortcuts);
1855 // A traversal class which finds all the expressions which must be
1856 // evaluated in order within a statement or larger expression. This
1857 // is used to implement the rules about order of evaluation.
1859 class Find_eval_ordering : public Traverse
1862 typedef std::vector<Expression**> Expression_pointers;
1865 Find_eval_ordering()
1866 : Traverse(traverse_blocks
1867 | traverse_statements
1868 | traverse_expressions),
1874 { return this->exprs_.size(); }
1876 typedef Expression_pointers::const_iterator const_iterator;
1880 { return this->exprs_.begin(); }
1884 { return this->exprs_.end(); }
1889 { return TRAVERSE_SKIP_COMPONENTS; }
1892 statement(Block*, size_t*, Statement*)
1893 { return TRAVERSE_SKIP_COMPONENTS; }
1896 expression(Expression**);
1899 // A list of pointers to expressions with side-effects.
1900 Expression_pointers exprs_;
1903 // If an expression must be evaluated in order, put it on the list.
1906 Find_eval_ordering::expression(Expression** expression_pointer)
1908 // We have to look at subexpressions before this one.
1909 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1910 return TRAVERSE_EXIT;
1911 if ((*expression_pointer)->must_eval_in_order())
1912 this->exprs_.push_back(expression_pointer);
1913 return TRAVERSE_SKIP_COMPONENTS;
1916 // A traversal class for ordering evaluations.
1918 class Order_eval : public Traverse
1921 Order_eval(Gogo* gogo)
1922 : Traverse(traverse_variables
1923 | traverse_statements),
1928 variable(Named_object*);
1931 statement(Block*, size_t*, Statement*);
1938 // Implement the order of evaluation rules for a statement.
1941 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1943 // FIXME: This approach doesn't work for switch statements, because
1944 // we add the new statements before the whole switch when we need to
1945 // instead add them just before the switch expression. The right
1946 // fix is probably to lower switch statements with nonconstant cases
1947 // to a series of conditionals.
1948 if (s->switch_statement() != NULL)
1949 return TRAVERSE_CONTINUE;
1951 Find_eval_ordering find_eval_ordering;
1953 // If S is a variable declaration, then ordinary traversal won't do
1954 // anything. We want to explicitly traverse the initialization
1955 // expression if there is one.
1956 Variable_declaration_statement* vds = s->variable_declaration_statement();
1957 Expression* init = NULL;
1958 Expression* orig_init = NULL;
1960 s->traverse_contents(&find_eval_ordering);
1963 init = vds->var()->var_value()->init();
1965 return TRAVERSE_CONTINUE;
1968 // It might seem that this could be
1969 // init->traverse_subexpressions. Unfortunately that can fail
1972 // newvar, err := call(arg())
1973 // Here newvar will have an init of call result 0 of
1974 // call(arg()). If we only traverse subexpressions, we will
1975 // only find arg(), and we won't bother to move anything out.
1976 // Then we get to the assignment to err, we will traverse the
1977 // whole statement, and this time we will find both call() and
1978 // arg(), and so we will move them out. This will cause them to
1979 // be put into temporary variables before the assignment to err
1980 // but after the declaration of newvar. To avoid that problem,
1981 // we traverse the entire expression here.
1982 Expression::traverse(&init, &find_eval_ordering);
1985 if (find_eval_ordering.size() <= 1)
1987 // If there is only one expression with a side-effect, we can
1988 // leave it in place.
1989 return TRAVERSE_CONTINUE;
1992 bool is_thunk = s->thunk_statement() != NULL;
1993 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1994 p != find_eval_ordering.end();
1997 Expression** pexpr = *p;
1999 // The last expression in a thunk will be the call passed to go
2000 // or defer, which we must not evaluate early.
2001 if (is_thunk && p + 1 == find_eval_ordering.end())
2004 source_location loc = (*pexpr)->location();
2006 if ((*pexpr)->call_expression() == NULL
2007 || (*pexpr)->call_expression()->result_count() < 2)
2009 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2012 *pexpr = Expression::make_temporary_reference(ts, loc);
2016 // A call expression which returns multiple results needs to
2017 // be handled specially. We can't create a temporary
2018 // because there is no type to give it. Any actual uses of
2019 // the values will be done via Call_result_expressions.
2020 s = Statement::make_statement(*pexpr);
2023 block->insert_statement_before(*pindex, s);
2027 if (init != orig_init)
2028 vds->var()->var_value()->set_init(init);
2030 return TRAVERSE_CONTINUE;
2033 // Implement the order of evaluation rules for the initializer of a
2037 Order_eval::variable(Named_object* no)
2039 if (no->is_result_variable())
2040 return TRAVERSE_CONTINUE;
2041 Variable* var = no->var_value();
2042 Expression* init = var->init();
2043 if (!var->is_global() || init == NULL)
2044 return TRAVERSE_CONTINUE;
2046 Find_eval_ordering find_eval_ordering;
2047 Expression::traverse(&init, &find_eval_ordering);
2049 if (find_eval_ordering.size() <= 1)
2051 // If there is only one expression with a side-effect, we can
2052 // leave it in place.
2053 return TRAVERSE_SKIP_COMPONENTS;
2056 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2057 p != find_eval_ordering.end();
2060 Expression** pexpr = *p;
2061 source_location loc = (*pexpr)->location();
2063 if ((*pexpr)->call_expression() == NULL
2064 || (*pexpr)->call_expression()->result_count() < 2)
2066 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2069 *pexpr = Expression::make_temporary_reference(ts, loc);
2073 // A call expression which returns multiple results needs to
2074 // be handled specially.
2075 s = Statement::make_statement(*pexpr);
2077 var->add_preinit_statement(this->gogo_, s);
2080 return TRAVERSE_SKIP_COMPONENTS;
2083 // Use temporary variables to implement the order of evaluation rules.
2086 Gogo::order_evaluations()
2088 Order_eval order_eval(this);
2089 this->traverse(&order_eval);
2092 // Traversal to convert calls to the predeclared recover function to
2093 // pass in an argument indicating whether it can recover from a panic
2096 class Convert_recover : public Traverse
2099 Convert_recover(Named_object* arg)
2100 : Traverse(traverse_expressions),
2106 expression(Expression**);
2109 // The argument to pass to the function.
2113 // Convert calls to recover.
2116 Convert_recover::expression(Expression** pp)
2118 Call_expression* ce = (*pp)->call_expression();
2119 if (ce != NULL && ce->is_recover_call())
2120 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2122 return TRAVERSE_CONTINUE;
2125 // Traversal for build_recover_thunks.
2127 class Build_recover_thunks : public Traverse
2130 Build_recover_thunks(Gogo* gogo)
2131 : Traverse(traverse_functions),
2136 function(Named_object*);
2140 can_recover_arg(source_location);
2146 // If this function calls recover, turn it into a thunk.
2149 Build_recover_thunks::function(Named_object* orig_no)
2151 Function* orig_func = orig_no->func_value();
2152 if (!orig_func->calls_recover()
2153 || orig_func->is_recover_thunk()
2154 || orig_func->has_recover_thunk())
2155 return TRAVERSE_CONTINUE;
2157 Gogo* gogo = this->gogo_;
2158 source_location location = orig_func->location();
2163 Function_type* orig_fntype = orig_func->type();
2164 Typed_identifier_list* new_params = new Typed_identifier_list();
2165 std::string receiver_name;
2166 if (orig_fntype->is_method())
2168 const Typed_identifier* receiver = orig_fntype->receiver();
2169 snprintf(buf, sizeof buf, "rt.%u", count);
2171 receiver_name = buf;
2172 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2173 receiver->location()));
2175 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2176 if (orig_params != NULL && !orig_params->empty())
2178 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2179 p != orig_params->end();
2182 snprintf(buf, sizeof buf, "pt.%u", count);
2184 new_params->push_back(Typed_identifier(buf, p->type(),
2188 snprintf(buf, sizeof buf, "pr.%u", count);
2190 std::string can_recover_name = buf;
2191 new_params->push_back(Typed_identifier(can_recover_name,
2192 Type::lookup_bool_type(),
2193 orig_fntype->location()));
2195 const Typed_identifier_list* orig_results = orig_fntype->results();
2196 Typed_identifier_list* new_results;
2197 if (orig_results == NULL || orig_results->empty())
2201 new_results = new Typed_identifier_list();
2202 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2203 p != orig_results->end();
2205 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2208 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2210 orig_fntype->location());
2211 if (orig_fntype->is_varargs())
2212 new_fntype->set_is_varargs();
2214 std::string name = orig_no->name() + "$recover";
2215 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2217 Function *new_func = new_no->func_value();
2218 if (orig_func->enclosing() != NULL)
2219 new_func->set_enclosing(orig_func->enclosing());
2221 // We build the code for the original function attached to the new
2222 // function, and then swap the original and new function bodies.
2223 // This means that existing references to the original function will
2224 // then refer to the new function. That makes this code a little
2225 // confusing, in that the reference to NEW_NO really refers to the
2226 // other function, not the one we are building.
2228 Expression* closure = NULL;
2229 if (orig_func->needs_closure())
2231 Named_object* orig_closure_no = orig_func->closure_var();
2232 Variable* orig_closure_var = orig_closure_no->var_value();
2233 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2234 true, false, location);
2235 snprintf(buf, sizeof buf, "closure.%u", count);
2237 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2239 new_func->set_closure_var(new_closure_no);
2240 closure = Expression::make_var_reference(new_closure_no, location);
2243 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2245 Expression_list* args = new Expression_list();
2246 if (new_params != NULL)
2248 // Note that we skip the last parameter, which is the boolean
2249 // indicating whether recover can succed.
2250 for (Typed_identifier_list::const_iterator p = new_params->begin();
2251 p + 1 != new_params->end();
2254 Named_object* p_no = gogo->lookup(p->name(), NULL);
2255 go_assert(p_no != NULL
2256 && p_no->is_variable()
2257 && p_no->var_value()->is_parameter());
2258 args->push_back(Expression::make_var_reference(p_no, location));
2261 args->push_back(this->can_recover_arg(location));
2263 gogo->start_block(location);
2265 Call_expression* call = Expression::make_call(fn, args, false, location);
2268 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2269 s = Statement::make_statement(call);
2272 Expression_list* vals = new Expression_list();
2273 size_t rc = orig_fntype->results()->size();
2275 vals->push_back(call);
2278 for (size_t i = 0; i < rc; ++i)
2279 vals->push_back(Expression::make_call_result(call, i));
2281 s = Statement::make_return_statement(vals, location);
2283 s->determine_types();
2284 gogo->add_statement(s);
2286 Block* b = gogo->finish_block(location);
2288 gogo->add_block(b, location);
2290 // Lower the call in case it returns multiple results.
2291 gogo->lower_block(new_no, b);
2293 gogo->finish_function(location);
2295 // Swap the function bodies and types.
2296 new_func->swap_for_recover(orig_func);
2297 orig_func->set_is_recover_thunk();
2298 new_func->set_calls_recover();
2299 new_func->set_has_recover_thunk();
2301 Bindings* orig_bindings = orig_func->block()->bindings();
2302 Bindings* new_bindings = new_func->block()->bindings();
2303 if (orig_fntype->is_method())
2305 // We changed the receiver to be a regular parameter. We have
2306 // to update the binding accordingly in both functions.
2307 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2308 go_assert(orig_rec_no != NULL
2309 && orig_rec_no->is_variable()
2310 && !orig_rec_no->var_value()->is_receiver());
2311 orig_rec_no->var_value()->set_is_receiver();
2313 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2314 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2315 if (new_rec_no == NULL)
2316 go_assert(saw_errors());
2319 go_assert(new_rec_no->is_variable()
2320 && new_rec_no->var_value()->is_receiver());
2321 new_rec_no->var_value()->set_is_not_receiver();
2325 // Because we flipped blocks but not types, the can_recover
2326 // parameter appears in the (now) old bindings as a parameter.
2327 // Change it to a local variable, whereupon it will be discarded.
2328 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2329 go_assert(can_recover_no != NULL
2330 && can_recover_no->is_variable()
2331 && can_recover_no->var_value()->is_parameter());
2332 orig_bindings->remove_binding(can_recover_no);
2334 // Add the can_recover argument to the (now) new bindings, and
2335 // attach it to any recover statements.
2336 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2337 false, true, false, location);
2338 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2340 Convert_recover convert_recover(can_recover_no);
2341 new_func->traverse(&convert_recover);
2343 // Update the function pointers in any named results.
2344 new_func->update_result_variables();
2345 orig_func->update_result_variables();
2347 return TRAVERSE_CONTINUE;
2350 // Return the expression to pass for the .can_recover parameter to the
2351 // new function. This indicates whether a call to recover may return
2352 // non-nil. The expression is
2353 // __go_can_recover(__builtin_return_address()).
2356 Build_recover_thunks::can_recover_arg(source_location location)
2358 static Named_object* builtin_return_address;
2359 if (builtin_return_address == NULL)
2361 const source_location bloc = BUILTINS_LOCATION;
2363 Typed_identifier_list* param_types = new Typed_identifier_list();
2364 Type* uint_type = Type::lookup_integer_type("uint");
2365 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2367 Typed_identifier_list* return_types = new Typed_identifier_list();
2368 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2369 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2371 Function_type* fntype = Type::make_function_type(NULL, param_types,
2372 return_types, bloc);
2373 builtin_return_address =
2374 Named_object::make_function_declaration("__builtin_return_address",
2375 NULL, fntype, bloc);
2376 const char* n = "__builtin_return_address";
2377 builtin_return_address->func_declaration_value()->set_asm_name(n);
2380 static Named_object* can_recover;
2381 if (can_recover == NULL)
2383 const source_location bloc = BUILTINS_LOCATION;
2384 Typed_identifier_list* param_types = new Typed_identifier_list();
2385 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2386 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2387 Type* boolean_type = Type::lookup_bool_type();
2388 Typed_identifier_list* results = new Typed_identifier_list();
2389 results->push_back(Typed_identifier("", boolean_type, bloc));
2390 Function_type* fntype = Type::make_function_type(NULL, param_types,
2392 can_recover = Named_object::make_function_declaration("__go_can_recover",
2395 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2398 Expression* fn = Expression::make_func_reference(builtin_return_address,
2402 mpz_init_set_ui(zval, 0UL);
2403 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2405 Expression_list *args = new Expression_list();
2406 args->push_back(zexpr);
2408 Expression* call = Expression::make_call(fn, args, false, location);
2410 args = new Expression_list();
2411 args->push_back(call);
2413 fn = Expression::make_func_reference(can_recover, NULL, location);
2414 return Expression::make_call(fn, args, false, location);
2417 // Build thunks for functions which call recover. We build a new
2418 // function with an extra parameter, which is whether a call to
2419 // recover can succeed. We then move the body of this function to
2420 // that one. We then turn this function into a thunk which calls the
2421 // new one, passing the value of
2422 // __go_can_recover(__builtin_return_address()). The function will be
2423 // marked as not splitting the stack. This will cooperate with the
2424 // implementation of defer to make recover do the right thing.
2427 Gogo::build_recover_thunks()
2429 Build_recover_thunks build_recover_thunks(this);
2430 this->traverse(&build_recover_thunks);
2433 // Look for named types to see whether we need to create an interface
2436 class Build_method_tables : public Traverse
2439 Build_method_tables(Gogo* gogo,
2440 const std::vector<Interface_type*>& interfaces)
2441 : Traverse(traverse_types),
2442 gogo_(gogo), interfaces_(interfaces)
2451 // A list of locally defined interfaces which have hidden methods.
2452 const std::vector<Interface_type*>& interfaces_;
2455 // Build all required interface method tables for types. We need to
2456 // ensure that we have an interface method table for every interface
2457 // which has a hidden method, for every named type which implements
2458 // that interface. Normally we can just build interface method tables
2459 // as we need them. However, in some cases we can require an
2460 // interface method table for an interface defined in a different
2461 // package for a type defined in that package. If that interface and
2462 // type both use a hidden method, that is OK. However, we will not be
2463 // able to build that interface method table when we need it, because
2464 // the type's hidden method will be static. So we have to build it
2465 // here, and just refer it from other packages as needed.
2468 Gogo::build_interface_method_tables()
2470 std::vector<Interface_type*> hidden_interfaces;
2471 hidden_interfaces.reserve(this->interface_types_.size());
2472 for (std::vector<Interface_type*>::const_iterator pi =
2473 this->interface_types_.begin();
2474 pi != this->interface_types_.end();
2477 const Typed_identifier_list* methods = (*pi)->methods();
2478 if (methods == NULL)
2480 for (Typed_identifier_list::const_iterator pm = methods->begin();
2481 pm != methods->end();
2484 if (Gogo::is_hidden_name(pm->name()))
2486 hidden_interfaces.push_back(*pi);
2492 if (!hidden_interfaces.empty())
2494 // Now traverse the tree looking for all named types.
2495 Build_method_tables bmt(this, hidden_interfaces);
2496 this->traverse(&bmt);
2499 // We no longer need the list of interfaces.
2501 this->interface_types_.clear();
2504 // This is called for each type. For a named type, for each of the
2505 // interfaces with hidden methods that it implements, create the
2509 Build_method_tables::type(Type* type)
2511 Named_type* nt = type->named_type();
2514 for (std::vector<Interface_type*>::const_iterator p =
2515 this->interfaces_.begin();
2516 p != this->interfaces_.end();
2519 // We ask whether a pointer to the named type implements the
2520 // interface, because a pointer can implement more methods
2522 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2524 nt->interface_method_table(this->gogo_, *p, false);
2525 nt->interface_method_table(this->gogo_, *p, true);
2529 return TRAVERSE_CONTINUE;
2532 // Traversal class used to check for return statements.
2534 class Check_return_statements_traverse : public Traverse
2537 Check_return_statements_traverse()
2538 : Traverse(traverse_functions)
2542 function(Named_object*);
2545 // Check that a function has a return statement if it needs one.
2548 Check_return_statements_traverse::function(Named_object* no)
2550 Function* func = no->func_value();
2551 const Function_type* fntype = func->type();
2552 const Typed_identifier_list* results = fntype->results();
2554 // We only need a return statement if there is a return value.
2555 if (results == NULL || results->empty())
2556 return TRAVERSE_CONTINUE;
2558 if (func->block()->may_fall_through())
2559 error_at(func->location(), "control reaches end of non-void function");
2561 return TRAVERSE_CONTINUE;
2564 // Check return statements.
2567 Gogo::check_return_statements()
2569 Check_return_statements_traverse traverse;
2570 this->traverse(&traverse);
2573 // Get the unique prefix to use before all exported symbols. This
2574 // must be unique across the entire link.
2577 Gogo::unique_prefix() const
2579 go_assert(!this->unique_prefix_.empty());
2580 return this->unique_prefix_;
2583 // Set the unique prefix to use before all exported symbols. This
2584 // comes from the command line option -fgo-prefix=XXX.
2587 Gogo::set_unique_prefix(const std::string& arg)
2589 go_assert(this->unique_prefix_.empty());
2590 this->unique_prefix_ = arg;
2591 this->unique_prefix_specified_ = true;
2594 // Work out the package priority. It is one more than the maximum
2595 // priority of an imported package.
2598 Gogo::package_priority() const
2601 for (Packages::const_iterator p = this->packages_.begin();
2602 p != this->packages_.end();
2604 if (p->second->priority() > priority)
2605 priority = p->second->priority();
2606 return priority + 1;
2609 // Export identifiers as requested.
2614 // For now we always stream to a section. Later we may want to
2615 // support streaming to a separate file.
2616 Stream_to_section stream;
2618 Export exp(&stream);
2619 exp.register_builtin_types(this);
2620 exp.export_globals(this->package_name(),
2621 this->unique_prefix(),
2622 this->package_priority(),
2623 (this->need_init_fn_ && !this->is_main_package()
2624 ? this->get_init_fn_name()
2626 this->imported_init_fns_,
2627 this->package_->bindings());
2630 // Find the blocks in order to convert named types defined in blocks.
2632 class Convert_named_types : public Traverse
2635 Convert_named_types(Gogo* gogo)
2636 : Traverse(traverse_blocks),
2642 block(Block* block);
2649 Convert_named_types::block(Block* block)
2651 this->gogo_->convert_named_types_in_bindings(block->bindings());
2652 return TRAVERSE_CONTINUE;
2655 // Convert all named types to the backend representation. Since named
2656 // types can refer to other types, this needs to be done in the right
2657 // sequence, which is handled by Named_type::convert. Here we arrange
2658 // to call that for each named type.
2661 Gogo::convert_named_types()
2663 this->convert_named_types_in_bindings(this->globals_);
2664 for (Packages::iterator p = this->packages_.begin();
2665 p != this->packages_.end();
2668 Package* package = p->second;
2669 this->convert_named_types_in_bindings(package->bindings());
2672 Convert_named_types cnt(this);
2673 this->traverse(&cnt);
2675 // Make all the builtin named types used for type descriptors, and
2676 // then convert them. They will only be written out if they are
2678 Type::make_type_descriptor_type();
2679 Type::make_type_descriptor_ptr_type();
2680 Function_type::make_function_type_descriptor_type();
2681 Pointer_type::make_pointer_type_descriptor_type();
2682 Struct_type::make_struct_type_descriptor_type();
2683 Array_type::make_array_type_descriptor_type();
2684 Array_type::make_slice_type_descriptor_type();
2685 Map_type::make_map_type_descriptor_type();
2686 Map_type::make_map_descriptor_type();
2687 Channel_type::make_chan_type_descriptor_type();
2688 Interface_type::make_interface_type_descriptor_type();
2689 Type::convert_builtin_named_types(this);
2691 Runtime::convert_types(this);
2693 Function_type::convert_types(this);
2695 this->named_types_are_converted_ = true;
2698 // Convert all names types in a set of bindings.
2701 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2703 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2704 p != bindings->end_definitions();
2707 if ((*p)->is_type())
2708 (*p)->type_value()->convert(this);
2714 Function::Function(Function_type* type, Function* enclosing, Block* block,
2715 source_location location)
2716 : type_(type), enclosing_(enclosing), results_(NULL),
2717 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2718 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2719 is_recover_thunk_(false), has_recover_thunk_(false)
2723 // Create the named result variables.
2726 Function::create_result_variables(Gogo* gogo)
2728 const Typed_identifier_list* results = this->type_->results();
2729 if (results == NULL || results->empty())
2732 if (!results->front().name().empty())
2733 this->results_are_named_ = true;
2735 this->results_ = new Results();
2736 this->results_->reserve(results->size());
2738 Block* block = this->block_;
2740 for (Typed_identifier_list::const_iterator p = results->begin();
2741 p != results->end();
2744 std::string name = p->name();
2745 if (name.empty() || Gogo::is_sink_name(name))
2747 static int result_counter;
2749 snprintf(buf, sizeof buf, "$ret%d", result_counter);
2751 name = gogo->pack_hidden_name(buf, false);
2753 Result_variable* result = new Result_variable(p->type(), this, index,
2755 Named_object* no = block->bindings()->add_result_variable(name, result);
2756 if (no->is_result_variable())
2757 this->results_->push_back(no);
2760 static int dummy_result_count;
2762 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2763 ++dummy_result_count;
2764 name = gogo->pack_hidden_name(buf, false);
2765 no = block->bindings()->add_result_variable(name, result);
2766 go_assert(no->is_result_variable());
2767 this->results_->push_back(no);
2772 // Update the named result variables when cloning a function which
2776 Function::update_result_variables()
2778 if (this->results_ == NULL)
2781 for (Results::iterator p = this->results_->begin();
2782 p != this->results_->end();
2784 (*p)->result_var_value()->set_function(this);
2787 // Return the closure variable, creating it if necessary.
2790 Function::closure_var()
2792 if (this->closure_var_ == NULL)
2794 // We don't know the type of the variable yet. We add fields as
2796 source_location loc = this->type_->location();
2797 Struct_field_list* sfl = new Struct_field_list;
2798 Type* struct_type = Type::make_struct_type(sfl, loc);
2799 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2800 NULL, false, true, false, loc);
2801 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2802 // Note that the new variable is not in any binding contour.
2804 return this->closure_var_;
2807 // Set the type of the closure variable.
2810 Function::set_closure_type()
2812 if (this->closure_var_ == NULL)
2814 Named_object* closure = this->closure_var_;
2815 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2816 unsigned int index = 0;
2817 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2818 p != this->closure_fields_.end();
2821 Named_object* no = p->first;
2823 snprintf(buf, sizeof buf, "%u", index);
2824 std::string n = no->name() + buf;
2826 if (no->is_variable())
2827 var_type = no->var_value()->type();
2829 var_type = no->result_var_value()->type();
2830 Type* field_type = Type::make_pointer_type(var_type);
2831 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2835 // Return whether this function is a method.
2838 Function::is_method() const
2840 return this->type_->is_method();
2843 // Add a label definition.
2846 Function::add_label_definition(const std::string& label_name,
2847 source_location location)
2849 Label* lnull = NULL;
2850 std::pair<Labels::iterator, bool> ins =
2851 this->labels_.insert(std::make_pair(label_name, lnull));
2854 // This is a new label.
2855 Label* label = new Label(label_name);
2856 label->define(location);
2857 ins.first->second = label;
2862 // The label was already in the hash table.
2863 Label* label = ins.first->second;
2864 if (!label->is_defined())
2866 label->define(location);
2871 error_at(location, "label %qs already defined",
2872 Gogo::message_name(label_name).c_str());
2873 inform(label->location(), "previous definition of %qs was here",
2874 Gogo::message_name(label_name).c_str());
2875 return new Label(label_name);
2880 // Add a reference to a label.
2883 Function::add_label_reference(const std::string& label_name)
2885 Label* lnull = NULL;
2886 std::pair<Labels::iterator, bool> ins =
2887 this->labels_.insert(std::make_pair(label_name, lnull));
2890 // The label was already in the hash table.
2891 Label* label = ins.first->second;
2892 label->set_is_used();
2897 go_assert(ins.first->second == NULL);
2898 Label* label = new Label(label_name);
2899 ins.first->second = label;
2900 label->set_is_used();
2905 // Warn about labels that are defined but not used.
2908 Function::check_labels() const
2910 for (Labels::const_iterator p = this->labels_.begin();
2911 p != this->labels_.end();
2914 Label* label = p->second;
2915 if (!label->is_used())
2916 error_at(label->location(), "label %qs defined and not used",
2917 Gogo::message_name(label->name()).c_str());
2921 // Swap one function with another. This is used when building the
2922 // thunk we use to call a function which calls recover. It may not
2923 // work for any other case.
2926 Function::swap_for_recover(Function *x)
2928 go_assert(this->enclosing_ == x->enclosing_);
2929 std::swap(this->results_, x->results_);
2930 std::swap(this->closure_var_, x->closure_var_);
2931 std::swap(this->block_, x->block_);
2932 go_assert(this->location_ == x->location_);
2933 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2934 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2937 // Traverse the tree.
2940 Function::traverse(Traverse* traverse)
2942 unsigned int traverse_mask = traverse->traverse_mask();
2945 & (Traverse::traverse_types | Traverse::traverse_expressions))
2948 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2949 return TRAVERSE_EXIT;
2952 // FIXME: We should check traverse_functions here if nested
2953 // functions are stored in block bindings.
2954 if (this->block_ != NULL
2956 & (Traverse::traverse_variables
2957 | Traverse::traverse_constants
2958 | Traverse::traverse_blocks
2959 | Traverse::traverse_statements
2960 | Traverse::traverse_expressions
2961 | Traverse::traverse_types)) != 0)
2963 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2964 return TRAVERSE_EXIT;
2967 return TRAVERSE_CONTINUE;
2970 // Work out types for unspecified variables and constants.
2973 Function::determine_types()
2975 if (this->block_ != NULL)
2976 this->block_->determine_types();
2979 // Get a pointer to the variable representing the defer stack for this
2980 // function, making it if necessary. The value of the variable is set
2981 // by the runtime routines to true if the function is returning,
2982 // rather than panicing through. A pointer to this variable is used
2983 // as a marker for the functions on the defer stack associated with
2984 // this function. A function-specific variable permits inlining a
2985 // function which uses defer.
2988 Function::defer_stack(source_location location)
2990 if (this->defer_stack_ == NULL)
2992 Type* t = Type::lookup_bool_type();
2993 Expression* n = Expression::make_boolean(false, location);
2994 this->defer_stack_ = Statement::make_temporary(t, n, location);
2995 this->defer_stack_->set_is_address_taken();
2997 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
2999 return Expression::make_unary(OPERATOR_AND, ref, location);
3002 // Export the function.
3005 Function::export_func(Export* exp, const std::string& name) const
3007 Function::export_func_with_type(exp, name, this->type_);
3010 // Export a function with a type.
3013 Function::export_func_with_type(Export* exp, const std::string& name,
3014 const Function_type* fntype)
3016 exp->write_c_string("func ");
3018 if (fntype->is_method())
3020 exp->write_c_string("(");
3021 exp->write_type(fntype->receiver()->type());
3022 exp->write_c_string(") ");
3025 exp->write_string(name);
3027 exp->write_c_string(" (");
3028 const Typed_identifier_list* parameters = fntype->parameters();
3029 if (parameters != NULL)
3031 bool is_varargs = fntype->is_varargs();
3033 for (Typed_identifier_list::const_iterator p = parameters->begin();
3034 p != parameters->end();
3040 exp->write_c_string(", ");
3041 if (!is_varargs || p + 1 != parameters->end())
3042 exp->write_type(p->type());
3045 exp->write_c_string("...");
3046 exp->write_type(p->type()->array_type()->element_type());
3050 exp->write_c_string(")");
3052 const Typed_identifier_list* results = fntype->results();
3053 if (results != NULL)
3055 if (results->size() == 1)
3057 exp->write_c_string(" ");
3058 exp->write_type(results->begin()->type());
3062 exp->write_c_string(" (");
3064 for (Typed_identifier_list::const_iterator p = results->begin();
3065 p != results->end();
3071 exp->write_c_string(", ");
3072 exp->write_type(p->type());
3074 exp->write_c_string(")");
3077 exp->write_c_string(";\n");
3080 // Import a function.
3083 Function::import_func(Import* imp, std::string* pname,
3084 Typed_identifier** preceiver,
3085 Typed_identifier_list** pparameters,
3086 Typed_identifier_list** presults,
3089 imp->require_c_string("func ");
3092 if (imp->peek_char() == '(')
3094 imp->require_c_string("(");
3095 Type* rtype = imp->read_type();
3096 *preceiver = new Typed_identifier(Import::import_marker, rtype,
3098 imp->require_c_string(") ");
3101 *pname = imp->read_identifier();
3103 Typed_identifier_list* parameters;
3104 *is_varargs = false;
3105 imp->require_c_string(" (");
3106 if (imp->peek_char() == ')')
3110 parameters = new Typed_identifier_list();
3113 if (imp->match_c_string("..."))
3119 Type* ptype = imp->read_type();
3121 ptype = Type::make_array_type(ptype, NULL);
3122 parameters->push_back(Typed_identifier(Import::import_marker,
3123 ptype, imp->location()));
3124 if (imp->peek_char() != ',')
3126 go_assert(!*is_varargs);
3127 imp->require_c_string(", ");
3130 imp->require_c_string(")");
3131 *pparameters = parameters;
3133 Typed_identifier_list* results;
3134 if (imp->peek_char() != ' ')
3138 results = new Typed_identifier_list();
3139 imp->require_c_string(" ");
3140 if (imp->peek_char() != '(')
3142 Type* rtype = imp->read_type();
3143 results->push_back(Typed_identifier(Import::import_marker, rtype,
3148 imp->require_c_string("(");
3151 Type* rtype = imp->read_type();
3152 results->push_back(Typed_identifier(Import::import_marker,
3153 rtype, imp->location()));
3154 if (imp->peek_char() != ',')
3156 imp->require_c_string(", ");
3158 imp->require_c_string(")");
3161 imp->require_c_string(";\n");
3162 *presults = results;
3167 Block::Block(Block* enclosing, source_location location)
3168 : enclosing_(enclosing), statements_(),
3169 bindings_(new Bindings(enclosing == NULL
3171 : enclosing->bindings())),
3172 start_location_(location),
3173 end_location_(UNKNOWN_LOCATION)
3177 // Add a statement to a block.
3180 Block::add_statement(Statement* statement)
3182 this->statements_.push_back(statement);
3185 // Add a statement to the front of a block. This is slow but is only
3186 // used for reference counts of parameters.
3189 Block::add_statement_at_front(Statement* statement)
3191 this->statements_.insert(this->statements_.begin(), statement);
3194 // Replace a statement in a block.
3197 Block::replace_statement(size_t index, Statement* s)
3199 go_assert(index < this->statements_.size());
3200 this->statements_[index] = s;
3203 // Add a statement before another statement.
3206 Block::insert_statement_before(size_t index, Statement* s)
3208 go_assert(index < this->statements_.size());
3209 this->statements_.insert(this->statements_.begin() + index, s);
3212 // Add a statement after another statement.
3215 Block::insert_statement_after(size_t index, Statement* s)
3217 go_assert(index < this->statements_.size());
3218 this->statements_.insert(this->statements_.begin() + index + 1, s);
3221 // Traverse the tree.
3224 Block::traverse(Traverse* traverse)
3226 unsigned int traverse_mask = traverse->traverse_mask();
3228 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3230 int t = traverse->block(this);
3231 if (t == TRAVERSE_EXIT)
3232 return TRAVERSE_EXIT;
3233 else if (t == TRAVERSE_SKIP_COMPONENTS)
3234 return TRAVERSE_CONTINUE;
3238 & (Traverse::traverse_variables
3239 | Traverse::traverse_constants
3240 | Traverse::traverse_expressions
3241 | Traverse::traverse_types)) != 0)
3243 const unsigned int e_or_t = (Traverse::traverse_expressions
3244 | Traverse::traverse_types);
3245 const unsigned int e_or_t_or_s = (e_or_t
3246 | Traverse::traverse_statements);
3247 for (Bindings::const_definitions_iterator pb =
3248 this->bindings_->begin_definitions();
3249 pb != this->bindings_->end_definitions();
3252 int t = TRAVERSE_CONTINUE;
3253 switch ((*pb)->classification())
3255 case Named_object::NAMED_OBJECT_CONST:
3256 if ((traverse_mask & Traverse::traverse_constants) != 0)
3257 t = traverse->constant(*pb, false);
3258 if (t == TRAVERSE_CONTINUE
3259 && (traverse_mask & e_or_t) != 0)
3261 Type* tc = (*pb)->const_value()->type();
3263 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3264 return TRAVERSE_EXIT;
3265 t = (*pb)->const_value()->traverse_expression(traverse);
3269 case Named_object::NAMED_OBJECT_VAR:
3270 case Named_object::NAMED_OBJECT_RESULT_VAR:
3271 if ((traverse_mask & Traverse::traverse_variables) != 0)
3272 t = traverse->variable(*pb);
3273 if (t == TRAVERSE_CONTINUE
3274 && (traverse_mask & e_or_t) != 0)
3276 if ((*pb)->is_result_variable()
3277 || (*pb)->var_value()->has_type())
3279 Type* tv = ((*pb)->is_variable()
3280 ? (*pb)->var_value()->type()
3281 : (*pb)->result_var_value()->type());
3283 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3284 return TRAVERSE_EXIT;
3287 if (t == TRAVERSE_CONTINUE
3288 && (traverse_mask & e_or_t_or_s) != 0
3289 && (*pb)->is_variable())
3290 t = (*pb)->var_value()->traverse_expression(traverse,
3294 case Named_object::NAMED_OBJECT_FUNC:
3295 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3298 case Named_object::NAMED_OBJECT_TYPE:
3299 if ((traverse_mask & e_or_t) != 0)
3300 t = Type::traverse((*pb)->type_value(), traverse);
3303 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3304 case Named_object::NAMED_OBJECT_UNKNOWN:
3307 case Named_object::NAMED_OBJECT_PACKAGE:
3308 case Named_object::NAMED_OBJECT_SINK:
3315 if (t == TRAVERSE_EXIT)
3316 return TRAVERSE_EXIT;
3320 // No point in checking traverse_mask here--if we got here we always
3321 // want to walk the statements. The traversal can insert new
3322 // statements before or after the current statement. Inserting
3323 // statements before the current statement requires updating I via
3324 // the pointer; those statements will not be traversed. Any new
3325 // statements inserted after the current statement will be traversed
3327 for (size_t i = 0; i < this->statements_.size(); ++i)
3329 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3330 return TRAVERSE_EXIT;
3333 return TRAVERSE_CONTINUE;
3336 // Work out types for unspecified variables and constants.
3339 Block::determine_types()
3341 for (Bindings::const_definitions_iterator pb =
3342 this->bindings_->begin_definitions();
3343 pb != this->bindings_->end_definitions();
3346 if ((*pb)->is_variable())
3347 (*pb)->var_value()->determine_type();
3348 else if ((*pb)->is_const())
3349 (*pb)->const_value()->determine_type();
3352 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3353 ps != this->statements_.end();
3355 (*ps)->determine_types();
3358 // Return true if the statements in this block may fall through.
3361 Block::may_fall_through() const
3363 if (this->statements_.empty())
3365 return this->statements_.back()->may_fall_through();
3368 // Convert a block to the backend representation.
3371 Block::get_backend(Translate_context* context)
3373 Gogo* gogo = context->gogo();
3374 Named_object* function = context->function();
3375 std::vector<Bvariable*> vars;
3376 vars.reserve(this->bindings_->size_definitions());
3377 for (Bindings::const_definitions_iterator pv =
3378 this->bindings_->begin_definitions();
3379 pv != this->bindings_->end_definitions();
3382 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3383 vars.push_back((*pv)->get_backend_variable(gogo, function));
3386 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3387 // until we have a proper representation of the init function.
3388 Bfunction* bfunction;
3389 if (function == NULL)
3392 bfunction = tree_to_function(function->func_value()->get_decl());
3393 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3394 vars, this->start_location_,
3395 this->end_location_);
3397 Translate_context subcontext(gogo, function, this, ret);
3398 std::vector<Bstatement*> bstatements;
3399 bstatements.reserve(this->statements_.size());
3400 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3401 p != this->statements_.end();
3403 bstatements.push_back((*p)->get_backend(&subcontext));
3405 context->backend()->block_add_statements(ret, bstatements);
3412 Variable::Variable(Type* type, Expression* init, bool is_global,
3413 bool is_parameter, bool is_receiver,
3414 source_location location)
3415 : type_(type), init_(init), preinit_(NULL), location_(location),
3416 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3417 is_receiver_(is_receiver), is_varargs_parameter_(false),
3418 is_address_taken_(false), is_non_escaping_address_taken_(false),
3419 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
3420 type_from_range_index_(false), type_from_range_value_(false),
3421 type_from_chan_element_(false), is_type_switch_var_(false),
3422 determined_type_(false)
3424 go_assert(type != NULL || init != NULL);
3425 go_assert(!is_parameter || init == NULL);
3428 // Traverse the initializer expression.
3431 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
3433 if (this->preinit_ != NULL)
3435 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3436 return TRAVERSE_EXIT;
3438 if (this->init_ != NULL
3440 & (Traverse::traverse_expressions | Traverse::traverse_types))
3443 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3444 return TRAVERSE_EXIT;
3446 return TRAVERSE_CONTINUE;
3449 // Lower the initialization expression after parsing is complete.
3452 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
3453 Statement_inserter* inserter)
3455 if (this->init_ != NULL && !this->init_is_lowered_)
3459 // We will give an error elsewhere, this is just to prevent
3460 // an infinite loop.
3465 Statement_inserter global_inserter;
3466 if (this->is_global_)
3468 global_inserter = Statement_inserter(gogo, this);
3469 inserter = &global_inserter;
3472 gogo->lower_expression(function, inserter, &this->init_);
3474 this->seen_ = false;
3476 this->init_is_lowered_ = true;
3480 // Get the preinit block.
3483 Variable::preinit_block(Gogo* gogo)
3485 go_assert(this->is_global_);
3486 if (this->preinit_ == NULL)
3487 this->preinit_ = new Block(NULL, this->location());
3489 // If a global variable has a preinitialization statement, then we
3490 // need to have an initialization function.
3491 gogo->set_need_init_fn();
3493 return this->preinit_;
3496 // Add a statement to be run before the initialization expression.
3499 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3501 Block* b = this->preinit_block(gogo);
3502 b->add_statement(s);
3503 b->set_end_location(s->location());
3506 // In an assignment which sets a variable to a tuple of EXPR, return
3507 // the type of the first element of the tuple.
3510 Variable::type_from_tuple(Expression* expr, bool report_error) const
3512 if (expr->map_index_expression() != NULL)
3514 Map_type* mt = expr->map_index_expression()->get_map_type();
3516 return Type::make_error_type();
3517 return mt->val_type();
3519 else if (expr->receive_expression() != NULL)
3521 Expression* channel = expr->receive_expression()->channel();
3522 Type* channel_type = channel->type();
3523 if (channel_type->channel_type() == NULL)
3524 return Type::make_error_type();
3525 return channel_type->channel_type()->element_type();
3530 error_at(this->location(), "invalid tuple definition");
3531 return Type::make_error_type();
3535 // Given EXPR used in a range clause, return either the index type or
3536 // the value type of the range, depending upon GET_INDEX_TYPE.
3539 Variable::type_from_range(Expression* expr, bool get_index_type,
3540 bool report_error) const
3542 Type* t = expr->type();
3543 if (t->array_type() != NULL
3544 || (t->points_to() != NULL
3545 && t->points_to()->array_type() != NULL
3546 && !t->points_to()->is_open_array_type()))
3549 return Type::lookup_integer_type("int");
3551 return t->deref()->array_type()->element_type();
3553 else if (t->is_string_type())
3554 return Type::lookup_integer_type("int");
3555 else if (t->map_type() != NULL)
3558 return t->map_type()->key_type();
3560 return t->map_type()->val_type();
3562 else if (t->channel_type() != NULL)
3565 return t->channel_type()->element_type();
3569 error_at(this->location(),
3570 "invalid definition of value variable for channel range");
3571 return Type::make_error_type();
3577 error_at(this->location(), "invalid type for range clause");
3578 return Type::make_error_type();
3582 // EXPR should be a channel. Return the channel's element type.
3585 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3587 Type* t = expr->type();
3588 if (t->channel_type() != NULL)
3589 return t->channel_type()->element_type();
3593 error_at(this->location(), "expected channel");
3594 return Type::make_error_type();
3598 // Return the type of the Variable. This may be called before
3599 // Variable::determine_type is called, which means that we may need to
3600 // get the type from the initializer. FIXME: If we combine lowering
3601 // with type determination, then this should be unnecessary.
3606 // A variable in a type switch with a nil case will have the wrong
3607 // type here. This gets fixed up in determine_type, below.
3608 Type* type = this->type_;
3609 Expression* init = this->init_;
3610 if (this->is_type_switch_var_
3611 && this->type_->is_nil_constant_as_type())
3613 Type_guard_expression* tge = this->init_->type_guard_expression();
3614 go_assert(tge != NULL);
3621 if (this->type_ == NULL || !this->type_->is_error_type())
3623 error_at(this->location_, "variable initializer refers to itself");
3624 this->type_ = Type::make_error_type();
3633 else if (this->type_from_init_tuple_)
3634 type = this->type_from_tuple(init, false);
3635 else if (this->type_from_range_index_ || this->type_from_range_value_)
3636 type = this->type_from_range(init, this->type_from_range_index_, false);
3637 else if (this->type_from_chan_element_)
3638 type = this->type_from_chan_element(init, false);
3641 go_assert(init != NULL);
3642 type = init->type();
3643 go_assert(type != NULL);
3645 // Variables should not have abstract types.
3646 if (type->is_abstract())
3647 type = type->make_non_abstract_type();
3649 if (type->is_void_type())
3650 type = Type::make_error_type();
3653 this->seen_ = false;
3658 // Fetch the type from a const pointer, in which case it should have
3659 // been set already.
3662 Variable::type() const
3664 go_assert(this->type_ != NULL);
3668 // Set the type if necessary.
3671 Variable::determine_type()
3673 if (this->determined_type_)
3675 this->determined_type_ = true;
3677 if (this->preinit_ != NULL)
3678 this->preinit_->determine_types();
3680 // A variable in a type switch with a nil case will have the wrong
3681 // type here. It will have an initializer which is a type guard.
3682 // We want to initialize it to the value without the type guard, and
3683 // use the type of that value as well.
3684 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3686 Type_guard_expression* tge = this->init_->type_guard_expression();
3687 go_assert(tge != NULL);
3689 this->init_ = tge->expr();
3692 if (this->init_ == NULL)
3693 go_assert(this->type_ != NULL && !this->type_->is_abstract());
3694 else if (this->type_from_init_tuple_)
3696 Expression *init = this->init_;
3697 init->determine_type_no_context();
3698 this->type_ = this->type_from_tuple(init, true);
3701 else if (this->type_from_range_index_ || this->type_from_range_value_)
3703 Expression* init = this->init_;
3704 init->determine_type_no_context();
3705 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3709 else if (this->type_from_chan_element_)
3711 Expression* init = this->init_;
3712 init->determine_type_no_context();
3713 this->type_ = this->type_from_chan_element(init, true);
3718 Type_context context(this->type_, false);
3719 this->init_->determine_type(&context);
3720 if (this->type_ == NULL)
3722 Type* type = this->init_->type();
3723 go_assert(type != NULL);
3724 if (type->is_abstract())
3725 type = type->make_non_abstract_type();
3727 if (type->is_void_type())
3729 error_at(this->location_, "variable has no type");
3730 type = Type::make_error_type();
3732 else if (type->is_nil_type())
3734 error_at(this->location_, "variable defined to nil type");
3735 type = Type::make_error_type();
3737 else if (type->is_call_multiple_result_type())
3739 error_at(this->location_,
3740 "single variable set to multiple value function call");
3741 type = Type::make_error_type();
3749 // Export the variable
3752 Variable::export_var(Export* exp, const std::string& name) const
3754 go_assert(this->is_global_);
3755 exp->write_c_string("var ");
3756 exp->write_string(name);
3757 exp->write_c_string(" ");
3758 exp->write_type(this->type());
3759 exp->write_c_string(";\n");
3762 // Import a variable.
3765 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3767 imp->require_c_string("var ");
3768 *pname = imp->read_identifier();
3769 imp->require_c_string(" ");
3770 *ptype = imp->read_type();
3771 imp->require_c_string(";\n");
3774 // Convert a variable to the backend representation.
3777 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
3778 const Package* package, const std::string& name)
3780 if (this->backend_ == NULL)
3782 Backend* backend = gogo->backend();
3783 Type* type = this->type_;
3784 if (type->is_error_type()
3785 || (type->is_undefined()
3786 && (!this->is_global_ || package == NULL)))
3787 this->backend_ = backend->error_variable();
3790 bool is_parameter = this->is_parameter_;
3791 if (this->is_receiver_ && type->points_to() == NULL)
3792 is_parameter = false;
3793 if (this->is_in_heap())
3795 is_parameter = false;
3796 type = Type::make_pointer_type(type);
3799 std::string n = Gogo::unpack_hidden_name(name);
3800 Btype* btype = type->get_backend(gogo);
3803 if (this->is_global_)
3804 bvar = backend->global_variable((package == NULL
3805 ? gogo->package_name()
3808 ? gogo->unique_prefix()
3809 : package->unique_prefix()),
3813 Gogo::is_hidden_name(name),
3817 tree fndecl = function->func_value()->get_decl();
3818 Bfunction* bfunction = tree_to_function(fndecl);
3819 bool is_address_taken = (this->is_non_escaping_address_taken_
3820 && !this->is_in_heap());
3822 bvar = backend->parameter_variable(bfunction, n, btype,
3826 bvar = backend->local_variable(bfunction, n, btype,
3830 this->backend_ = bvar;
3833 return this->backend_;
3836 // Class Result_variable.
3838 // Convert a result variable to the backend representation.
3841 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
3842 const std::string& name)
3844 if (this->backend_ == NULL)
3846 Backend* backend = gogo->backend();
3847 Type* type = this->type_;
3848 if (type->is_error())
3849 this->backend_ = backend->error_variable();
3852 if (this->is_in_heap())
3853 type = Type::make_pointer_type(type);
3854 Btype* btype = type->get_backend(gogo);
3855 tree fndecl = function->func_value()->get_decl();
3856 Bfunction* bfunction = tree_to_function(fndecl);
3857 std::string n = Gogo::unpack_hidden_name(name);
3858 bool is_address_taken = (this->is_non_escaping_address_taken_
3859 && !this->is_in_heap());
3860 this->backend_ = backend->local_variable(bfunction, n, btype,
3865 return this->backend_;
3868 // Class Named_constant.
3870 // Traverse the initializer expression.
3873 Named_constant::traverse_expression(Traverse* traverse)
3875 return Expression::traverse(&this->expr_, traverse);
3878 // Determine the type of the constant.
3881 Named_constant::determine_type()
3883 if (this->type_ != NULL)
3885 Type_context context(this->type_, false);
3886 this->expr_->determine_type(&context);
3890 // A constant may have an abstract type.
3891 Type_context context(NULL, true);
3892 this->expr_->determine_type(&context);
3893 this->type_ = this->expr_->type();
3894 go_assert(this->type_ != NULL);
3898 // Indicate that we found and reported an error for this constant.
3901 Named_constant::set_error()
3903 this->type_ = Type::make_error_type();
3904 this->expr_ = Expression::make_error(this->location_);
3907 // Export a constant.
3910 Named_constant::export_const(Export* exp, const std::string& name) const
3912 exp->write_c_string("const ");
3913 exp->write_string(name);
3914 exp->write_c_string(" ");
3915 if (!this->type_->is_abstract())
3917 exp->write_type(this->type_);
3918 exp->write_c_string(" ");
3920 exp->write_c_string("= ");
3921 this->expr()->export_expression(exp);
3922 exp->write_c_string(";\n");
3925 // Import a constant.
3928 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3931 imp->require_c_string("const ");
3932 *pname = imp->read_identifier();
3933 imp->require_c_string(" ");
3934 if (imp->peek_char() == '=')
3938 *ptype = imp->read_type();
3939 imp->require_c_string(" ");
3941 imp->require_c_string("= ");
3942 *pexpr = Expression::import_expression(imp);
3943 imp->require_c_string(";\n");
3949 Type_declaration::add_method(const std::string& name, Function* function)
3951 Named_object* ret = Named_object::make_function(name, NULL, function);
3952 this->methods_.push_back(ret);
3956 // Add a method declaration.
3959 Type_declaration::add_method_declaration(const std::string& name,
3960 Function_type* type,
3961 source_location location)
3963 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3965 this->methods_.push_back(ret);
3969 // Return whether any methods ere defined.
3972 Type_declaration::has_methods() const
3974 return !this->methods_.empty();
3977 // Define methods for the real type.
3980 Type_declaration::define_methods(Named_type* nt)
3982 for (Methods::const_iterator p = this->methods_.begin();
3983 p != this->methods_.end();
3985 nt->add_existing_method(*p);
3988 // We are using the type. Return true if we should issue a warning.
3991 Type_declaration::using_type()
3993 bool ret = !this->issued_warning_;
3994 this->issued_warning_ = true;
3998 // Class Unknown_name.
4000 // Set the real named object.
4003 Unknown_name::set_real_named_object(Named_object* no)
4005 go_assert(this->real_named_object_ == NULL);
4006 go_assert(!no->is_unknown());
4007 this->real_named_object_ = no;
4010 // Class Named_object.
4012 Named_object::Named_object(const std::string& name,
4013 const Package* package,
4014 Classification classification)
4015 : name_(name), package_(package), classification_(classification),
4018 if (Gogo::is_sink_name(name))
4019 go_assert(classification == NAMED_OBJECT_SINK);
4022 // Make an unknown name. This is used by the parser. The name must
4023 // be resolved later. Unknown names are only added in the current
4027 Named_object::make_unknown_name(const std::string& name,
4028 source_location location)
4030 Named_object* named_object = new Named_object(name, NULL,
4031 NAMED_OBJECT_UNKNOWN);
4032 Unknown_name* value = new Unknown_name(location);
4033 named_object->u_.unknown_value = value;
4034 return named_object;
4040 Named_object::make_constant(const Typed_identifier& tid,
4041 const Package* package, Expression* expr,
4044 Named_object* named_object = new Named_object(tid.name(), package,
4045 NAMED_OBJECT_CONST);
4046 Named_constant* named_constant = new Named_constant(tid.type(), expr,
4049 named_object->u_.const_value = named_constant;
4050 return named_object;
4053 // Make a named type.
4056 Named_object::make_type(const std::string& name, const Package* package,
4057 Type* type, source_location location)
4059 Named_object* named_object = new Named_object(name, package,
4061 Named_type* named_type = Type::make_named_type(named_object, type, location);
4062 named_object->u_.type_value = named_type;
4063 return named_object;
4066 // Make a type declaration.
4069 Named_object::make_type_declaration(const std::string& name,
4070 const Package* package,
4071 source_location location)
4073 Named_object* named_object = new Named_object(name, package,
4074 NAMED_OBJECT_TYPE_DECLARATION);
4075 Type_declaration* type_declaration = new Type_declaration(location);
4076 named_object->u_.type_declaration = type_declaration;
4077 return named_object;
4083 Named_object::make_variable(const std::string& name, const Package* package,
4086 Named_object* named_object = new Named_object(name, package,
4088 named_object->u_.var_value = variable;
4089 return named_object;
4092 // Make a result variable.
4095 Named_object::make_result_variable(const std::string& name,
4096 Result_variable* result)
4098 Named_object* named_object = new Named_object(name, NULL,
4099 NAMED_OBJECT_RESULT_VAR);
4100 named_object->u_.result_var_value = result;
4101 return named_object;
4104 // Make a sink. This is used for the special blank identifier _.
4107 Named_object::make_sink()
4109 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4112 // Make a named function.
4115 Named_object::make_function(const std::string& name, const Package* package,
4118 Named_object* named_object = new Named_object(name, package,
4120 named_object->u_.func_value = function;
4121 return named_object;
4124 // Make a function declaration.
4127 Named_object::make_function_declaration(const std::string& name,
4128 const Package* package,
4129 Function_type* fntype,
4130 source_location location)
4132 Named_object* named_object = new Named_object(name, package,
4133 NAMED_OBJECT_FUNC_DECLARATION);
4134 Function_declaration *func_decl = new Function_declaration(fntype, location);
4135 named_object->u_.func_declaration_value = func_decl;
4136 return named_object;
4142 Named_object::make_package(const std::string& alias, Package* package)
4144 Named_object* named_object = new Named_object(alias, NULL,
4145 NAMED_OBJECT_PACKAGE);
4146 named_object->u_.package_value = package;
4147 return named_object;
4150 // Return the name to use in an error message.
4153 Named_object::message_name() const
4155 if (this->package_ == NULL)
4156 return Gogo::message_name(this->name_);
4157 std::string ret = Gogo::message_name(this->package_->name());
4159 ret += Gogo::message_name(this->name_);
4163 // Set the type when a declaration is defined.
4166 Named_object::set_type_value(Named_type* named_type)
4168 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4169 Type_declaration* td = this->u_.type_declaration;
4170 td->define_methods(named_type);
4171 Named_object* in_function = td->in_function();
4172 if (in_function != NULL)
4173 named_type->set_in_function(in_function);
4175 this->classification_ = NAMED_OBJECT_TYPE;
4176 this->u_.type_value = named_type;
4179 // Define a function which was previously declared.
4182 Named_object::set_function_value(Function* function)
4184 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4185 this->classification_ = NAMED_OBJECT_FUNC;
4186 // FIXME: We should free the old value.
4187 this->u_.func_value = function;
4190 // Declare an unknown object as a type declaration.
4193 Named_object::declare_as_type()
4195 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4196 Unknown_name* unk = this->u_.unknown_value;
4197 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4198 this->u_.type_declaration = new Type_declaration(unk->location());
4202 // Return the location of a named object.
4205 Named_object::location() const
4207 switch (this->classification_)
4210 case NAMED_OBJECT_UNINITIALIZED:
4213 case NAMED_OBJECT_UNKNOWN:
4214 return this->unknown_value()->location();
4216 case NAMED_OBJECT_CONST:
4217 return this->const_value()->location();
4219 case NAMED_OBJECT_TYPE:
4220 return this->type_value()->location();
4222 case NAMED_OBJECT_TYPE_DECLARATION:
4223 return this->type_declaration_value()->location();
4225 case NAMED_OBJECT_VAR:
4226 return this->var_value()->location();
4228 case NAMED_OBJECT_RESULT_VAR:
4229 return this->result_var_value()->location();
4231 case NAMED_OBJECT_SINK:
4234 case NAMED_OBJECT_FUNC:
4235 return this->func_value()->location();
4237 case NAMED_OBJECT_FUNC_DECLARATION:
4238 return this->func_declaration_value()->location();
4240 case NAMED_OBJECT_PACKAGE:
4241 return this->package_value()->location();
4245 // Export a named object.
4248 Named_object::export_named_object(Export* exp) const
4250 switch (this->classification_)
4253 case NAMED_OBJECT_UNINITIALIZED:
4254 case NAMED_OBJECT_UNKNOWN:
4257 case NAMED_OBJECT_CONST:
4258 this->const_value()->export_const(exp, this->name_);
4261 case NAMED_OBJECT_TYPE:
4262 this->type_value()->export_named_type(exp, this->name_);
4265 case NAMED_OBJECT_TYPE_DECLARATION:
4266 error_at(this->type_declaration_value()->location(),
4267 "attempt to export %<%s%> which was declared but not defined",
4268 this->message_name().c_str());
4271 case NAMED_OBJECT_FUNC_DECLARATION:
4272 this->func_declaration_value()->export_func(exp, this->name_);
4275 case NAMED_OBJECT_VAR:
4276 this->var_value()->export_var(exp, this->name_);
4279 case NAMED_OBJECT_RESULT_VAR:
4280 case NAMED_OBJECT_SINK:
4283 case NAMED_OBJECT_FUNC:
4284 this->func_value()->export_func(exp, this->name_);
4289 // Convert a variable to the backend representation.
4292 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4294 if (this->classification_ == NAMED_OBJECT_VAR)
4295 return this->var_value()->get_backend_variable(gogo, function,
4296 this->package_, this->name_);
4297 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4298 return this->result_var_value()->get_backend_variable(gogo, function,
4306 Bindings::Bindings(Bindings* enclosing)
4307 : enclosing_(enclosing), named_objects_(), bindings_()
4314 Bindings::clear_file_scope()
4316 Contour::iterator p = this->bindings_.begin();
4317 while (p != this->bindings_.end())
4320 if (p->second->package() != NULL)
4322 else if (p->second->is_package())
4324 else if (p->second->is_function()
4325 && !p->second->func_value()->type()->is_method()
4326 && Gogo::unpack_hidden_name(p->second->name()) == "init")
4334 p = this->bindings_.erase(p);
4338 // Look up a symbol.
4341 Bindings::lookup(const std::string& name) const
4343 Contour::const_iterator p = this->bindings_.find(name);
4344 if (p != this->bindings_.end())
4345 return p->second->resolve();
4346 else if (this->enclosing_ != NULL)
4347 return this->enclosing_->lookup(name);
4352 // Look up a symbol locally.
4355 Bindings::lookup_local(const std::string& name) const
4357 Contour::const_iterator p = this->bindings_.find(name);
4358 if (p == this->bindings_.end())
4363 // Remove an object from a set of bindings. This is used for a
4364 // special case in thunks for functions which call recover.
4367 Bindings::remove_binding(Named_object* no)
4369 Contour::iterator pb = this->bindings_.find(no->name());
4370 go_assert(pb != this->bindings_.end());
4371 this->bindings_.erase(pb);
4372 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4373 pn != this->named_objects_.end();
4378 this->named_objects_.erase(pn);
4385 // Add a method to the list of objects. This is not added to the
4386 // lookup table. This is so that we have a single list of objects
4387 // declared at the top level, which we walk through when it's time to
4388 // convert to trees.
4391 Bindings::add_method(Named_object* method)
4393 this->named_objects_.push_back(method);
4396 // Add a generic Named_object to a Contour.
4399 Bindings::add_named_object_to_contour(Contour* contour,
4400 Named_object* named_object)
4402 go_assert(named_object == named_object->resolve());
4403 const std::string& name(named_object->name());
4404 go_assert(!Gogo::is_sink_name(name));
4406 std::pair<Contour::iterator, bool> ins =
4407 contour->insert(std::make_pair(name, named_object));
4410 // The name was already there.
4411 if (named_object->package() != NULL
4412 && ins.first->second->package() == named_object->package()
4413 && (ins.first->second->classification()
4414 == named_object->classification()))
4416 // This is a second import of the same object.
4417 return ins.first->second;
4419 ins.first->second = this->new_definition(ins.first->second,
4421 return ins.first->second;
4425 // Don't push declarations on the list. We push them on when
4426 // and if we find the definitions. That way we genericize the
4427 // functions in order.
4428 if (!named_object->is_type_declaration()
4429 && !named_object->is_function_declaration()
4430 && !named_object->is_unknown())
4431 this->named_objects_.push_back(named_object);
4432 return named_object;
4436 // We had an existing named object OLD_OBJECT, and we've seen a new
4437 // one NEW_OBJECT with the same name. FIXME: This does not free the
4438 // new object when we don't need it.
4441 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4444 switch (old_object->classification())
4447 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4450 case Named_object::NAMED_OBJECT_UNKNOWN:
4452 Named_object* real = old_object->unknown_value()->real_named_object();
4454 return this->new_definition(real, new_object);
4455 go_assert(!new_object->is_unknown());
4456 old_object->unknown_value()->set_real_named_object(new_object);
4457 if (!new_object->is_type_declaration()
4458 && !new_object->is_function_declaration())
4459 this->named_objects_.push_back(new_object);
4463 case Named_object::NAMED_OBJECT_CONST:
4466 case Named_object::NAMED_OBJECT_TYPE:
4467 if (new_object->is_type_declaration())
4471 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4472 if (new_object->is_type_declaration())
4474 if (new_object->is_type())
4476 old_object->set_type_value(new_object->type_value());
4477 new_object->type_value()->set_named_object(old_object);
4478 this->named_objects_.push_back(old_object);
4483 case Named_object::NAMED_OBJECT_VAR:
4484 case Named_object::NAMED_OBJECT_RESULT_VAR:
4487 case Named_object::NAMED_OBJECT_SINK:
4490 case Named_object::NAMED_OBJECT_FUNC:
4491 if (new_object->is_function_declaration())
4493 if (!new_object->func_declaration_value()->asm_name().empty())
4494 sorry("__asm__ for function definitions");
4495 Function_type* old_type = old_object->func_value()->type();
4496 Function_type* new_type =
4497 new_object->func_declaration_value()->type();
4498 if (old_type->is_valid_redeclaration(new_type, &reason))
4503 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4505 Function_type* old_type = old_object->func_declaration_value()->type();
4506 if (new_object->is_function_declaration())
4508 Function_type* new_type =
4509 new_object->func_declaration_value()->type();
4510 if (old_type->is_valid_redeclaration(new_type, &reason))
4513 if (new_object->is_function())
4515 Function_type* new_type = new_object->func_value()->type();
4516 if (old_type->is_valid_redeclaration(new_type, &reason))
4518 if (!old_object->func_declaration_value()->asm_name().empty())
4519 sorry("__asm__ for function definitions");
4520 old_object->set_function_value(new_object->func_value());
4521 this->named_objects_.push_back(old_object);
4528 case Named_object::NAMED_OBJECT_PACKAGE:
4529 if (new_object->is_package()
4530 && (old_object->package_value()->name()
4531 == new_object->package_value()->name()))
4537 std::string n = old_object->message_name();
4539 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4541 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4544 inform(old_object->location(), "previous definition of %qs was here",
4550 // Add a named type.
4553 Bindings::add_named_type(Named_type* named_type)
4555 return this->add_named_object(named_type->named_object());
4561 Bindings::add_function(const std::string& name, const Package* package,
4564 return this->add_named_object(Named_object::make_function(name, package,
4568 // Add a function declaration.
4571 Bindings::add_function_declaration(const std::string& name,
4572 const Package* package,
4573 Function_type* type,
4574 source_location location)
4576 Named_object* no = Named_object::make_function_declaration(name, package,
4578 return this->add_named_object(no);
4581 // Define a type which was previously declared.
4584 Bindings::define_type(Named_object* no, Named_type* type)
4586 no->set_type_value(type);
4587 this->named_objects_.push_back(no);
4590 // Traverse bindings.
4593 Bindings::traverse(Traverse* traverse, bool is_global)
4595 unsigned int traverse_mask = traverse->traverse_mask();
4597 // We don't use an iterator because we permit the traversal to add
4598 // new global objects.
4599 const unsigned int e_or_t = (Traverse::traverse_expressions
4600 | Traverse::traverse_types);
4601 const unsigned int e_or_t_or_s = (e_or_t
4602 | Traverse::traverse_statements);
4603 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4605 Named_object* p = this->named_objects_[i];
4606 int t = TRAVERSE_CONTINUE;
4607 switch (p->classification())
4609 case Named_object::NAMED_OBJECT_CONST:
4610 if ((traverse_mask & Traverse::traverse_constants) != 0)
4611 t = traverse->constant(p, is_global);
4612 if (t == TRAVERSE_CONTINUE
4613 && (traverse_mask & e_or_t) != 0)
4615 Type* tc = p->const_value()->type();
4617 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
4618 return TRAVERSE_EXIT;
4619 t = p->const_value()->traverse_expression(traverse);
4623 case Named_object::NAMED_OBJECT_VAR:
4624 case Named_object::NAMED_OBJECT_RESULT_VAR:
4625 if ((traverse_mask & Traverse::traverse_variables) != 0)
4626 t = traverse->variable(p);
4627 if (t == TRAVERSE_CONTINUE
4628 && (traverse_mask & e_or_t) != 0)
4630 if (p->is_result_variable()
4631 || p->var_value()->has_type())
4633 Type* tv = (p->is_variable()
4634 ? p->var_value()->type()
4635 : p->result_var_value()->type());
4637 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
4638 return TRAVERSE_EXIT;
4641 if (t == TRAVERSE_CONTINUE
4642 && (traverse_mask & e_or_t_or_s) != 0
4643 && p->is_variable())
4644 t = p->var_value()->traverse_expression(traverse, traverse_mask);
4647 case Named_object::NAMED_OBJECT_FUNC:
4648 if ((traverse_mask & Traverse::traverse_functions) != 0)
4649 t = traverse->function(p);
4651 if (t == TRAVERSE_CONTINUE
4653 & (Traverse::traverse_variables
4654 | Traverse::traverse_constants
4655 | Traverse::traverse_functions
4656 | Traverse::traverse_blocks
4657 | Traverse::traverse_statements
4658 | Traverse::traverse_expressions
4659 | Traverse::traverse_types)) != 0)
4661 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4662 return TRAVERSE_EXIT;
4666 case Named_object::NAMED_OBJECT_PACKAGE:
4667 // These are traversed in Gogo::traverse.
4668 go_assert(is_global);
4671 case Named_object::NAMED_OBJECT_TYPE:
4672 if ((traverse_mask & e_or_t) != 0)
4673 t = Type::traverse(p->type_value(), traverse);
4676 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4677 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4678 case Named_object::NAMED_OBJECT_UNKNOWN:
4681 case Named_object::NAMED_OBJECT_SINK:
4686 if (t == TRAVERSE_EXIT)
4687 return TRAVERSE_EXIT;
4690 return TRAVERSE_CONTINUE;
4695 // Get the backend representation for a label.
4698 Label::get_backend_label(Translate_context* context)
4700 if (this->blabel_ == NULL)
4702 Function* function = context->function()->func_value();
4703 tree fndecl = function->get_decl();
4704 Bfunction* bfunction = tree_to_function(fndecl);
4705 this->blabel_ = context->backend()->label(bfunction, this->name_,
4708 return this->blabel_;
4711 // Return an expression for the address of this label.
4714 Label::get_addr(Translate_context* context, source_location location)
4716 Blabel* label = this->get_backend_label(context);
4717 return context->backend()->label_address(label, location);
4720 // Class Unnamed_label.
4722 // Get the backend representation for an unnamed label.
4725 Unnamed_label::get_blabel(Translate_context* context)
4727 if (this->blabel_ == NULL)
4729 Function* function = context->function()->func_value();
4730 tree fndecl = function->get_decl();
4731 Bfunction* bfunction = tree_to_function(fndecl);
4732 this->blabel_ = context->backend()->label(bfunction, "",
4735 return this->blabel_;
4738 // Return a statement which defines this unnamed label.
4741 Unnamed_label::get_definition(Translate_context* context)
4743 Blabel* blabel = this->get_blabel(context);
4744 return context->backend()->label_definition_statement(blabel);
4747 // Return a goto statement to this unnamed label.
4750 Unnamed_label::get_goto(Translate_context* context, source_location location)
4752 Blabel* blabel = this->get_blabel(context);
4753 return context->backend()->goto_statement(blabel, location);
4758 Package::Package(const std::string& name, const std::string& unique_prefix,
4759 source_location location)
4760 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4761 priority_(0), location_(location), used_(false), is_imported_(false),
4762 uses_sink_alias_(false)
4764 go_assert(!name.empty() && !unique_prefix.empty());
4767 // Set the priority. We may see multiple priorities for an imported
4768 // package; we want to use the largest one.
4771 Package::set_priority(int priority)
4773 if (priority > this->priority_)
4774 this->priority_ = priority;
4777 // Determine types of constants. Everything else in a package
4778 // (variables, function declarations) should already have a fixed
4779 // type. Constants may have abstract types.
4782 Package::determine_types()
4784 Bindings* bindings = this->bindings_;
4785 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4786 p != bindings->end_definitions();
4789 if ((*p)->is_const())
4790 (*p)->const_value()->determine_type();
4798 Traverse::~Traverse()
4800 if (this->types_seen_ != NULL)
4801 delete this->types_seen_;
4802 if (this->expressions_seen_ != NULL)
4803 delete this->expressions_seen_;
4806 // Record that we are looking at a type, and return true if we have
4810 Traverse::remember_type(const Type* type)
4812 if (type->is_error_type())
4814 go_assert((this->traverse_mask() & traverse_types) != 0
4815 || (this->traverse_mask() & traverse_expressions) != 0);
4816 // We only have to remember named types, as they are the only ones
4817 // we can see multiple times in a traversal.
4818 if (type->classification() != Type::TYPE_NAMED)
4820 if (this->types_seen_ == NULL)
4821 this->types_seen_ = new Types_seen();
4822 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4826 // Record that we are looking at an expression, and return true if we
4827 // have already seen it.
4830 Traverse::remember_expression(const Expression* expression)
4832 go_assert((this->traverse_mask() & traverse_types) != 0
4833 || (this->traverse_mask() & traverse_expressions) != 0);
4834 if (this->expressions_seen_ == NULL)
4835 this->expressions_seen_ = new Expressions_seen();
4836 std::pair<Expressions_seen::iterator, bool> ins =
4837 this->expressions_seen_->insert(expression);
4841 // The default versions of these functions should never be called: the
4842 // traversal mask indicates which functions may be called.
4845 Traverse::variable(Named_object*)
4851 Traverse::constant(Named_object*, bool)
4857 Traverse::function(Named_object*)
4863 Traverse::block(Block*)
4869 Traverse::statement(Block*, size_t*, Statement*)
4875 Traverse::expression(Expression**)
4881 Traverse::type(Type*)
4886 // Class Statement_inserter.
4889 Statement_inserter::insert(Statement* s)
4891 if (this->block_ != NULL)
4893 go_assert(this->pindex_ != NULL);
4894 this->block_->insert_statement_before(*this->pindex_, s);
4897 else if (this->var_ != NULL)
4898 this->var_->add_preinit_statement(this->gogo_, s);