a63abfefde3806805c64d968f646874c8bc35e81
[gcc.git] / gcc / go / gofrontend / gogo.cc
1 // gogo.cc -- Go frontend parsed representation.
2
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 #include "go-system.h"
8
9 #include "go-c.h"
10 #include "go-dump.h"
11 #include "lex.h"
12 #include "types.h"
13 #include "statements.h"
14 #include "expressions.h"
15 #include "dataflow.h"
16 #include "import.h"
17 #include "export.h"
18 #include "gogo.h"
19
20 // Class Gogo.
21
22 Gogo::Gogo(int int_type_size, int pointer_size)
23 : package_(NULL),
24 functions_(),
25 globals_(new Bindings(NULL)),
26 imports_(),
27 imported_unsafe_(false),
28 packages_(),
29 map_descriptors_(NULL),
30 type_descriptor_decls_(NULL),
31 init_functions_(),
32 need_init_fn_(false),
33 init_fn_name_(),
34 imported_init_fns_(),
35 unique_prefix_(),
36 unique_prefix_specified_(false),
37 interface_types_()
38 {
39 const source_location loc = BUILTINS_LOCATION;
40
41 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
42 RUNTIME_TYPE_KIND_UINT8);
43 this->add_named_type(uint8_type);
44 this->add_named_type(Type::make_integer_type("uint16", true, 16,
45 RUNTIME_TYPE_KIND_UINT16));
46 this->add_named_type(Type::make_integer_type("uint32", true, 32,
47 RUNTIME_TYPE_KIND_UINT32));
48 this->add_named_type(Type::make_integer_type("uint64", true, 64,
49 RUNTIME_TYPE_KIND_UINT64));
50
51 this->add_named_type(Type::make_integer_type("int8", false, 8,
52 RUNTIME_TYPE_KIND_INT8));
53 this->add_named_type(Type::make_integer_type("int16", false, 16,
54 RUNTIME_TYPE_KIND_INT16));
55 this->add_named_type(Type::make_integer_type("int32", false, 32,
56 RUNTIME_TYPE_KIND_INT32));
57 this->add_named_type(Type::make_integer_type("int64", false, 64,
58 RUNTIME_TYPE_KIND_INT64));
59
60 this->add_named_type(Type::make_float_type("float32", 32,
61 RUNTIME_TYPE_KIND_FLOAT32));
62 this->add_named_type(Type::make_float_type("float64", 64,
63 RUNTIME_TYPE_KIND_FLOAT64));
64
65 this->add_named_type(Type::make_complex_type("complex64", 64,
66 RUNTIME_TYPE_KIND_COMPLEX64));
67 this->add_named_type(Type::make_complex_type("complex128", 128,
68 RUNTIME_TYPE_KIND_COMPLEX128));
69
70 if (int_type_size < 32)
71 int_type_size = 32;
72 this->add_named_type(Type::make_integer_type("uint", true,
73 int_type_size,
74 RUNTIME_TYPE_KIND_UINT));
75 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
76 RUNTIME_TYPE_KIND_INT);
77 this->add_named_type(int_type);
78
79 // "byte" is an alias for "uint8". Construct a Named_object which
80 // points to UINT8_TYPE. Note that this breaks the normal pairing
81 // in which a Named_object points to a Named_type which points back
82 // to the same Named_object.
83 Named_object* byte_type = this->declare_type("byte", loc);
84 byte_type->set_type_value(uint8_type);
85
86 this->add_named_type(Type::make_integer_type("uintptr", true,
87 pointer_size,
88 RUNTIME_TYPE_KIND_UINTPTR));
89
90 this->add_named_type(Type::make_named_bool_type());
91
92 this->add_named_type(Type::make_named_string_type());
93
94 this->globals_->add_constant(Typed_identifier("true",
95 Type::make_boolean_type(),
96 loc),
97 NULL,
98 Expression::make_boolean(true, loc),
99 0);
100 this->globals_->add_constant(Typed_identifier("false",
101 Type::make_boolean_type(),
102 loc),
103 NULL,
104 Expression::make_boolean(false, loc),
105 0);
106
107 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
108 loc),
109 NULL,
110 Expression::make_nil(loc),
111 0);
112
113 Type* abstract_int_type = Type::make_abstract_integer_type();
114 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
115 loc),
116 NULL,
117 Expression::make_iota(),
118 0);
119
120 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
121 new_type->set_is_varargs();
122 new_type->set_is_builtin();
123 this->globals_->add_function_declaration("new", NULL, new_type, loc);
124
125 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
126 make_type->set_is_varargs();
127 make_type->set_is_builtin();
128 this->globals_->add_function_declaration("make", NULL, make_type, loc);
129
130 Typed_identifier_list* len_result = new Typed_identifier_list();
131 len_result->push_back(Typed_identifier("", int_type, loc));
132 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
133 loc);
134 len_type->set_is_builtin();
135 this->globals_->add_function_declaration("len", NULL, len_type, loc);
136
137 Typed_identifier_list* cap_result = new Typed_identifier_list();
138 cap_result->push_back(Typed_identifier("", int_type, loc));
139 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
140 loc);
141 cap_type->set_is_builtin();
142 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
143
144 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
145 print_type->set_is_varargs();
146 print_type->set_is_builtin();
147 this->globals_->add_function_declaration("print", NULL, print_type, loc);
148
149 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
150 print_type->set_is_varargs();
151 print_type->set_is_builtin();
152 this->globals_->add_function_declaration("println", NULL, print_type, loc);
153
154 Type *empty = Type::make_interface_type(NULL, loc);
155 Typed_identifier_list* panic_parms = new Typed_identifier_list();
156 panic_parms->push_back(Typed_identifier("e", empty, loc));
157 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
158 NULL, loc);
159 panic_type->set_is_builtin();
160 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
161
162 Typed_identifier_list* recover_result = new Typed_identifier_list();
163 recover_result->push_back(Typed_identifier("", empty, loc));
164 Function_type* recover_type = Type::make_function_type(NULL, NULL,
165 recover_result,
166 loc);
167 recover_type->set_is_builtin();
168 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
169
170 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
171 close_type->set_is_varargs();
172 close_type->set_is_builtin();
173 this->globals_->add_function_declaration("close", NULL, close_type, loc);
174
175 Typed_identifier_list* closed_result = new Typed_identifier_list();
176 closed_result->push_back(Typed_identifier("", Type::lookup_bool_type(),
177 loc));
178 Function_type* closed_type = Type::make_function_type(NULL, NULL,
179 closed_result, loc);
180 closed_type->set_is_varargs();
181 closed_type->set_is_builtin();
182 this->globals_->add_function_declaration("closed", NULL, closed_type, loc);
183
184 Typed_identifier_list* copy_result = new Typed_identifier_list();
185 copy_result->push_back(Typed_identifier("", int_type, loc));
186 Function_type* copy_type = Type::make_function_type(NULL, NULL,
187 copy_result, loc);
188 copy_type->set_is_varargs();
189 copy_type->set_is_builtin();
190 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
191
192 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
193 append_type->set_is_varargs();
194 append_type->set_is_builtin();
195 this->globals_->add_function_declaration("append", NULL, append_type, loc);
196
197 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 complex_type->set_is_varargs();
199 complex_type->set_is_builtin();
200 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
201
202 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
203 real_type->set_is_varargs();
204 real_type->set_is_builtin();
205 this->globals_->add_function_declaration("real", NULL, real_type, loc);
206
207 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
208 imag_type->set_is_varargs();
209 imag_type->set_is_builtin();
210 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
211
212 this->define_builtin_function_trees();
213
214 // Declare "init", to ensure that it is not defined with parameters
215 // or return values.
216 this->declare_function("init",
217 Type::make_function_type(NULL, NULL, NULL, loc),
218 loc);
219 }
220
221 // Munge name for use in an error message.
222
223 std::string
224 Gogo::message_name(const std::string& name)
225 {
226 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
227 }
228
229 // Get the package name.
230
231 const std::string&
232 Gogo::package_name() const
233 {
234 gcc_assert(this->package_ != NULL);
235 return this->package_->name();
236 }
237
238 // Set the package name.
239
240 void
241 Gogo::set_package_name(const std::string& package_name,
242 source_location location)
243 {
244 if (this->package_ != NULL && this->package_->name() != package_name)
245 {
246 error_at(location, "expected package %<%s%>",
247 Gogo::message_name(this->package_->name()).c_str());
248 return;
249 }
250
251 // If the user did not specify a unique prefix, we always use "go".
252 // This in effect requires that the package name be unique.
253 if (this->unique_prefix_.empty())
254 this->unique_prefix_ = "go";
255
256 this->package_ = this->register_package(package_name, this->unique_prefix_,
257 location);
258
259 // We used to permit people to qualify symbols with the current
260 // package name (e.g., P.x), but we no longer do.
261 // this->globals_->add_package(package_name, this->package_);
262
263 if (this->is_main_package())
264 {
265 // Declare "main" as a function which takes no parameters and
266 // returns no value.
267 this->declare_function("main",
268 Type::make_function_type(NULL, NULL, NULL,
269 BUILTINS_LOCATION),
270 BUILTINS_LOCATION);
271 }
272 }
273
274 // Return whether this is the "main" package. This is not true if
275 // -fgo-prefix was used.
276
277 bool
278 Gogo::is_main_package() const
279 {
280 return this->package_name() == "main" && !this->unique_prefix_specified_;
281 }
282
283 // Import a package.
284
285 void
286 Gogo::import_package(const std::string& filename,
287 const std::string& local_name,
288 bool is_local_name_exported,
289 source_location location)
290 {
291 if (filename == "unsafe")
292 {
293 this->import_unsafe(local_name, is_local_name_exported, location);
294 return;
295 }
296
297 Imports::const_iterator p = this->imports_.find(filename);
298 if (p != this->imports_.end())
299 {
300 Package* package = p->second;
301 package->set_location(location);
302 package->set_is_imported();
303 std::string ln = local_name;
304 bool is_ln_exported = is_local_name_exported;
305 if (ln.empty())
306 {
307 ln = package->name();
308 is_ln_exported = Lex::is_exported_name(ln);
309 }
310 if (ln != ".")
311 {
312 ln = this->pack_hidden_name(ln, is_ln_exported);
313 this->package_->bindings()->add_package(ln, package);
314 }
315 else
316 {
317 Bindings* bindings = package->bindings();
318 for (Bindings::const_declarations_iterator p =
319 bindings->begin_declarations();
320 p != bindings->end_declarations();
321 ++p)
322 this->add_named_object(p->second);
323 }
324 return;
325 }
326
327 Import::Stream* stream = Import::open_package(filename, location);
328 if (stream == NULL)
329 {
330 error_at(location, "import file %qs not found", filename.c_str());
331 return;
332 }
333
334 Import imp(stream, location);
335 imp.register_builtin_types(this);
336 Package* package = imp.import(this, local_name, is_local_name_exported);
337 if (package != NULL)
338 {
339 if (package->name() == this->package_name()
340 && package->unique_prefix() == this->unique_prefix())
341 error_at(location,
342 ("imported package uses same package name and prefix "
343 "as package being compiled (see -fgo-prefix option)"));
344
345 this->imports_.insert(std::make_pair(filename, package));
346 package->set_is_imported();
347 }
348
349 delete stream;
350 }
351
352 // Add an import control function for an imported package to the list.
353
354 void
355 Gogo::add_import_init_fn(const std::string& package_name,
356 const std::string& init_name, int prio)
357 {
358 for (std::set<Import_init>::const_iterator p =
359 this->imported_init_fns_.begin();
360 p != this->imported_init_fns_.end();
361 ++p)
362 {
363 if (p->init_name() == init_name
364 && (p->package_name() != package_name || p->priority() != prio))
365 {
366 error("duplicate package initialization name %qs",
367 Gogo::message_name(init_name).c_str());
368 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
369 Gogo::message_name(p->package_name()).c_str(),
370 p->priority());
371 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
372 Gogo::message_name(package_name).c_str(), prio);
373 return;
374 }
375 }
376
377 this->imported_init_fns_.insert(Import_init(package_name, init_name,
378 prio));
379 }
380
381 // Return whether we are at the global binding level.
382
383 bool
384 Gogo::in_global_scope() const
385 {
386 return this->functions_.empty();
387 }
388
389 // Return the current binding contour.
390
391 Bindings*
392 Gogo::current_bindings()
393 {
394 if (!this->functions_.empty())
395 return this->functions_.back().blocks.back()->bindings();
396 else if (this->package_ != NULL)
397 return this->package_->bindings();
398 else
399 return this->globals_;
400 }
401
402 const Bindings*
403 Gogo::current_bindings() const
404 {
405 if (!this->functions_.empty())
406 return this->functions_.back().blocks.back()->bindings();
407 else if (this->package_ != NULL)
408 return this->package_->bindings();
409 else
410 return this->globals_;
411 }
412
413 // Return the current block.
414
415 Block*
416 Gogo::current_block()
417 {
418 if (this->functions_.empty())
419 return NULL;
420 else
421 return this->functions_.back().blocks.back();
422 }
423
424 // Look up a name in the current binding contour. If PFUNCTION is not
425 // NULL, set it to the function in which the name is defined, or NULL
426 // if the name is defined in global scope.
427
428 Named_object*
429 Gogo::lookup(const std::string& name, Named_object** pfunction) const
430 {
431 if (pfunction != NULL)
432 *pfunction = NULL;
433
434 if (Gogo::is_sink_name(name))
435 return Named_object::make_sink();
436
437 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
438 p != this->functions_.rend();
439 ++p)
440 {
441 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
442 if (ret != NULL)
443 {
444 if (pfunction != NULL)
445 *pfunction = p->function;
446 return ret;
447 }
448 }
449
450 if (this->package_ != NULL)
451 {
452 Named_object* ret = this->package_->bindings()->lookup(name);
453 if (ret != NULL)
454 {
455 if (ret->package() != NULL)
456 ret->package()->set_used();
457 return ret;
458 }
459 }
460
461 // We do not look in the global namespace. If we did, the global
462 // namespace would effectively hide names which were defined in
463 // package scope which we have not yet seen. Instead,
464 // define_global_names is called after parsing is over to connect
465 // undefined names at package scope with names defined at global
466 // scope.
467
468 return NULL;
469 }
470
471 // Look up a name in the current block, without searching enclosing
472 // blocks.
473
474 Named_object*
475 Gogo::lookup_in_block(const std::string& name) const
476 {
477 gcc_assert(!this->functions_.empty());
478 gcc_assert(!this->functions_.back().blocks.empty());
479 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
480 }
481
482 // Look up a name in the global namespace.
483
484 Named_object*
485 Gogo::lookup_global(const char* name) const
486 {
487 return this->globals_->lookup(name);
488 }
489
490 // Add an imported package.
491
492 Package*
493 Gogo::add_imported_package(const std::string& real_name,
494 const std::string& alias_arg,
495 bool is_alias_exported,
496 const std::string& unique_prefix,
497 source_location location,
498 bool* padd_to_globals)
499 {
500 // FIXME: Now that we compile packages as a whole, should we permit
501 // importing the current package?
502 if (this->package_name() == real_name
503 && this->unique_prefix() == unique_prefix)
504 {
505 *padd_to_globals = false;
506 if (!alias_arg.empty() && alias_arg != ".")
507 {
508 std::string alias = this->pack_hidden_name(alias_arg,
509 is_alias_exported);
510 this->package_->bindings()->add_package(alias, this->package_);
511 }
512 return this->package_;
513 }
514 else if (alias_arg == ".")
515 {
516 *padd_to_globals = true;
517 return this->register_package(real_name, unique_prefix, location);
518 }
519 else if (alias_arg == "_")
520 {
521 Package* ret = this->register_package(real_name, unique_prefix, location);
522 ret->set_uses_sink_alias();
523 return ret;
524 }
525 else
526 {
527 *padd_to_globals = false;
528 std::string alias = alias_arg;
529 if (alias.empty())
530 {
531 alias = real_name;
532 is_alias_exported = Lex::is_exported_name(alias);
533 }
534 alias = this->pack_hidden_name(alias, is_alias_exported);
535 Named_object* no = this->add_package(real_name, alias, unique_prefix,
536 location);
537 if (!no->is_package())
538 return NULL;
539 return no->package_value();
540 }
541 }
542
543 // Add a package.
544
545 Named_object*
546 Gogo::add_package(const std::string& real_name, const std::string& alias,
547 const std::string& unique_prefix, source_location location)
548 {
549 gcc_assert(this->in_global_scope());
550
551 // Register the package. Note that we might have already seen it in
552 // an earlier import.
553 Package* package = this->register_package(real_name, unique_prefix, location);
554
555 return this->package_->bindings()->add_package(alias, package);
556 }
557
558 // Register a package. This package may or may not be imported. This
559 // returns the Package structure for the package, creating if it
560 // necessary.
561
562 Package*
563 Gogo::register_package(const std::string& package_name,
564 const std::string& unique_prefix,
565 source_location location)
566 {
567 gcc_assert(!unique_prefix.empty() && !package_name.empty());
568 std::string name = unique_prefix + '.' + package_name;
569 Package* package = NULL;
570 std::pair<Packages::iterator, bool> ins =
571 this->packages_.insert(std::make_pair(name, package));
572 if (!ins.second)
573 {
574 // We have seen this package name before.
575 package = ins.first->second;
576 gcc_assert(package != NULL);
577 gcc_assert(package->name() == package_name
578 && package->unique_prefix() == unique_prefix);
579 if (package->location() == UNKNOWN_LOCATION)
580 package->set_location(location);
581 }
582 else
583 {
584 // First time we have seen this package name.
585 package = new Package(package_name, unique_prefix, location);
586 gcc_assert(ins.first->second == NULL);
587 ins.first->second = package;
588 }
589
590 return package;
591 }
592
593 // Start compiling a function.
594
595 Named_object*
596 Gogo::start_function(const std::string& name, Function_type* type,
597 bool add_method_to_type, source_location location)
598 {
599 bool at_top_level = this->functions_.empty();
600
601 Block* block = new Block(NULL, location);
602
603 Function* enclosing = (at_top_level
604 ? NULL
605 : this->functions_.back().function->func_value());
606
607 Function* function = new Function(type, enclosing, block, location);
608
609 if (type->is_method())
610 {
611 const Typed_identifier* receiver = type->receiver();
612 Variable* this_param = new Variable(receiver->type(), NULL, false,
613 true, true, location);
614 std::string name = receiver->name();
615 if (name.empty())
616 {
617 // We need to give receivers a name since they wind up in
618 // DECL_ARGUMENTS. FIXME.
619 static unsigned int count;
620 char buf[50];
621 snprintf(buf, sizeof buf, "r.%u", count);
622 ++count;
623 name = buf;
624 }
625 block->bindings()->add_variable(name, NULL, this_param);
626 }
627
628 const Typed_identifier_list* parameters = type->parameters();
629 bool is_varargs = type->is_varargs();
630 if (parameters != NULL)
631 {
632 for (Typed_identifier_list::const_iterator p = parameters->begin();
633 p != parameters->end();
634 ++p)
635 {
636 Variable* param = new Variable(p->type(), NULL, false, true, false,
637 location);
638 if (is_varargs && p + 1 == parameters->end())
639 param->set_is_varargs_parameter();
640
641 std::string name = p->name();
642 if (name.empty() || Gogo::is_sink_name(name))
643 {
644 // We need to give parameters a name since they wind up
645 // in DECL_ARGUMENTS. FIXME.
646 static unsigned int count;
647 char buf[50];
648 snprintf(buf, sizeof buf, "p.%u", count);
649 ++count;
650 name = buf;
651 }
652 block->bindings()->add_variable(name, NULL, param);
653 }
654 }
655
656 function->create_named_result_variables(this);
657
658 const std::string* pname;
659 std::string nested_name;
660 if (!name.empty())
661 pname = &name;
662 else
663 {
664 // Invent a name for a nested function.
665 static int nested_count;
666 char buf[30];
667 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
668 ++nested_count;
669 nested_name = buf;
670 pname = &nested_name;
671 }
672
673 Named_object* ret;
674 if (Gogo::is_sink_name(*pname))
675 {
676 static int sink_count;
677 char buf[30];
678 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
679 ++sink_count;
680 ret = Named_object::make_function(buf, NULL, function);
681 }
682 else if (!type->is_method())
683 {
684 ret = this->package_->bindings()->add_function(*pname, NULL, function);
685 if (!ret->is_function() || ret->func_value() != function)
686 {
687 // Redefinition error. Invent a name to avoid knockon
688 // errors.
689 static int redefinition_count;
690 char buf[30];
691 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
692 ++redefinition_count;
693 ret = this->package_->bindings()->add_function(buf, NULL, function);
694 }
695 }
696 else
697 {
698 if (!add_method_to_type)
699 ret = Named_object::make_function(name, NULL, function);
700 else
701 {
702 gcc_assert(at_top_level);
703 Type* rtype = type->receiver()->type();
704
705 // We want to look through the pointer created by the
706 // parser, without getting an error if the type is not yet
707 // defined.
708 if (rtype->classification() == Type::TYPE_POINTER)
709 rtype = rtype->points_to();
710
711 if (rtype->is_error_type())
712 ret = Named_object::make_function(name, NULL, function);
713 else if (rtype->named_type() != NULL)
714 {
715 ret = rtype->named_type()->add_method(name, function);
716 if (!ret->is_function())
717 {
718 // Redefinition error.
719 ret = Named_object::make_function(name, NULL, function);
720 }
721 }
722 else if (rtype->forward_declaration_type() != NULL)
723 {
724 Named_object* type_no =
725 rtype->forward_declaration_type()->named_object();
726 if (type_no->is_unknown())
727 {
728 // If we are seeing methods it really must be a
729 // type. Declare it as such. An alternative would
730 // be to support lists of methods for unknown
731 // expressions. Either way the error messages if
732 // this is not a type are going to get confusing.
733 Named_object* declared =
734 this->declare_package_type(type_no->name(),
735 type_no->location());
736 gcc_assert(declared
737 == type_no->unknown_value()->real_named_object());
738 }
739 ret = rtype->forward_declaration_type()->add_method(name,
740 function);
741 }
742 else
743 gcc_unreachable();
744 }
745 this->package_->bindings()->add_method(ret);
746 }
747
748 this->functions_.resize(this->functions_.size() + 1);
749 Open_function& of(this->functions_.back());
750 of.function = ret;
751 of.blocks.push_back(block);
752
753 if (!type->is_method() && Gogo::unpack_hidden_name(name) == "init")
754 {
755 this->init_functions_.push_back(ret);
756 this->need_init_fn_ = true;
757 }
758
759 return ret;
760 }
761
762 // Finish compiling a function.
763
764 void
765 Gogo::finish_function(source_location location)
766 {
767 this->finish_block(location);
768 gcc_assert(this->functions_.back().blocks.empty());
769 this->functions_.pop_back();
770 }
771
772 // Return the current function.
773
774 Named_object*
775 Gogo::current_function() const
776 {
777 gcc_assert(!this->functions_.empty());
778 return this->functions_.back().function;
779 }
780
781 // Start a new block.
782
783 void
784 Gogo::start_block(source_location location)
785 {
786 gcc_assert(!this->functions_.empty());
787 Block* block = new Block(this->current_block(), location);
788 this->functions_.back().blocks.push_back(block);
789 }
790
791 // Finish a block.
792
793 Block*
794 Gogo::finish_block(source_location location)
795 {
796 gcc_assert(!this->functions_.empty());
797 gcc_assert(!this->functions_.back().blocks.empty());
798 Block* block = this->functions_.back().blocks.back();
799 this->functions_.back().blocks.pop_back();
800 block->set_end_location(location);
801 return block;
802 }
803
804 // Add an unknown name.
805
806 Named_object*
807 Gogo::add_unknown_name(const std::string& name, source_location location)
808 {
809 return this->package_->bindings()->add_unknown_name(name, location);
810 }
811
812 // Declare a function.
813
814 Named_object*
815 Gogo::declare_function(const std::string& name, Function_type* type,
816 source_location location)
817 {
818 if (!type->is_method())
819 return this->current_bindings()->add_function_declaration(name, NULL, type,
820 location);
821 else
822 {
823 // We don't bother to add this to the list of global
824 // declarations.
825 Type* rtype = type->receiver()->type();
826
827 // We want to look through the pointer created by the
828 // parser, without getting an error if the type is not yet
829 // defined.
830 if (rtype->classification() == Type::TYPE_POINTER)
831 rtype = rtype->points_to();
832
833 if (rtype->is_error_type())
834 return NULL;
835 else if (rtype->named_type() != NULL)
836 return rtype->named_type()->add_method_declaration(name, NULL, type,
837 location);
838 else if (rtype->forward_declaration_type() != NULL)
839 {
840 Forward_declaration_type* ftype = rtype->forward_declaration_type();
841 return ftype->add_method_declaration(name, type, location);
842 }
843 else
844 gcc_unreachable();
845 }
846 }
847
848 // Add a label definition.
849
850 Label*
851 Gogo::add_label_definition(const std::string& label_name,
852 source_location location)
853 {
854 gcc_assert(!this->functions_.empty());
855 Function* func = this->functions_.back().function->func_value();
856 Label* label = func->add_label_definition(label_name, location);
857 this->add_statement(Statement::make_label_statement(label, location));
858 return label;
859 }
860
861 // Add a label reference.
862
863 Label*
864 Gogo::add_label_reference(const std::string& label_name)
865 {
866 gcc_assert(!this->functions_.empty());
867 Function* func = this->functions_.back().function->func_value();
868 return func->add_label_reference(label_name);
869 }
870
871 // Add a statement.
872
873 void
874 Gogo::add_statement(Statement* statement)
875 {
876 gcc_assert(!this->functions_.empty()
877 && !this->functions_.back().blocks.empty());
878 this->functions_.back().blocks.back()->add_statement(statement);
879 }
880
881 // Add a block.
882
883 void
884 Gogo::add_block(Block* block, source_location location)
885 {
886 gcc_assert(!this->functions_.empty()
887 && !this->functions_.back().blocks.empty());
888 Statement* statement = Statement::make_block_statement(block, location);
889 this->functions_.back().blocks.back()->add_statement(statement);
890 }
891
892 // Add a constant.
893
894 Named_object*
895 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
896 int iota_value)
897 {
898 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
899 }
900
901 // Add a type.
902
903 void
904 Gogo::add_type(const std::string& name, Type* type, source_location location)
905 {
906 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
907 location);
908 if (!this->in_global_scope() && no->is_type())
909 no->type_value()->set_in_function(this->functions_.back().function);
910 }
911
912 // Add a named type.
913
914 void
915 Gogo::add_named_type(Named_type* type)
916 {
917 gcc_assert(this->in_global_scope());
918 this->current_bindings()->add_named_type(type);
919 }
920
921 // Declare a type.
922
923 Named_object*
924 Gogo::declare_type(const std::string& name, source_location location)
925 {
926 Bindings* bindings = this->current_bindings();
927 Named_object* no = bindings->add_type_declaration(name, NULL, location);
928 if (!this->in_global_scope() && no->is_type_declaration())
929 {
930 Named_object* f = this->functions_.back().function;
931 no->type_declaration_value()->set_in_function(f);
932 }
933 return no;
934 }
935
936 // Declare a type at the package level.
937
938 Named_object*
939 Gogo::declare_package_type(const std::string& name, source_location location)
940 {
941 return this->package_->bindings()->add_type_declaration(name, NULL, location);
942 }
943
944 // Define a type which was already declared.
945
946 void
947 Gogo::define_type(Named_object* no, Named_type* type)
948 {
949 this->current_bindings()->define_type(no, type);
950 }
951
952 // Add a variable.
953
954 Named_object*
955 Gogo::add_variable(const std::string& name, Variable* variable)
956 {
957 Named_object* no = this->current_bindings()->add_variable(name, NULL,
958 variable);
959
960 // In a function the middle-end wants to see a DECL_EXPR node.
961 if (no != NULL
962 && no->is_variable()
963 && !no->var_value()->is_parameter()
964 && !this->functions_.empty())
965 this->add_statement(Statement::make_variable_declaration(no));
966
967 return no;
968 }
969
970 // Add a sink--a reference to the blank identifier _.
971
972 Named_object*
973 Gogo::add_sink()
974 {
975 return Named_object::make_sink();
976 }
977
978 // Add a named object.
979
980 void
981 Gogo::add_named_object(Named_object* no)
982 {
983 this->current_bindings()->add_named_object(no);
984 }
985
986 // Record that we've seen an interface type.
987
988 void
989 Gogo::record_interface_type(Interface_type* itype)
990 {
991 this->interface_types_.push_back(itype);
992 }
993
994 // Return a name for a thunk object.
995
996 std::string
997 Gogo::thunk_name()
998 {
999 static int thunk_count;
1000 char thunk_name[50];
1001 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1002 ++thunk_count;
1003 return thunk_name;
1004 }
1005
1006 // Return whether a function is a thunk.
1007
1008 bool
1009 Gogo::is_thunk(const Named_object* no)
1010 {
1011 return no->name().compare(0, 6, "$thunk") == 0;
1012 }
1013
1014 // Define the global names. We do this only after parsing all the
1015 // input files, because the program might define the global names
1016 // itself.
1017
1018 void
1019 Gogo::define_global_names()
1020 {
1021 for (Bindings::const_declarations_iterator p =
1022 this->globals_->begin_declarations();
1023 p != this->globals_->end_declarations();
1024 ++p)
1025 {
1026 Named_object* global_no = p->second;
1027 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1028 Named_object* no = this->package_->bindings()->lookup(name);
1029 if (no == NULL)
1030 continue;
1031 no = no->resolve();
1032 if (no->is_type_declaration())
1033 {
1034 if (global_no->is_type())
1035 {
1036 if (no->type_declaration_value()->has_methods())
1037 error_at(no->location(),
1038 "may not define methods for global type");
1039 no->set_type_value(global_no->type_value());
1040 }
1041 else
1042 {
1043 error_at(no->location(), "expected type");
1044 Type* errtype = Type::make_error_type();
1045 Named_object* err = Named_object::make_type("error", NULL,
1046 errtype,
1047 BUILTINS_LOCATION);
1048 no->set_type_value(err->type_value());
1049 }
1050 }
1051 else if (no->is_unknown())
1052 no->unknown_value()->set_real_named_object(global_no);
1053 }
1054 }
1055
1056 // Clear out names in file scope.
1057
1058 void
1059 Gogo::clear_file_scope()
1060 {
1061 this->package_->bindings()->clear_file_scope();
1062
1063 // Warn about packages which were imported but not used.
1064 for (Packages::iterator p = this->packages_.begin();
1065 p != this->packages_.end();
1066 ++p)
1067 {
1068 Package* package = p->second;
1069 if (package != this->package_
1070 && package->is_imported()
1071 && !package->used()
1072 && !package->uses_sink_alias()
1073 && !saw_errors())
1074 error_at(package->location(), "imported and not used: %s",
1075 Gogo::message_name(package->name()).c_str());
1076 package->clear_is_imported();
1077 package->clear_uses_sink_alias();
1078 package->clear_used();
1079 }
1080 }
1081
1082 // Traverse the tree.
1083
1084 void
1085 Gogo::traverse(Traverse* traverse)
1086 {
1087 // Traverse the current package first for consistency. The other
1088 // packages will only contain imported types, constants, and
1089 // declarations.
1090 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1091 return;
1092 for (Packages::const_iterator p = this->packages_.begin();
1093 p != this->packages_.end();
1094 ++p)
1095 {
1096 if (p->second != this->package_)
1097 {
1098 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1099 break;
1100 }
1101 }
1102 }
1103
1104 // Traversal class used to verify types.
1105
1106 class Verify_types : public Traverse
1107 {
1108 public:
1109 Verify_types()
1110 : Traverse(traverse_types)
1111 { }
1112
1113 int
1114 type(Type*);
1115 };
1116
1117 // Verify that a type is correct.
1118
1119 int
1120 Verify_types::type(Type* t)
1121 {
1122 // Don't verify types defined in other packages.
1123 Named_type* nt = t->named_type();
1124 if (nt != NULL && nt->named_object()->package() != NULL)
1125 return TRAVERSE_SKIP_COMPONENTS;
1126
1127 if (!t->verify())
1128 return TRAVERSE_SKIP_COMPONENTS;
1129 return TRAVERSE_CONTINUE;
1130 }
1131
1132 // Verify that all types are correct.
1133
1134 void
1135 Gogo::verify_types()
1136 {
1137 Verify_types traverse;
1138 this->traverse(&traverse);
1139 }
1140
1141 // Traversal class used to lower parse tree.
1142
1143 class Lower_parse_tree : public Traverse
1144 {
1145 public:
1146 Lower_parse_tree(Gogo* gogo, Named_object* function)
1147 : Traverse(traverse_variables
1148 | traverse_constants
1149 | traverse_functions
1150 | traverse_statements
1151 | traverse_expressions),
1152 gogo_(gogo), function_(function), iota_value_(-1)
1153 { }
1154
1155 int
1156 variable(Named_object*);
1157
1158 int
1159 constant(Named_object*, bool);
1160
1161 int
1162 function(Named_object*);
1163
1164 int
1165 statement(Block*, size_t* pindex, Statement*);
1166
1167 int
1168 expression(Expression**);
1169
1170 private:
1171 // General IR.
1172 Gogo* gogo_;
1173 // The function we are traversing.
1174 Named_object* function_;
1175 // Value to use for the predeclared constant iota.
1176 int iota_value_;
1177 };
1178
1179 // Lower variables. We handle variables specially to break loops in
1180 // which a variable initialization expression refers to itself. The
1181 // loop breaking is in lower_init_expression.
1182
1183 int
1184 Lower_parse_tree::variable(Named_object* no)
1185 {
1186 if (no->is_variable())
1187 no->var_value()->lower_init_expression(this->gogo_, this->function_);
1188 return TRAVERSE_CONTINUE;
1189 }
1190
1191 // Lower constants. We handle constants specially so that we can set
1192 // the right value for the predeclared constant iota. This works in
1193 // conjunction with the way we lower Const_expression objects.
1194
1195 int
1196 Lower_parse_tree::constant(Named_object* no, bool)
1197 {
1198 Named_constant* nc = no->const_value();
1199
1200 // Don't get into trouble if the constant's initializer expression
1201 // refers to the constant itself.
1202 if (nc->lowering())
1203 return TRAVERSE_CONTINUE;
1204 nc->set_lowering();
1205
1206 gcc_assert(this->iota_value_ == -1);
1207 this->iota_value_ = nc->iota_value();
1208 nc->traverse_expression(this);
1209 this->iota_value_ = -1;
1210
1211 nc->clear_lowering();
1212
1213 // We will traverse the expression a second time, but that will be
1214 // fast.
1215
1216 return TRAVERSE_CONTINUE;
1217 }
1218
1219 // Lower function closure types. Record the function while lowering
1220 // it, so that we can pass it down when lowering an expression.
1221
1222 int
1223 Lower_parse_tree::function(Named_object* no)
1224 {
1225 no->func_value()->set_closure_type();
1226
1227 gcc_assert(this->function_ == NULL);
1228 this->function_ = no;
1229 int t = no->func_value()->traverse(this);
1230 this->function_ = NULL;
1231
1232 if (t == TRAVERSE_EXIT)
1233 return t;
1234 return TRAVERSE_SKIP_COMPONENTS;
1235 }
1236
1237 // Lower statement parse trees.
1238
1239 int
1240 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1241 {
1242 // Lower the expressions first.
1243 int t = sorig->traverse_contents(this);
1244 if (t == TRAVERSE_EXIT)
1245 return t;
1246
1247 // Keep lowering until nothing changes.
1248 Statement* s = sorig;
1249 while (true)
1250 {
1251 Statement* snew = s->lower(this->gogo_, block);
1252 if (snew == s)
1253 break;
1254 s = snew;
1255 t = s->traverse_contents(this);
1256 if (t == TRAVERSE_EXIT)
1257 return t;
1258 }
1259
1260 if (s != sorig)
1261 block->replace_statement(*pindex, s);
1262
1263 return TRAVERSE_SKIP_COMPONENTS;
1264 }
1265
1266 // Lower expression parse trees.
1267
1268 int
1269 Lower_parse_tree::expression(Expression** pexpr)
1270 {
1271 // We have to lower all subexpressions first, so that we can get
1272 // their type if necessary. This is awkward, because we don't have
1273 // a postorder traversal pass.
1274 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1275 return TRAVERSE_EXIT;
1276 // Keep lowering until nothing changes.
1277 while (true)
1278 {
1279 Expression* e = *pexpr;
1280 Expression* enew = e->lower(this->gogo_, this->function_,
1281 this->iota_value_);
1282 if (enew == e)
1283 break;
1284 *pexpr = enew;
1285 }
1286 return TRAVERSE_SKIP_COMPONENTS;
1287 }
1288
1289 // Lower the parse tree. This is called after the parse is complete,
1290 // when all names should be resolved.
1291
1292 void
1293 Gogo::lower_parse_tree()
1294 {
1295 Lower_parse_tree lower_parse_tree(this, NULL);
1296 this->traverse(&lower_parse_tree);
1297 }
1298
1299 // Lower an expression.
1300
1301 void
1302 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1303 {
1304 Lower_parse_tree lower_parse_tree(this, function);
1305 lower_parse_tree.expression(pexpr);
1306 }
1307
1308 // Lower a constant. This is called when lowering a reference to a
1309 // constant. We have to make sure that the constant has already been
1310 // lowered.
1311
1312 void
1313 Gogo::lower_constant(Named_object* no)
1314 {
1315 gcc_assert(no->is_const());
1316 Lower_parse_tree lower(this, NULL);
1317 lower.constant(no, false);
1318 }
1319
1320 // Look for interface types to finalize methods of inherited
1321 // interfaces.
1322
1323 class Finalize_methods : public Traverse
1324 {
1325 public:
1326 Finalize_methods(Gogo* gogo)
1327 : Traverse(traverse_types),
1328 gogo_(gogo)
1329 { }
1330
1331 int
1332 type(Type*);
1333
1334 private:
1335 Gogo* gogo_;
1336 };
1337
1338 // Finalize the methods of an interface type.
1339
1340 int
1341 Finalize_methods::type(Type* t)
1342 {
1343 // Check the classification so that we don't finalize the methods
1344 // twice for a named interface type.
1345 switch (t->classification())
1346 {
1347 case Type::TYPE_INTERFACE:
1348 t->interface_type()->finalize_methods();
1349 break;
1350
1351 case Type::TYPE_NAMED:
1352 {
1353 // We have to finalize the methods of the real type first.
1354 // But if the real type is a struct type, then we only want to
1355 // finalize the methods of the field types, not of the struct
1356 // type itself. We don't want to add methods to the struct,
1357 // since it has a name.
1358 Type* rt = t->named_type()->real_type();
1359 if (rt->classification() != Type::TYPE_STRUCT)
1360 {
1361 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1362 return TRAVERSE_EXIT;
1363 }
1364 else
1365 {
1366 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1367 return TRAVERSE_EXIT;
1368 }
1369
1370 t->named_type()->finalize_methods(this->gogo_);
1371
1372 return TRAVERSE_SKIP_COMPONENTS;
1373 }
1374
1375 case Type::TYPE_STRUCT:
1376 t->struct_type()->finalize_methods(this->gogo_);
1377 break;
1378
1379 default:
1380 break;
1381 }
1382
1383 return TRAVERSE_CONTINUE;
1384 }
1385
1386 // Finalize method lists and build stub methods for types.
1387
1388 void
1389 Gogo::finalize_methods()
1390 {
1391 Finalize_methods finalize(this);
1392 this->traverse(&finalize);
1393 }
1394
1395 // Set types for unspecified variables and constants.
1396
1397 void
1398 Gogo::determine_types()
1399 {
1400 Bindings* bindings = this->current_bindings();
1401 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1402 p != bindings->end_definitions();
1403 ++p)
1404 {
1405 if ((*p)->is_function())
1406 (*p)->func_value()->determine_types();
1407 else if ((*p)->is_variable())
1408 (*p)->var_value()->determine_type();
1409 else if ((*p)->is_const())
1410 (*p)->const_value()->determine_type();
1411
1412 // See if a variable requires us to build an initialization
1413 // function. We know that we will see all global variables
1414 // here.
1415 if (!this->need_init_fn_ && (*p)->is_variable())
1416 {
1417 Variable* variable = (*p)->var_value();
1418
1419 // If this is a global variable which requires runtime
1420 // initialization, we need an initialization function.
1421 if (!variable->is_global())
1422 ;
1423 else if (variable->init() == NULL)
1424 ;
1425 else if (variable->type()->interface_type() != NULL)
1426 this->need_init_fn_ = true;
1427 else if (variable->init()->is_constant())
1428 ;
1429 else if (!variable->init()->is_composite_literal())
1430 this->need_init_fn_ = true;
1431 else if (variable->init()->is_nonconstant_composite_literal())
1432 this->need_init_fn_ = true;
1433
1434 // If this is a global variable which holds a pointer value,
1435 // then we need an initialization function to register it as a
1436 // GC root.
1437 if (variable->is_global() && variable->type()->has_pointer())
1438 this->need_init_fn_ = true;
1439 }
1440 }
1441
1442 // Determine the types of constants in packages.
1443 for (Packages::const_iterator p = this->packages_.begin();
1444 p != this->packages_.end();
1445 ++p)
1446 p->second->determine_types();
1447 }
1448
1449 // Traversal class used for type checking.
1450
1451 class Check_types_traverse : public Traverse
1452 {
1453 public:
1454 Check_types_traverse(Gogo* gogo)
1455 : Traverse(traverse_variables
1456 | traverse_constants
1457 | traverse_statements
1458 | traverse_expressions),
1459 gogo_(gogo)
1460 { }
1461
1462 int
1463 variable(Named_object*);
1464
1465 int
1466 constant(Named_object*, bool);
1467
1468 int
1469 statement(Block*, size_t* pindex, Statement*);
1470
1471 int
1472 expression(Expression**);
1473
1474 private:
1475 // General IR.
1476 Gogo* gogo_;
1477 };
1478
1479 // Check that a variable initializer has the right type.
1480
1481 int
1482 Check_types_traverse::variable(Named_object* named_object)
1483 {
1484 if (named_object->is_variable())
1485 {
1486 Variable* var = named_object->var_value();
1487 Expression* init = var->init();
1488 std::string reason;
1489 if (init != NULL
1490 && !Type::are_assignable(var->type(), init->type(), &reason))
1491 {
1492 if (reason.empty())
1493 error_at(var->location(), "incompatible type in initialization");
1494 else
1495 error_at(var->location(),
1496 "incompatible type in initialization (%s)",
1497 reason.c_str());
1498 var->clear_init();
1499 }
1500 }
1501 return TRAVERSE_CONTINUE;
1502 }
1503
1504 // Check that a constant initializer has the right type.
1505
1506 int
1507 Check_types_traverse::constant(Named_object* named_object, bool)
1508 {
1509 Named_constant* constant = named_object->const_value();
1510 Type* ctype = constant->type();
1511 if (ctype->integer_type() == NULL
1512 && ctype->float_type() == NULL
1513 && ctype->complex_type() == NULL
1514 && !ctype->is_boolean_type()
1515 && !ctype->is_string_type())
1516 {
1517 if (!ctype->is_error_type())
1518 error_at(constant->location(), "invalid constant type");
1519 constant->set_error();
1520 }
1521 else if (!constant->expr()->is_constant())
1522 {
1523 error_at(constant->expr()->location(), "expression is not constant");
1524 constant->set_error();
1525 }
1526 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1527 NULL))
1528 {
1529 error_at(constant->location(),
1530 "initialization expression has wrong type");
1531 constant->set_error();
1532 }
1533 return TRAVERSE_CONTINUE;
1534 }
1535
1536 // Check that types are valid in a statement.
1537
1538 int
1539 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1540 {
1541 s->check_types(this->gogo_);
1542 return TRAVERSE_CONTINUE;
1543 }
1544
1545 // Check that types are valid in an expression.
1546
1547 int
1548 Check_types_traverse::expression(Expression** expr)
1549 {
1550 (*expr)->check_types(this->gogo_);
1551 return TRAVERSE_CONTINUE;
1552 }
1553
1554 // Check that types are valid.
1555
1556 void
1557 Gogo::check_types()
1558 {
1559 Check_types_traverse traverse(this);
1560 this->traverse(&traverse);
1561 }
1562
1563 // Check the types in a single block.
1564
1565 void
1566 Gogo::check_types_in_block(Block* block)
1567 {
1568 Check_types_traverse traverse(this);
1569 block->traverse(&traverse);
1570 }
1571
1572 // A traversal class used to find a single shortcut operator within an
1573 // expression.
1574
1575 class Find_shortcut : public Traverse
1576 {
1577 public:
1578 Find_shortcut()
1579 : Traverse(traverse_blocks
1580 | traverse_statements
1581 | traverse_expressions),
1582 found_(NULL)
1583 { }
1584
1585 // A pointer to the expression which was found, or NULL if none was
1586 // found.
1587 Expression**
1588 found() const
1589 { return this->found_; }
1590
1591 protected:
1592 int
1593 block(Block*)
1594 { return TRAVERSE_SKIP_COMPONENTS; }
1595
1596 int
1597 statement(Block*, size_t*, Statement*)
1598 { return TRAVERSE_SKIP_COMPONENTS; }
1599
1600 int
1601 expression(Expression**);
1602
1603 private:
1604 Expression** found_;
1605 };
1606
1607 // Find a shortcut expression.
1608
1609 int
1610 Find_shortcut::expression(Expression** pexpr)
1611 {
1612 Expression* expr = *pexpr;
1613 Binary_expression* be = expr->binary_expression();
1614 if (be == NULL)
1615 return TRAVERSE_CONTINUE;
1616 Operator op = be->op();
1617 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1618 return TRAVERSE_CONTINUE;
1619 gcc_assert(this->found_ == NULL);
1620 this->found_ = pexpr;
1621 return TRAVERSE_EXIT;
1622 }
1623
1624 // A traversal class used to turn shortcut operators into explicit if
1625 // statements.
1626
1627 class Shortcuts : public Traverse
1628 {
1629 public:
1630 Shortcuts(Gogo* gogo)
1631 : Traverse(traverse_variables
1632 | traverse_statements),
1633 gogo_(gogo)
1634 { }
1635
1636 protected:
1637 int
1638 variable(Named_object*);
1639
1640 int
1641 statement(Block*, size_t*, Statement*);
1642
1643 private:
1644 // Convert a shortcut operator.
1645 Statement*
1646 convert_shortcut(Block* enclosing, Expression** pshortcut);
1647
1648 // The IR.
1649 Gogo* gogo_;
1650 };
1651
1652 // Remove shortcut operators in a single statement.
1653
1654 int
1655 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1656 {
1657 // FIXME: This approach doesn't work for switch statements, because
1658 // we add the new statements before the whole switch when we need to
1659 // instead add them just before the switch expression. The right
1660 // fix is probably to lower switch statements with nonconstant cases
1661 // to a series of conditionals.
1662 if (s->switch_statement() != NULL)
1663 return TRAVERSE_CONTINUE;
1664
1665 while (true)
1666 {
1667 Find_shortcut find_shortcut;
1668
1669 // If S is a variable declaration, then ordinary traversal won't
1670 // do anything. We want to explicitly traverse the
1671 // initialization expression if there is one.
1672 Variable_declaration_statement* vds = s->variable_declaration_statement();
1673 Expression* init = NULL;
1674 if (vds == NULL)
1675 s->traverse_contents(&find_shortcut);
1676 else
1677 {
1678 init = vds->var()->var_value()->init();
1679 if (init == NULL)
1680 return TRAVERSE_CONTINUE;
1681 init->traverse(&init, &find_shortcut);
1682 }
1683 Expression** pshortcut = find_shortcut.found();
1684 if (pshortcut == NULL)
1685 return TRAVERSE_CONTINUE;
1686
1687 Statement* snew = this->convert_shortcut(block, pshortcut);
1688 block->insert_statement_before(*pindex, snew);
1689 ++*pindex;
1690
1691 if (pshortcut == &init)
1692 vds->var()->var_value()->set_init(init);
1693 }
1694 }
1695
1696 // Remove shortcut operators in the initializer of a global variable.
1697
1698 int
1699 Shortcuts::variable(Named_object* no)
1700 {
1701 if (no->is_result_variable())
1702 return TRAVERSE_CONTINUE;
1703 Variable* var = no->var_value();
1704 Expression* init = var->init();
1705 if (!var->is_global() || init == NULL)
1706 return TRAVERSE_CONTINUE;
1707
1708 while (true)
1709 {
1710 Find_shortcut find_shortcut;
1711 init->traverse(&init, &find_shortcut);
1712 Expression** pshortcut = find_shortcut.found();
1713 if (pshortcut == NULL)
1714 return TRAVERSE_CONTINUE;
1715
1716 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1717 var->add_preinit_statement(this->gogo_, snew);
1718 if (pshortcut == &init)
1719 var->set_init(init);
1720 }
1721 }
1722
1723 // Given an expression which uses a shortcut operator, return a
1724 // statement which implements it, and update *PSHORTCUT accordingly.
1725
1726 Statement*
1727 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1728 {
1729 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1730 Expression* left = shortcut->left();
1731 Expression* right = shortcut->right();
1732 source_location loc = shortcut->location();
1733
1734 Block* retblock = new Block(enclosing, loc);
1735 retblock->set_end_location(loc);
1736
1737 Temporary_statement* ts = Statement::make_temporary(Type::make_boolean_type(),
1738 left, loc);
1739 retblock->add_statement(ts);
1740
1741 Block* block = new Block(retblock, loc);
1742 block->set_end_location(loc);
1743 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1744 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1745 block->add_statement(assign);
1746
1747 Expression* cond = Expression::make_temporary_reference(ts, loc);
1748 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1749 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1750
1751 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1752 loc);
1753 retblock->add_statement(if_statement);
1754
1755 *pshortcut = Expression::make_temporary_reference(ts, loc);
1756
1757 delete shortcut;
1758
1759 // Now convert any shortcut operators in LEFT and RIGHT.
1760 Shortcuts shortcuts(this->gogo_);
1761 retblock->traverse(&shortcuts);
1762
1763 return Statement::make_block_statement(retblock, loc);
1764 }
1765
1766 // Turn shortcut operators into explicit if statements. Doing this
1767 // considerably simplifies the order of evaluation rules.
1768
1769 void
1770 Gogo::remove_shortcuts()
1771 {
1772 Shortcuts shortcuts(this);
1773 this->traverse(&shortcuts);
1774 }
1775
1776 // A traversal class which finds all the expressions which must be
1777 // evaluated in order within a statement or larger expression. This
1778 // is used to implement the rules about order of evaluation.
1779
1780 class Find_eval_ordering : public Traverse
1781 {
1782 private:
1783 typedef std::vector<Expression**> Expression_pointers;
1784
1785 public:
1786 Find_eval_ordering()
1787 : Traverse(traverse_blocks
1788 | traverse_statements
1789 | traverse_expressions),
1790 exprs_()
1791 { }
1792
1793 size_t
1794 size() const
1795 { return this->exprs_.size(); }
1796
1797 typedef Expression_pointers::const_iterator const_iterator;
1798
1799 const_iterator
1800 begin() const
1801 { return this->exprs_.begin(); }
1802
1803 const_iterator
1804 end() const
1805 { return this->exprs_.end(); }
1806
1807 protected:
1808 int
1809 block(Block*)
1810 { return TRAVERSE_SKIP_COMPONENTS; }
1811
1812 int
1813 statement(Block*, size_t*, Statement*)
1814 { return TRAVERSE_SKIP_COMPONENTS; }
1815
1816 int
1817 expression(Expression**);
1818
1819 private:
1820 // A list of pointers to expressions with side-effects.
1821 Expression_pointers exprs_;
1822 };
1823
1824 // If an expression must be evaluated in order, put it on the list.
1825
1826 int
1827 Find_eval_ordering::expression(Expression** expression_pointer)
1828 {
1829 // We have to look at subexpressions before this one.
1830 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1831 return TRAVERSE_EXIT;
1832 if ((*expression_pointer)->must_eval_in_order())
1833 this->exprs_.push_back(expression_pointer);
1834 return TRAVERSE_SKIP_COMPONENTS;
1835 }
1836
1837 // A traversal class for ordering evaluations.
1838
1839 class Order_eval : public Traverse
1840 {
1841 public:
1842 Order_eval(Gogo* gogo)
1843 : Traverse(traverse_variables
1844 | traverse_statements),
1845 gogo_(gogo)
1846 { }
1847
1848 int
1849 variable(Named_object*);
1850
1851 int
1852 statement(Block*, size_t*, Statement*);
1853
1854 private:
1855 // The IR.
1856 Gogo* gogo_;
1857 };
1858
1859 // Implement the order of evaluation rules for a statement.
1860
1861 int
1862 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1863 {
1864 // FIXME: This approach doesn't work for switch statements, because
1865 // we add the new statements before the whole switch when we need to
1866 // instead add them just before the switch expression. The right
1867 // fix is probably to lower switch statements with nonconstant cases
1868 // to a series of conditionals.
1869 if (s->switch_statement() != NULL)
1870 return TRAVERSE_CONTINUE;
1871
1872 Find_eval_ordering find_eval_ordering;
1873
1874 // If S is a variable declaration, then ordinary traversal won't do
1875 // anything. We want to explicitly traverse the initialization
1876 // expression if there is one.
1877 Variable_declaration_statement* vds = s->variable_declaration_statement();
1878 Expression* init = NULL;
1879 Expression* orig_init = NULL;
1880 if (vds == NULL)
1881 s->traverse_contents(&find_eval_ordering);
1882 else
1883 {
1884 init = vds->var()->var_value()->init();
1885 if (init == NULL)
1886 return TRAVERSE_CONTINUE;
1887 orig_init = init;
1888
1889 // It might seem that this could be
1890 // init->traverse_subexpressions. Unfortunately that can fail
1891 // in a case like
1892 // var err os.Error
1893 // newvar, err := call(arg())
1894 // Here newvar will have an init of call result 0 of
1895 // call(arg()). If we only traverse subexpressions, we will
1896 // only find arg(), and we won't bother to move anything out.
1897 // Then we get to the assignment to err, we will traverse the
1898 // whole statement, and this time we will find both call() and
1899 // arg(), and so we will move them out. This will cause them to
1900 // be put into temporary variables before the assignment to err
1901 // but after the declaration of newvar. To avoid that problem,
1902 // we traverse the entire expression here.
1903 Expression::traverse(&init, &find_eval_ordering);
1904 }
1905
1906 if (find_eval_ordering.size() <= 1)
1907 {
1908 // If there is only one expression with a side-effect, we can
1909 // leave it in place.
1910 return TRAVERSE_CONTINUE;
1911 }
1912
1913 bool is_thunk = s->thunk_statement() != NULL;
1914 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1915 p != find_eval_ordering.end();
1916 ++p)
1917 {
1918 Expression** pexpr = *p;
1919
1920 // If the last expression is a send or receive expression, we
1921 // may be ignoring the value; we don't want to evaluate it
1922 // early.
1923 if (p + 1 == find_eval_ordering.end()
1924 && ((*pexpr)->classification() == Expression::EXPRESSION_SEND
1925 || (*pexpr)->classification() == Expression::EXPRESSION_RECEIVE))
1926 break;
1927
1928 // The last expression in a thunk will be the call passed to go
1929 // or defer, which we must not evaluate early.
1930 if (is_thunk && p + 1 == find_eval_ordering.end())
1931 break;
1932
1933 source_location loc = (*pexpr)->location();
1934 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1935 block->insert_statement_before(*pindex, ts);
1936 ++*pindex;
1937
1938 *pexpr = Expression::make_temporary_reference(ts, loc);
1939 }
1940
1941 if (init != orig_init)
1942 vds->var()->var_value()->set_init(init);
1943
1944 return TRAVERSE_CONTINUE;
1945 }
1946
1947 // Implement the order of evaluation rules for the initializer of a
1948 // global variable.
1949
1950 int
1951 Order_eval::variable(Named_object* no)
1952 {
1953 if (no->is_result_variable())
1954 return TRAVERSE_CONTINUE;
1955 Variable* var = no->var_value();
1956 Expression* init = var->init();
1957 if (!var->is_global() || init == NULL)
1958 return TRAVERSE_CONTINUE;
1959
1960 Find_eval_ordering find_eval_ordering;
1961 init->traverse_subexpressions(&find_eval_ordering);
1962
1963 if (find_eval_ordering.size() <= 1)
1964 {
1965 // If there is only one expression with a side-effect, we can
1966 // leave it in place.
1967 return TRAVERSE_SKIP_COMPONENTS;
1968 }
1969
1970 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1971 p != find_eval_ordering.end();
1972 ++p)
1973 {
1974 Expression** pexpr = *p;
1975 source_location loc = (*pexpr)->location();
1976 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1977 var->add_preinit_statement(this->gogo_, ts);
1978 *pexpr = Expression::make_temporary_reference(ts, loc);
1979 }
1980
1981 return TRAVERSE_SKIP_COMPONENTS;
1982 }
1983
1984 // Use temporary variables to implement the order of evaluation rules.
1985
1986 void
1987 Gogo::order_evaluations()
1988 {
1989 Order_eval order_eval(this);
1990 this->traverse(&order_eval);
1991 }
1992
1993 // Traversal to convert calls to the predeclared recover function to
1994 // pass in an argument indicating whether it can recover from a panic
1995 // or not.
1996
1997 class Convert_recover : public Traverse
1998 {
1999 public:
2000 Convert_recover(Named_object* arg)
2001 : Traverse(traverse_expressions),
2002 arg_(arg)
2003 { }
2004
2005 protected:
2006 int
2007 expression(Expression**);
2008
2009 private:
2010 // The argument to pass to the function.
2011 Named_object* arg_;
2012 };
2013
2014 // Convert calls to recover.
2015
2016 int
2017 Convert_recover::expression(Expression** pp)
2018 {
2019 Call_expression* ce = (*pp)->call_expression();
2020 if (ce != NULL && ce->is_recover_call())
2021 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2022 ce->location()));
2023 return TRAVERSE_CONTINUE;
2024 }
2025
2026 // Traversal for build_recover_thunks.
2027
2028 class Build_recover_thunks : public Traverse
2029 {
2030 public:
2031 Build_recover_thunks(Gogo* gogo)
2032 : Traverse(traverse_functions),
2033 gogo_(gogo)
2034 { }
2035
2036 int
2037 function(Named_object*);
2038
2039 private:
2040 Expression*
2041 can_recover_arg(source_location);
2042
2043 // General IR.
2044 Gogo* gogo_;
2045 };
2046
2047 // If this function calls recover, turn it into a thunk.
2048
2049 int
2050 Build_recover_thunks::function(Named_object* orig_no)
2051 {
2052 Function* orig_func = orig_no->func_value();
2053 if (!orig_func->calls_recover()
2054 || orig_func->is_recover_thunk()
2055 || orig_func->has_recover_thunk())
2056 return TRAVERSE_CONTINUE;
2057
2058 Gogo* gogo = this->gogo_;
2059 source_location location = orig_func->location();
2060
2061 static int count;
2062 char buf[50];
2063
2064 Function_type* orig_fntype = orig_func->type();
2065 Typed_identifier_list* new_params = new Typed_identifier_list();
2066 std::string receiver_name;
2067 if (orig_fntype->is_method())
2068 {
2069 const Typed_identifier* receiver = orig_fntype->receiver();
2070 snprintf(buf, sizeof buf, "rt.%u", count);
2071 ++count;
2072 receiver_name = buf;
2073 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2074 receiver->location()));
2075 }
2076 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2077 if (orig_params != NULL && !orig_params->empty())
2078 {
2079 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2080 p != orig_params->end();
2081 ++p)
2082 {
2083 snprintf(buf, sizeof buf, "pt.%u", count);
2084 ++count;
2085 new_params->push_back(Typed_identifier(buf, p->type(),
2086 p->location()));
2087 }
2088 }
2089 snprintf(buf, sizeof buf, "pr.%u", count);
2090 ++count;
2091 std::string can_recover_name = buf;
2092 new_params->push_back(Typed_identifier(can_recover_name,
2093 Type::make_boolean_type(),
2094 orig_fntype->location()));
2095
2096 const Typed_identifier_list* orig_results = orig_fntype->results();
2097 Typed_identifier_list* new_results;
2098 if (orig_results == NULL || orig_results->empty())
2099 new_results = NULL;
2100 else
2101 {
2102 new_results = new Typed_identifier_list();
2103 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2104 p != orig_results->end();
2105 ++p)
2106 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2107 }
2108
2109 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2110 new_results,
2111 orig_fntype->location());
2112 if (orig_fntype->is_varargs())
2113 new_fntype->set_is_varargs();
2114
2115 std::string name = orig_no->name() + "$recover";
2116 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2117 location);
2118 Function *new_func = new_no->func_value();
2119 if (orig_func->enclosing() != NULL)
2120 new_func->set_enclosing(orig_func->enclosing());
2121
2122 // We build the code for the original function attached to the new
2123 // function, and then swap the original and new function bodies.
2124 // This means that existing references to the original function will
2125 // then refer to the new function. That makes this code a little
2126 // confusing, in that the reference to NEW_NO really refers to the
2127 // other function, not the one we are building.
2128
2129 Expression* closure = NULL;
2130 if (orig_func->needs_closure())
2131 {
2132 Named_object* orig_closure_no = orig_func->closure_var();
2133 Variable* orig_closure_var = orig_closure_no->var_value();
2134 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2135 true, false, location);
2136 snprintf(buf, sizeof buf, "closure.%u", count);
2137 ++count;
2138 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2139 new_var);
2140 new_func->set_closure_var(new_closure_no);
2141 closure = Expression::make_var_reference(new_closure_no, location);
2142 }
2143
2144 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2145
2146 Expression_list* args = new Expression_list();
2147 if (new_params != NULL)
2148 {
2149 // Note that we skip the last parameter, which is the boolean
2150 // indicating whether recover can succed.
2151 for (Typed_identifier_list::const_iterator p = new_params->begin();
2152 p + 1 != new_params->end();
2153 ++p)
2154 {
2155 Named_object* p_no = gogo->lookup(p->name(), NULL);
2156 gcc_assert(p_no != NULL
2157 && p_no->is_variable()
2158 && p_no->var_value()->is_parameter());
2159 args->push_back(Expression::make_var_reference(p_no, location));
2160 }
2161 }
2162 args->push_back(this->can_recover_arg(location));
2163
2164 Call_expression* call = Expression::make_call(fn, args, false, location);
2165
2166 Statement* s;
2167 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2168 s = Statement::make_statement(call);
2169 else
2170 {
2171 Expression_list* vals = new Expression_list();
2172 size_t rc = orig_fntype->results()->size();
2173 if (rc == 1)
2174 vals->push_back(call);
2175 else
2176 {
2177 for (size_t i = 0; i < rc; ++i)
2178 vals->push_back(Expression::make_call_result(call, i));
2179 }
2180 s = Statement::make_return_statement(new_func->type()->results(),
2181 vals, location);
2182 }
2183 s->determine_types();
2184 gogo->add_statement(s);
2185
2186 gogo->finish_function(location);
2187
2188 // Swap the function bodies and types.
2189 new_func->swap_for_recover(orig_func);
2190 orig_func->set_is_recover_thunk();
2191 new_func->set_calls_recover();
2192 new_func->set_has_recover_thunk();
2193
2194 Bindings* orig_bindings = orig_func->block()->bindings();
2195 Bindings* new_bindings = new_func->block()->bindings();
2196 if (orig_fntype->is_method())
2197 {
2198 // We changed the receiver to be a regular parameter. We have
2199 // to update the binding accordingly in both functions.
2200 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2201 gcc_assert(orig_rec_no != NULL
2202 && orig_rec_no->is_variable()
2203 && !orig_rec_no->var_value()->is_receiver());
2204 orig_rec_no->var_value()->set_is_receiver();
2205
2206 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2207 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2208 if (new_rec_no == NULL)
2209 gcc_assert(saw_errors());
2210 else
2211 {
2212 gcc_assert(new_rec_no->is_variable()
2213 && new_rec_no->var_value()->is_receiver());
2214 new_rec_no->var_value()->set_is_not_receiver();
2215 }
2216 }
2217
2218 // Because we flipped blocks but not types, the can_recover
2219 // parameter appears in the (now) old bindings as a parameter.
2220 // Change it to a local variable, whereupon it will be discarded.
2221 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2222 gcc_assert(can_recover_no != NULL
2223 && can_recover_no->is_variable()
2224 && can_recover_no->var_value()->is_parameter());
2225 orig_bindings->remove_binding(can_recover_no);
2226
2227 // Add the can_recover argument to the (now) new bindings, and
2228 // attach it to any recover statements.
2229 Variable* can_recover_var = new Variable(Type::make_boolean_type(), NULL,
2230 false, true, false, location);
2231 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2232 can_recover_var);
2233 Convert_recover convert_recover(can_recover_no);
2234 new_func->traverse(&convert_recover);
2235
2236 // Update the function pointers in any named results.
2237 new_func->update_named_result_variables();
2238 orig_func->update_named_result_variables();
2239
2240 return TRAVERSE_CONTINUE;
2241 }
2242
2243 // Return the expression to pass for the .can_recover parameter to the
2244 // new function. This indicates whether a call to recover may return
2245 // non-nil. The expression is
2246 // __go_can_recover(__builtin_return_address()).
2247
2248 Expression*
2249 Build_recover_thunks::can_recover_arg(source_location location)
2250 {
2251 static Named_object* builtin_return_address;
2252 if (builtin_return_address == NULL)
2253 {
2254 const source_location bloc = BUILTINS_LOCATION;
2255
2256 Typed_identifier_list* param_types = new Typed_identifier_list();
2257 Type* uint_type = Type::lookup_integer_type("uint");
2258 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2259
2260 Typed_identifier_list* return_types = new Typed_identifier_list();
2261 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2262 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2263
2264 Function_type* fntype = Type::make_function_type(NULL, param_types,
2265 return_types, bloc);
2266 builtin_return_address =
2267 Named_object::make_function_declaration("__builtin_return_address",
2268 NULL, fntype, bloc);
2269 const char* n = "__builtin_return_address";
2270 builtin_return_address->func_declaration_value()->set_asm_name(n);
2271 }
2272
2273 static Named_object* can_recover;
2274 if (can_recover == NULL)
2275 {
2276 const source_location bloc = BUILTINS_LOCATION;
2277 Typed_identifier_list* param_types = new Typed_identifier_list();
2278 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2279 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2280 Type* boolean_type = Type::make_boolean_type();
2281 Typed_identifier_list* results = new Typed_identifier_list();
2282 results->push_back(Typed_identifier("", boolean_type, bloc));
2283 Function_type* fntype = Type::make_function_type(NULL, param_types,
2284 results, bloc);
2285 can_recover = Named_object::make_function_declaration("__go_can_recover",
2286 NULL, fntype,
2287 bloc);
2288 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2289 }
2290
2291 Expression* fn = Expression::make_func_reference(builtin_return_address,
2292 NULL, location);
2293
2294 mpz_t zval;
2295 mpz_init_set_ui(zval, 0UL);
2296 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2297 mpz_clear(zval);
2298 Expression_list *args = new Expression_list();
2299 args->push_back(zexpr);
2300
2301 Expression* call = Expression::make_call(fn, args, false, location);
2302
2303 args = new Expression_list();
2304 args->push_back(call);
2305
2306 fn = Expression::make_func_reference(can_recover, NULL, location);
2307 return Expression::make_call(fn, args, false, location);
2308 }
2309
2310 // Build thunks for functions which call recover. We build a new
2311 // function with an extra parameter, which is whether a call to
2312 // recover can succeed. We then move the body of this function to
2313 // that one. We then turn this function into a thunk which calls the
2314 // new one, passing the value of
2315 // __go_can_recover(__builtin_return_address()). The function will be
2316 // marked as not splitting the stack. This will cooperate with the
2317 // implementation of defer to make recover do the right thing.
2318
2319 void
2320 Gogo::build_recover_thunks()
2321 {
2322 Build_recover_thunks build_recover_thunks(this);
2323 this->traverse(&build_recover_thunks);
2324 }
2325
2326 // Look for named types to see whether we need to create an interface
2327 // method table.
2328
2329 class Build_method_tables : public Traverse
2330 {
2331 public:
2332 Build_method_tables(Gogo* gogo,
2333 const std::vector<Interface_type*>& interfaces)
2334 : Traverse(traverse_types),
2335 gogo_(gogo), interfaces_(interfaces)
2336 { }
2337
2338 int
2339 type(Type*);
2340
2341 private:
2342 // The IR.
2343 Gogo* gogo_;
2344 // A list of locally defined interfaces which have hidden methods.
2345 const std::vector<Interface_type*>& interfaces_;
2346 };
2347
2348 // Build all required interface method tables for types. We need to
2349 // ensure that we have an interface method table for every interface
2350 // which has a hidden method, for every named type which implements
2351 // that interface. Normally we can just build interface method tables
2352 // as we need them. However, in some cases we can require an
2353 // interface method table for an interface defined in a different
2354 // package for a type defined in that package. If that interface and
2355 // type both use a hidden method, that is OK. However, we will not be
2356 // able to build that interface method table when we need it, because
2357 // the type's hidden method will be static. So we have to build it
2358 // here, and just refer it from other packages as needed.
2359
2360 void
2361 Gogo::build_interface_method_tables()
2362 {
2363 std::vector<Interface_type*> hidden_interfaces;
2364 hidden_interfaces.reserve(this->interface_types_.size());
2365 for (std::vector<Interface_type*>::const_iterator pi =
2366 this->interface_types_.begin();
2367 pi != this->interface_types_.end();
2368 ++pi)
2369 {
2370 const Typed_identifier_list* methods = (*pi)->methods();
2371 if (methods == NULL)
2372 continue;
2373 for (Typed_identifier_list::const_iterator pm = methods->begin();
2374 pm != methods->end();
2375 ++pm)
2376 {
2377 if (Gogo::is_hidden_name(pm->name()))
2378 {
2379 hidden_interfaces.push_back(*pi);
2380 break;
2381 }
2382 }
2383 }
2384
2385 if (!hidden_interfaces.empty())
2386 {
2387 // Now traverse the tree looking for all named types.
2388 Build_method_tables bmt(this, hidden_interfaces);
2389 this->traverse(&bmt);
2390 }
2391
2392 // We no longer need the list of interfaces.
2393
2394 this->interface_types_.clear();
2395 }
2396
2397 // This is called for each type. For a named type, for each of the
2398 // interfaces with hidden methods that it implements, create the
2399 // method table.
2400
2401 int
2402 Build_method_tables::type(Type* type)
2403 {
2404 Named_type* nt = type->named_type();
2405 if (nt != NULL)
2406 {
2407 for (std::vector<Interface_type*>::const_iterator p =
2408 this->interfaces_.begin();
2409 p != this->interfaces_.end();
2410 ++p)
2411 {
2412 // We ask whether a pointer to the named type implements the
2413 // interface, because a pointer can implement more methods
2414 // than a value.
2415 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2416 {
2417 nt->interface_method_table(this->gogo_, *p, false);
2418 nt->interface_method_table(this->gogo_, *p, true);
2419 }
2420 }
2421 }
2422 return TRAVERSE_CONTINUE;
2423 }
2424
2425 // Traversal class used to check for return statements.
2426
2427 class Check_return_statements_traverse : public Traverse
2428 {
2429 public:
2430 Check_return_statements_traverse()
2431 : Traverse(traverse_functions)
2432 { }
2433
2434 int
2435 function(Named_object*);
2436 };
2437
2438 // Check that a function has a return statement if it needs one.
2439
2440 int
2441 Check_return_statements_traverse::function(Named_object* no)
2442 {
2443 Function* func = no->func_value();
2444 const Function_type* fntype = func->type();
2445 const Typed_identifier_list* results = fntype->results();
2446
2447 // We only need a return statement if there is a return value.
2448 if (results == NULL || results->empty())
2449 return TRAVERSE_CONTINUE;
2450
2451 if (func->block()->may_fall_through())
2452 error_at(func->location(), "control reaches end of non-void function");
2453
2454 return TRAVERSE_CONTINUE;
2455 }
2456
2457 // Check return statements.
2458
2459 void
2460 Gogo::check_return_statements()
2461 {
2462 Check_return_statements_traverse traverse;
2463 this->traverse(&traverse);
2464 }
2465
2466 // Get the unique prefix to use before all exported symbols. This
2467 // must be unique across the entire link.
2468
2469 const std::string&
2470 Gogo::unique_prefix() const
2471 {
2472 gcc_assert(!this->unique_prefix_.empty());
2473 return this->unique_prefix_;
2474 }
2475
2476 // Set the unique prefix to use before all exported symbols. This
2477 // comes from the command line option -fgo-prefix=XXX.
2478
2479 void
2480 Gogo::set_unique_prefix(const std::string& arg)
2481 {
2482 gcc_assert(this->unique_prefix_.empty());
2483 this->unique_prefix_ = arg;
2484 this->unique_prefix_specified_ = true;
2485 }
2486
2487 // Work out the package priority. It is one more than the maximum
2488 // priority of an imported package.
2489
2490 int
2491 Gogo::package_priority() const
2492 {
2493 int priority = 0;
2494 for (Packages::const_iterator p = this->packages_.begin();
2495 p != this->packages_.end();
2496 ++p)
2497 if (p->second->priority() > priority)
2498 priority = p->second->priority();
2499 return priority + 1;
2500 }
2501
2502 // Export identifiers as requested.
2503
2504 void
2505 Gogo::do_exports()
2506 {
2507 // For now we always stream to a section. Later we may want to
2508 // support streaming to a separate file.
2509 Stream_to_section stream;
2510
2511 Export exp(&stream);
2512 exp.register_builtin_types(this);
2513 exp.export_globals(this->package_name(),
2514 this->unique_prefix(),
2515 this->package_priority(),
2516 (this->need_init_fn_ && !this->is_main_package()
2517 ? this->get_init_fn_name()
2518 : ""),
2519 this->imported_init_fns_,
2520 this->package_->bindings());
2521 }
2522
2523 // Class Function.
2524
2525 Function::Function(Function_type* type, Function* enclosing, Block* block,
2526 source_location location)
2527 : type_(type), enclosing_(enclosing), named_results_(NULL),
2528 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2529 defer_stack_(NULL), calls_recover_(false), is_recover_thunk_(false),
2530 has_recover_thunk_(false)
2531 {
2532 }
2533
2534 // Create the named result variables.
2535
2536 void
2537 Function::create_named_result_variables(Gogo* gogo)
2538 {
2539 const Typed_identifier_list* results = this->type_->results();
2540 if (results == NULL
2541 || results->empty()
2542 || results->front().name().empty())
2543 return;
2544
2545 this->named_results_ = new Named_results();
2546 this->named_results_->reserve(results->size());
2547
2548 Block* block = this->block_;
2549 int index = 0;
2550 for (Typed_identifier_list::const_iterator p = results->begin();
2551 p != results->end();
2552 ++p, ++index)
2553 {
2554 std::string name = p->name();
2555 if (Gogo::is_sink_name(name))
2556 {
2557 static int unnamed_result_counter;
2558 char buf[100];
2559 snprintf(buf, sizeof buf, "_$%d", unnamed_result_counter);
2560 ++unnamed_result_counter;
2561 name = gogo->pack_hidden_name(buf, false);
2562 }
2563 Result_variable* result = new Result_variable(p->type(), this, index);
2564 Named_object* no = block->bindings()->add_result_variable(name, result);
2565 if (no->is_result_variable())
2566 this->named_results_->push_back(no);
2567 }
2568 }
2569
2570 // Update the named result variables when cloning a function which
2571 // calls recover.
2572
2573 void
2574 Function::update_named_result_variables()
2575 {
2576 if (this->named_results_ == NULL)
2577 return;
2578
2579 for (Named_results::iterator p = this->named_results_->begin();
2580 p != this->named_results_->end();
2581 ++p)
2582 (*p)->result_var_value()->set_function(this);
2583 }
2584
2585 // Return the closure variable, creating it if necessary.
2586
2587 Named_object*
2588 Function::closure_var()
2589 {
2590 if (this->closure_var_ == NULL)
2591 {
2592 // We don't know the type of the variable yet. We add fields as
2593 // we find them.
2594 source_location loc = this->type_->location();
2595 Struct_field_list* sfl = new Struct_field_list;
2596 Type* struct_type = Type::make_struct_type(sfl, loc);
2597 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2598 NULL, false, true, false, loc);
2599 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2600 // Note that the new variable is not in any binding contour.
2601 }
2602 return this->closure_var_;
2603 }
2604
2605 // Set the type of the closure variable.
2606
2607 void
2608 Function::set_closure_type()
2609 {
2610 if (this->closure_var_ == NULL)
2611 return;
2612 Named_object* closure = this->closure_var_;
2613 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2614 unsigned int index = 0;
2615 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2616 p != this->closure_fields_.end();
2617 ++p, ++index)
2618 {
2619 Named_object* no = p->first;
2620 char buf[20];
2621 snprintf(buf, sizeof buf, "%u", index);
2622 std::string n = no->name() + buf;
2623 Type* var_type;
2624 if (no->is_variable())
2625 var_type = no->var_value()->type();
2626 else
2627 var_type = no->result_var_value()->type();
2628 Type* field_type = Type::make_pointer_type(var_type);
2629 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2630 }
2631 }
2632
2633 // Return whether this function is a method.
2634
2635 bool
2636 Function::is_method() const
2637 {
2638 return this->type_->is_method();
2639 }
2640
2641 // Add a label definition.
2642
2643 Label*
2644 Function::add_label_definition(const std::string& label_name,
2645 source_location location)
2646 {
2647 Label* lnull = NULL;
2648 std::pair<Labels::iterator, bool> ins =
2649 this->labels_.insert(std::make_pair(label_name, lnull));
2650 if (ins.second)
2651 {
2652 // This is a new label.
2653 Label* label = new Label(label_name);
2654 label->define(location);
2655 ins.first->second = label;
2656 return label;
2657 }
2658 else
2659 {
2660 // The label was already in the hash table.
2661 Label* label = ins.first->second;
2662 if (!label->is_defined())
2663 {
2664 label->define(location);
2665 return label;
2666 }
2667 else
2668 {
2669 error_at(location, "redefinition of label %qs",
2670 Gogo::message_name(label_name).c_str());
2671 inform(label->location(), "previous definition of %qs was here",
2672 Gogo::message_name(label_name).c_str());
2673 return new Label(label_name);
2674 }
2675 }
2676 }
2677
2678 // Add a reference to a label.
2679
2680 Label*
2681 Function::add_label_reference(const std::string& label_name)
2682 {
2683 Label* lnull = NULL;
2684 std::pair<Labels::iterator, bool> ins =
2685 this->labels_.insert(std::make_pair(label_name, lnull));
2686 if (!ins.second)
2687 {
2688 // The label was already in the hash table.
2689 return ins.first->second;
2690 }
2691 else
2692 {
2693 gcc_assert(ins.first->second == NULL);
2694 Label* label = new Label(label_name);
2695 ins.first->second = label;
2696 return label;
2697 }
2698 }
2699
2700 // Swap one function with another. This is used when building the
2701 // thunk we use to call a function which calls recover. It may not
2702 // work for any other case.
2703
2704 void
2705 Function::swap_for_recover(Function *x)
2706 {
2707 gcc_assert(this->enclosing_ == x->enclosing_);
2708 std::swap(this->named_results_, x->named_results_);
2709 std::swap(this->closure_var_, x->closure_var_);
2710 std::swap(this->block_, x->block_);
2711 gcc_assert(this->location_ == x->location_);
2712 gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2713 gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2714 }
2715
2716 // Traverse the tree.
2717
2718 int
2719 Function::traverse(Traverse* traverse)
2720 {
2721 unsigned int traverse_mask = traverse->traverse_mask();
2722
2723 if ((traverse_mask
2724 & (Traverse::traverse_types | Traverse::traverse_expressions))
2725 != 0)
2726 {
2727 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2728 return TRAVERSE_EXIT;
2729 }
2730
2731 // FIXME: We should check traverse_functions here if nested
2732 // functions are stored in block bindings.
2733 if (this->block_ != NULL
2734 && (traverse_mask
2735 & (Traverse::traverse_variables
2736 | Traverse::traverse_constants
2737 | Traverse::traverse_blocks
2738 | Traverse::traverse_statements
2739 | Traverse::traverse_expressions
2740 | Traverse::traverse_types)) != 0)
2741 {
2742 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2743 return TRAVERSE_EXIT;
2744 }
2745
2746 return TRAVERSE_CONTINUE;
2747 }
2748
2749 // Work out types for unspecified variables and constants.
2750
2751 void
2752 Function::determine_types()
2753 {
2754 if (this->block_ != NULL)
2755 this->block_->determine_types();
2756 }
2757
2758 // Export the function.
2759
2760 void
2761 Function::export_func(Export* exp, const std::string& name) const
2762 {
2763 Function::export_func_with_type(exp, name, this->type_);
2764 }
2765
2766 // Export a function with a type.
2767
2768 void
2769 Function::export_func_with_type(Export* exp, const std::string& name,
2770 const Function_type* fntype)
2771 {
2772 exp->write_c_string("func ");
2773
2774 if (fntype->is_method())
2775 {
2776 exp->write_c_string("(");
2777 exp->write_type(fntype->receiver()->type());
2778 exp->write_c_string(") ");
2779 }
2780
2781 exp->write_string(name);
2782
2783 exp->write_c_string(" (");
2784 const Typed_identifier_list* parameters = fntype->parameters();
2785 if (parameters != NULL)
2786 {
2787 bool is_varargs = fntype->is_varargs();
2788 bool first = true;
2789 for (Typed_identifier_list::const_iterator p = parameters->begin();
2790 p != parameters->end();
2791 ++p)
2792 {
2793 if (first)
2794 first = false;
2795 else
2796 exp->write_c_string(", ");
2797 if (!is_varargs || p + 1 != parameters->end())
2798 exp->write_type(p->type());
2799 else
2800 {
2801 exp->write_c_string("...");
2802 exp->write_type(p->type()->array_type()->element_type());
2803 }
2804 }
2805 }
2806 exp->write_c_string(")");
2807
2808 const Typed_identifier_list* results = fntype->results();
2809 if (results != NULL)
2810 {
2811 if (results->size() == 1)
2812 {
2813 exp->write_c_string(" ");
2814 exp->write_type(results->begin()->type());
2815 }
2816 else
2817 {
2818 exp->write_c_string(" (");
2819 bool first = true;
2820 for (Typed_identifier_list::const_iterator p = results->begin();
2821 p != results->end();
2822 ++p)
2823 {
2824 if (first)
2825 first = false;
2826 else
2827 exp->write_c_string(", ");
2828 exp->write_type(p->type());
2829 }
2830 exp->write_c_string(")");
2831 }
2832 }
2833 exp->write_c_string(";\n");
2834 }
2835
2836 // Import a function.
2837
2838 void
2839 Function::import_func(Import* imp, std::string* pname,
2840 Typed_identifier** preceiver,
2841 Typed_identifier_list** pparameters,
2842 Typed_identifier_list** presults,
2843 bool* is_varargs)
2844 {
2845 imp->require_c_string("func ");
2846
2847 *preceiver = NULL;
2848 if (imp->peek_char() == '(')
2849 {
2850 imp->require_c_string("(");
2851 Type* rtype = imp->read_type();
2852 *preceiver = new Typed_identifier(Import::import_marker, rtype,
2853 imp->location());
2854 imp->require_c_string(") ");
2855 }
2856
2857 *pname = imp->read_identifier();
2858
2859 Typed_identifier_list* parameters;
2860 *is_varargs = false;
2861 imp->require_c_string(" (");
2862 if (imp->peek_char() == ')')
2863 parameters = NULL;
2864 else
2865 {
2866 parameters = new Typed_identifier_list();
2867 while (true)
2868 {
2869 if (imp->match_c_string("..."))
2870 {
2871 imp->advance(3);
2872 *is_varargs = true;
2873 }
2874
2875 Type* ptype = imp->read_type();
2876 if (*is_varargs)
2877 ptype = Type::make_array_type(ptype, NULL);
2878 parameters->push_back(Typed_identifier(Import::import_marker,
2879 ptype, imp->location()));
2880 if (imp->peek_char() != ',')
2881 break;
2882 gcc_assert(!*is_varargs);
2883 imp->require_c_string(", ");
2884 }
2885 }
2886 imp->require_c_string(")");
2887 *pparameters = parameters;
2888
2889 Typed_identifier_list* results;
2890 if (imp->peek_char() != ' ')
2891 results = NULL;
2892 else
2893 {
2894 results = new Typed_identifier_list();
2895 imp->require_c_string(" ");
2896 if (imp->peek_char() != '(')
2897 {
2898 Type* rtype = imp->read_type();
2899 results->push_back(Typed_identifier(Import::import_marker, rtype,
2900 imp->location()));
2901 }
2902 else
2903 {
2904 imp->require_c_string("(");
2905 while (true)
2906 {
2907 Type* rtype = imp->read_type();
2908 results->push_back(Typed_identifier(Import::import_marker,
2909 rtype, imp->location()));
2910 if (imp->peek_char() != ',')
2911 break;
2912 imp->require_c_string(", ");
2913 }
2914 imp->require_c_string(")");
2915 }
2916 }
2917 imp->require_c_string(";\n");
2918 *presults = results;
2919 }
2920
2921 // Class Block.
2922
2923 Block::Block(Block* enclosing, source_location location)
2924 : enclosing_(enclosing), statements_(),
2925 bindings_(new Bindings(enclosing == NULL
2926 ? NULL
2927 : enclosing->bindings())),
2928 start_location_(location),
2929 end_location_(UNKNOWN_LOCATION)
2930 {
2931 }
2932
2933 // Add a statement to a block.
2934
2935 void
2936 Block::add_statement(Statement* statement)
2937 {
2938 this->statements_.push_back(statement);
2939 }
2940
2941 // Add a statement to the front of a block. This is slow but is only
2942 // used for reference counts of parameters.
2943
2944 void
2945 Block::add_statement_at_front(Statement* statement)
2946 {
2947 this->statements_.insert(this->statements_.begin(), statement);
2948 }
2949
2950 // Replace a statement in a block.
2951
2952 void
2953 Block::replace_statement(size_t index, Statement* s)
2954 {
2955 gcc_assert(index < this->statements_.size());
2956 this->statements_[index] = s;
2957 }
2958
2959 // Add a statement before another statement.
2960
2961 void
2962 Block::insert_statement_before(size_t index, Statement* s)
2963 {
2964 gcc_assert(index < this->statements_.size());
2965 this->statements_.insert(this->statements_.begin() + index, s);
2966 }
2967
2968 // Add a statement after another statement.
2969
2970 void
2971 Block::insert_statement_after(size_t index, Statement* s)
2972 {
2973 gcc_assert(index < this->statements_.size());
2974 this->statements_.insert(this->statements_.begin() + index + 1, s);
2975 }
2976
2977 // Traverse the tree.
2978
2979 int
2980 Block::traverse(Traverse* traverse)
2981 {
2982 unsigned int traverse_mask = traverse->traverse_mask();
2983
2984 if ((traverse_mask & Traverse::traverse_blocks) != 0)
2985 {
2986 int t = traverse->block(this);
2987 if (t == TRAVERSE_EXIT)
2988 return TRAVERSE_EXIT;
2989 else if (t == TRAVERSE_SKIP_COMPONENTS)
2990 return TRAVERSE_CONTINUE;
2991 }
2992
2993 if ((traverse_mask
2994 & (Traverse::traverse_variables
2995 | Traverse::traverse_constants
2996 | Traverse::traverse_expressions
2997 | Traverse::traverse_types)) != 0)
2998 {
2999 for (Bindings::const_definitions_iterator pb =
3000 this->bindings_->begin_definitions();
3001 pb != this->bindings_->end_definitions();
3002 ++pb)
3003 {
3004 switch ((*pb)->classification())
3005 {
3006 case Named_object::NAMED_OBJECT_CONST:
3007 if ((traverse_mask & Traverse::traverse_constants) != 0)
3008 {
3009 if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
3010 return TRAVERSE_EXIT;
3011 }
3012 if ((traverse_mask & Traverse::traverse_types) != 0
3013 || (traverse_mask & Traverse::traverse_expressions) != 0)
3014 {
3015 Type* t = (*pb)->const_value()->type();
3016 if (t != NULL
3017 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3018 return TRAVERSE_EXIT;
3019 }
3020 if ((traverse_mask & Traverse::traverse_expressions) != 0
3021 || (traverse_mask & Traverse::traverse_types) != 0)
3022 {
3023 if ((*pb)->const_value()->traverse_expression(traverse)
3024 == TRAVERSE_EXIT)
3025 return TRAVERSE_EXIT;
3026 }
3027 break;
3028
3029 case Named_object::NAMED_OBJECT_VAR:
3030 case Named_object::NAMED_OBJECT_RESULT_VAR:
3031 if ((traverse_mask & Traverse::traverse_variables) != 0)
3032 {
3033 if (traverse->variable(*pb) == TRAVERSE_EXIT)
3034 return TRAVERSE_EXIT;
3035 }
3036 if (((traverse_mask & Traverse::traverse_types) != 0
3037 || (traverse_mask & Traverse::traverse_expressions) != 0)
3038 && ((*pb)->is_result_variable()
3039 || (*pb)->var_value()->has_type()))
3040 {
3041 Type* t = ((*pb)->is_variable()
3042 ? (*pb)->var_value()->type()
3043 : (*pb)->result_var_value()->type());
3044 if (t != NULL
3045 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3046 return TRAVERSE_EXIT;
3047 }
3048 if ((*pb)->is_variable()
3049 && ((traverse_mask & Traverse::traverse_expressions) != 0
3050 || (traverse_mask & Traverse::traverse_types) != 0))
3051 {
3052 if ((*pb)->var_value()->traverse_expression(traverse)
3053 == TRAVERSE_EXIT)
3054 return TRAVERSE_EXIT;
3055 }
3056 break;
3057
3058 case Named_object::NAMED_OBJECT_FUNC:
3059 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3060 // FIXME: Where will nested functions be found?
3061 gcc_unreachable();
3062
3063 case Named_object::NAMED_OBJECT_TYPE:
3064 if ((traverse_mask & Traverse::traverse_types) != 0
3065 || (traverse_mask & Traverse::traverse_expressions) != 0)
3066 {
3067 if (Type::traverse((*pb)->type_value(), traverse)
3068 == TRAVERSE_EXIT)
3069 return TRAVERSE_EXIT;
3070 }
3071 break;
3072
3073 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3074 case Named_object::NAMED_OBJECT_UNKNOWN:
3075 break;
3076
3077 case Named_object::NAMED_OBJECT_PACKAGE:
3078 case Named_object::NAMED_OBJECT_SINK:
3079 gcc_unreachable();
3080
3081 default:
3082 gcc_unreachable();
3083 }
3084 }
3085 }
3086
3087 // No point in checking traverse_mask here--if we got here we always
3088 // want to walk the statements. The traversal can insert new
3089 // statements before or after the current statement. Inserting
3090 // statements before the current statement requires updating I via
3091 // the pointer; those statements will not be traversed. Any new
3092 // statements inserted after the current statement will be traversed
3093 // in their turn.
3094 for (size_t i = 0; i < this->statements_.size(); ++i)
3095 {
3096 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3097 return TRAVERSE_EXIT;
3098 }
3099
3100 return TRAVERSE_CONTINUE;
3101 }
3102
3103 // Work out types for unspecified variables and constants.
3104
3105 void
3106 Block::determine_types()
3107 {
3108 for (Bindings::const_definitions_iterator pb =
3109 this->bindings_->begin_definitions();
3110 pb != this->bindings_->end_definitions();
3111 ++pb)
3112 {
3113 if ((*pb)->is_variable())
3114 (*pb)->var_value()->determine_type();
3115 else if ((*pb)->is_const())
3116 (*pb)->const_value()->determine_type();
3117 }
3118
3119 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3120 ps != this->statements_.end();
3121 ++ps)
3122 (*ps)->determine_types();
3123 }
3124
3125 // Return true if the statements in this block may fall through.
3126
3127 bool
3128 Block::may_fall_through() const
3129 {
3130 if (this->statements_.empty())
3131 return true;
3132 return this->statements_.back()->may_fall_through();
3133 }
3134
3135 // Class Variable.
3136
3137 Variable::Variable(Type* type, Expression* init, bool is_global,
3138 bool is_parameter, bool is_receiver,
3139 source_location location)
3140 : type_(type), init_(init), preinit_(NULL), location_(location),
3141 is_global_(is_global), is_parameter_(is_parameter),
3142 is_receiver_(is_receiver), is_varargs_parameter_(false),
3143 is_address_taken_(false), seen_(false), init_is_lowered_(false),
3144 type_from_init_tuple_(false), type_from_range_index_(false),
3145 type_from_range_value_(false), type_from_chan_element_(false),
3146 is_type_switch_var_(false)
3147 {
3148 gcc_assert(type != NULL || init != NULL);
3149 gcc_assert(!is_parameter || init == NULL);
3150 }
3151
3152 // Traverse the initializer expression.
3153
3154 int
3155 Variable::traverse_expression(Traverse* traverse)
3156 {
3157 if (this->preinit_ != NULL)
3158 {
3159 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3160 return TRAVERSE_EXIT;
3161 }
3162 if (this->init_ != NULL)
3163 {
3164 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3165 return TRAVERSE_EXIT;
3166 }
3167 return TRAVERSE_CONTINUE;
3168 }
3169
3170 // Lower the initialization expression after parsing is complete.
3171
3172 void
3173 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3174 {
3175 if (this->init_ != NULL && !this->init_is_lowered_)
3176 {
3177 if (this->seen_)
3178 {
3179 // We will give an error elsewhere, this is just to prevent
3180 // an infinite loop.
3181 return;
3182 }
3183 this->seen_ = true;
3184
3185 gogo->lower_expression(function, &this->init_);
3186
3187 this->seen_ = false;
3188
3189 this->init_is_lowered_ = true;
3190 }
3191 }
3192
3193 // Get the preinit block.
3194
3195 Block*
3196 Variable::preinit_block(Gogo* gogo)
3197 {
3198 gcc_assert(this->is_global_);
3199 if (this->preinit_ == NULL)
3200 this->preinit_ = new Block(NULL, this->location());
3201
3202 // If a global variable has a preinitialization statement, then we
3203 // need to have an initialization function.
3204 gogo->set_need_init_fn();
3205
3206 return this->preinit_;
3207 }
3208
3209 // Add a statement to be run before the initialization expression.
3210
3211 void
3212 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3213 {
3214 Block* b = this->preinit_block(gogo);
3215 b->add_statement(s);
3216 b->set_end_location(s->location());
3217 }
3218
3219 // In an assignment which sets a variable to a tuple of EXPR, return
3220 // the type of the first element of the tuple.
3221
3222 Type*
3223 Variable::type_from_tuple(Expression* expr, bool report_error) const
3224 {
3225 if (expr->map_index_expression() != NULL)
3226 {
3227 Map_type* mt = expr->map_index_expression()->get_map_type();
3228 if (mt == NULL)
3229 return Type::make_error_type();
3230 return mt->val_type();
3231 }
3232 else if (expr->receive_expression() != NULL)
3233 {
3234 Expression* channel = expr->receive_expression()->channel();
3235 Type* channel_type = channel->type();
3236 if (channel_type->channel_type() == NULL)
3237 return Type::make_error_type();
3238 return channel_type->channel_type()->element_type();
3239 }
3240 else
3241 {
3242 if (report_error)
3243 error_at(this->location(), "invalid tuple definition");
3244 return Type::make_error_type();
3245 }
3246 }
3247
3248 // Given EXPR used in a range clause, return either the index type or
3249 // the value type of the range, depending upon GET_INDEX_TYPE.
3250
3251 Type*
3252 Variable::type_from_range(Expression* expr, bool get_index_type,
3253 bool report_error) const
3254 {
3255 Type* t = expr->type();
3256 if (t->array_type() != NULL
3257 || (t->points_to() != NULL
3258 && t->points_to()->array_type() != NULL
3259 && !t->points_to()->is_open_array_type()))
3260 {
3261 if (get_index_type)
3262 return Type::lookup_integer_type("int");
3263 else
3264 return t->deref()->array_type()->element_type();
3265 }
3266 else if (t->is_string_type())
3267 return Type::lookup_integer_type("int");
3268 else if (t->map_type() != NULL)
3269 {
3270 if (get_index_type)
3271 return t->map_type()->key_type();
3272 else
3273 return t->map_type()->val_type();
3274 }
3275 else if (t->channel_type() != NULL)
3276 {
3277 if (get_index_type)
3278 return t->channel_type()->element_type();
3279 else
3280 {
3281 if (report_error)
3282 error_at(this->location(),
3283 "invalid definition of value variable for channel range");
3284 return Type::make_error_type();
3285 }
3286 }
3287 else
3288 {
3289 if (report_error)
3290 error_at(this->location(), "invalid type for range clause");
3291 return Type::make_error_type();
3292 }
3293 }
3294
3295 // EXPR should be a channel. Return the channel's element type.
3296
3297 Type*
3298 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3299 {
3300 Type* t = expr->type();
3301 if (t->channel_type() != NULL)
3302 return t->channel_type()->element_type();
3303 else
3304 {
3305 if (report_error)
3306 error_at(this->location(), "expected channel");
3307 return Type::make_error_type();
3308 }
3309 }
3310
3311 // Return the type of the Variable. This may be called before
3312 // Variable::determine_type is called, which means that we may need to
3313 // get the type from the initializer. FIXME: If we combine lowering
3314 // with type determination, then this should be unnecessary.
3315
3316 Type*
3317 Variable::type()
3318 {
3319 // A variable in a type switch with a nil case will have the wrong
3320 // type here. This gets fixed up in determine_type, below.
3321 Type* type = this->type_;
3322 Expression* init = this->init_;
3323 if (this->is_type_switch_var_
3324 && this->type_->is_nil_constant_as_type())
3325 {
3326 Type_guard_expression* tge = this->init_->type_guard_expression();
3327 gcc_assert(tge != NULL);
3328 init = tge->expr();
3329 type = NULL;
3330 }
3331
3332 if (this->seen_)
3333 {
3334 if (this->type_ == NULL || !this->type_->is_error_type())
3335 {
3336 error_at(this->location_, "variable initializer refers to itself");
3337 this->type_ = Type::make_error_type();
3338 }
3339 return this->type_;
3340 }
3341
3342 this->seen_ = true;
3343
3344 if (type != NULL)
3345 ;
3346 else if (this->type_from_init_tuple_)
3347 type = this->type_from_tuple(init, false);
3348 else if (this->type_from_range_index_ || this->type_from_range_value_)
3349 type = this->type_from_range(init, this->type_from_range_index_, false);
3350 else if (this->type_from_chan_element_)
3351 type = this->type_from_chan_element(init, false);
3352 else
3353 {
3354 gcc_assert(init != NULL);
3355 type = init->type();
3356 gcc_assert(type != NULL);
3357
3358 // Variables should not have abstract types.
3359 if (type->is_abstract())
3360 type = type->make_non_abstract_type();
3361
3362 if (type->is_void_type())
3363 type = Type::make_error_type();
3364 }
3365
3366 this->seen_ = false;
3367
3368 return type;
3369 }
3370
3371 // Fetch the type from a const pointer, in which case it should have
3372 // been set already.
3373
3374 Type*
3375 Variable::type() const
3376 {
3377 gcc_assert(this->type_ != NULL);
3378 return this->type_;
3379 }
3380
3381 // Set the type if necessary.
3382
3383 void
3384 Variable::determine_type()
3385 {
3386 if (this->preinit_ != NULL)
3387 this->preinit_->determine_types();
3388
3389 // A variable in a type switch with a nil case will have the wrong
3390 // type here. It will have an initializer which is a type guard.
3391 // We want to initialize it to the value without the type guard, and
3392 // use the type of that value as well.
3393 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3394 {
3395 Type_guard_expression* tge = this->init_->type_guard_expression();
3396 gcc_assert(tge != NULL);
3397 this->type_ = NULL;
3398 this->init_ = tge->expr();
3399 }
3400
3401 if (this->init_ == NULL)
3402 gcc_assert(this->type_ != NULL && !this->type_->is_abstract());
3403 else if (this->type_from_init_tuple_)
3404 {
3405 Expression *init = this->init_;
3406 init->determine_type_no_context();
3407 this->type_ = this->type_from_tuple(init, true);
3408 this->init_ = NULL;
3409 }
3410 else if (this->type_from_range_index_ || this->type_from_range_value_)
3411 {
3412 Expression* init = this->init_;
3413 init->determine_type_no_context();
3414 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3415 true);
3416 this->init_ = NULL;
3417 }
3418 else
3419 {
3420 // type_from_chan_element_ should have been cleared during
3421 // lowering.
3422 gcc_assert(!this->type_from_chan_element_);
3423
3424 Type_context context(this->type_, false);
3425 this->init_->determine_type(&context);
3426 if (this->type_ == NULL)
3427 {
3428 Type* type = this->init_->type();
3429 gcc_assert(type != NULL);
3430 if (type->is_abstract())
3431 type = type->make_non_abstract_type();
3432
3433 if (type->is_void_type())
3434 {
3435 error_at(this->location_, "variable has no type");
3436 type = Type::make_error_type();
3437 }
3438 else if (type->is_nil_type())
3439 {
3440 error_at(this->location_, "variable defined to nil type");
3441 type = Type::make_error_type();
3442 }
3443 else if (type->is_call_multiple_result_type())
3444 {
3445 error_at(this->location_,
3446 "single variable set to multiple value function call");
3447 type = Type::make_error_type();
3448 }
3449
3450 this->type_ = type;
3451 }
3452 }
3453 }
3454
3455 // Export the variable
3456
3457 void
3458 Variable::export_var(Export* exp, const std::string& name) const
3459 {
3460 gcc_assert(this->is_global_);
3461 exp->write_c_string("var ");
3462 exp->write_string(name);
3463 exp->write_c_string(" ");
3464 exp->write_type(this->type());
3465 exp->write_c_string(";\n");
3466 }
3467
3468 // Import a variable.
3469
3470 void
3471 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3472 {
3473 imp->require_c_string("var ");
3474 *pname = imp->read_identifier();
3475 imp->require_c_string(" ");
3476 *ptype = imp->read_type();
3477 imp->require_c_string(";\n");
3478 }
3479
3480 // Class Named_constant.
3481
3482 // Traverse the initializer expression.
3483
3484 int
3485 Named_constant::traverse_expression(Traverse* traverse)
3486 {
3487 return Expression::traverse(&this->expr_, traverse);
3488 }
3489
3490 // Determine the type of the constant.
3491
3492 void
3493 Named_constant::determine_type()
3494 {
3495 if (this->type_ != NULL)
3496 {
3497 Type_context context(this->type_, false);
3498 this->expr_->determine_type(&context);
3499 }
3500 else
3501 {
3502 // A constant may have an abstract type.
3503 Type_context context(NULL, true);
3504 this->expr_->determine_type(&context);
3505 this->type_ = this->expr_->type();
3506 gcc_assert(this->type_ != NULL);
3507 }
3508 }
3509
3510 // Indicate that we found and reported an error for this constant.
3511
3512 void
3513 Named_constant::set_error()
3514 {
3515 this->type_ = Type::make_error_type();
3516 this->expr_ = Expression::make_error(this->location_);
3517 }
3518
3519 // Export a constant.
3520
3521 void
3522 Named_constant::export_const(Export* exp, const std::string& name) const
3523 {
3524 exp->write_c_string("const ");
3525 exp->write_string(name);
3526 exp->write_c_string(" ");
3527 if (!this->type_->is_abstract())
3528 {
3529 exp->write_type(this->type_);
3530 exp->write_c_string(" ");
3531 }
3532 exp->write_c_string("= ");
3533 this->expr()->export_expression(exp);
3534 exp->write_c_string(";\n");
3535 }
3536
3537 // Import a constant.
3538
3539 void
3540 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3541 Expression** pexpr)
3542 {
3543 imp->require_c_string("const ");
3544 *pname = imp->read_identifier();
3545 imp->require_c_string(" ");
3546 if (imp->peek_char() == '=')
3547 *ptype = NULL;
3548 else
3549 {
3550 *ptype = imp->read_type();
3551 imp->require_c_string(" ");
3552 }
3553 imp->require_c_string("= ");
3554 *pexpr = Expression::import_expression(imp);
3555 imp->require_c_string(";\n");
3556 }
3557
3558 // Add a method.
3559
3560 Named_object*
3561 Type_declaration::add_method(const std::string& name, Function* function)
3562 {
3563 Named_object* ret = Named_object::make_function(name, NULL, function);
3564 this->methods_.push_back(ret);
3565 return ret;
3566 }
3567
3568 // Add a method declaration.
3569
3570 Named_object*
3571 Type_declaration::add_method_declaration(const std::string& name,
3572 Function_type* type,
3573 source_location location)
3574 {
3575 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3576 location);
3577 this->methods_.push_back(ret);
3578 return ret;
3579 }
3580
3581 // Return whether any methods ere defined.
3582
3583 bool
3584 Type_declaration::has_methods() const
3585 {
3586 return !this->methods_.empty();
3587 }
3588
3589 // Define methods for the real type.
3590
3591 void
3592 Type_declaration::define_methods(Named_type* nt)
3593 {
3594 for (Methods::const_iterator p = this->methods_.begin();
3595 p != this->methods_.end();
3596 ++p)
3597 nt->add_existing_method(*p);
3598 }
3599
3600 // We are using the type. Return true if we should issue a warning.
3601
3602 bool
3603 Type_declaration::using_type()
3604 {
3605 bool ret = !this->issued_warning_;
3606 this->issued_warning_ = true;
3607 return ret;
3608 }
3609
3610 // Class Unknown_name.
3611
3612 // Set the real named object.
3613
3614 void
3615 Unknown_name::set_real_named_object(Named_object* no)
3616 {
3617 gcc_assert(this->real_named_object_ == NULL);
3618 gcc_assert(!no->is_unknown());
3619 this->real_named_object_ = no;
3620 }
3621
3622 // Class Named_object.
3623
3624 Named_object::Named_object(const std::string& name,
3625 const Package* package,
3626 Classification classification)
3627 : name_(name), package_(package), classification_(classification),
3628 tree_(NULL)
3629 {
3630 if (Gogo::is_sink_name(name))
3631 gcc_assert(classification == NAMED_OBJECT_SINK);
3632 }
3633
3634 // Make an unknown name. This is used by the parser. The name must
3635 // be resolved later. Unknown names are only added in the current
3636 // package.
3637
3638 Named_object*
3639 Named_object::make_unknown_name(const std::string& name,
3640 source_location location)
3641 {
3642 Named_object* named_object = new Named_object(name, NULL,
3643 NAMED_OBJECT_UNKNOWN);
3644 Unknown_name* value = new Unknown_name(location);
3645 named_object->u_.unknown_value = value;
3646 return named_object;
3647 }
3648
3649 // Make a constant.
3650
3651 Named_object*
3652 Named_object::make_constant(const Typed_identifier& tid,
3653 const Package* package, Expression* expr,
3654 int iota_value)
3655 {
3656 Named_object* named_object = new Named_object(tid.name(), package,
3657 NAMED_OBJECT_CONST);
3658 Named_constant* named_constant = new Named_constant(tid.type(), expr,
3659 iota_value,
3660 tid.location());
3661 named_object->u_.const_value = named_constant;
3662 return named_object;
3663 }
3664
3665 // Make a named type.
3666
3667 Named_object*
3668 Named_object::make_type(const std::string& name, const Package* package,
3669 Type* type, source_location location)
3670 {
3671 Named_object* named_object = new Named_object(name, package,
3672 NAMED_OBJECT_TYPE);
3673 Named_type* named_type = Type::make_named_type(named_object, type, location);
3674 named_object->u_.type_value = named_type;
3675 return named_object;
3676 }
3677
3678 // Make a type declaration.
3679
3680 Named_object*
3681 Named_object::make_type_declaration(const std::string& name,
3682 const Package* package,
3683 source_location location)
3684 {
3685 Named_object* named_object = new Named_object(name, package,
3686 NAMED_OBJECT_TYPE_DECLARATION);
3687 Type_declaration* type_declaration = new Type_declaration(location);
3688 named_object->u_.type_declaration = type_declaration;
3689 return named_object;
3690 }
3691
3692 // Make a variable.
3693
3694 Named_object*
3695 Named_object::make_variable(const std::string& name, const Package* package,
3696 Variable* variable)
3697 {
3698 Named_object* named_object = new Named_object(name, package,
3699 NAMED_OBJECT_VAR);
3700 named_object->u_.var_value = variable;
3701 return named_object;
3702 }
3703
3704 // Make a result variable.
3705
3706 Named_object*
3707 Named_object::make_result_variable(const std::string& name,
3708 Result_variable* result)
3709 {
3710 Named_object* named_object = new Named_object(name, NULL,
3711 NAMED_OBJECT_RESULT_VAR);
3712 named_object->u_.result_var_value = result;
3713 return named_object;
3714 }
3715
3716 // Make a sink. This is used for the special blank identifier _.
3717
3718 Named_object*
3719 Named_object::make_sink()
3720 {
3721 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
3722 }
3723
3724 // Make a named function.
3725
3726 Named_object*
3727 Named_object::make_function(const std::string& name, const Package* package,
3728 Function* function)
3729 {
3730 Named_object* named_object = new Named_object(name, package,
3731 NAMED_OBJECT_FUNC);
3732 named_object->u_.func_value = function;
3733 return named_object;
3734 }
3735
3736 // Make a function declaration.
3737
3738 Named_object*
3739 Named_object::make_function_declaration(const std::string& name,
3740 const Package* package,
3741 Function_type* fntype,
3742 source_location location)
3743 {
3744 Named_object* named_object = new Named_object(name, package,
3745 NAMED_OBJECT_FUNC_DECLARATION);
3746 Function_declaration *func_decl = new Function_declaration(fntype, location);
3747 named_object->u_.func_declaration_value = func_decl;
3748 return named_object;
3749 }
3750
3751 // Make a package.
3752
3753 Named_object*
3754 Named_object::make_package(const std::string& alias, Package* package)
3755 {
3756 Named_object* named_object = new Named_object(alias, NULL,
3757 NAMED_OBJECT_PACKAGE);
3758 named_object->u_.package_value = package;
3759 return named_object;
3760 }
3761
3762 // Return the name to use in an error message.
3763
3764 std::string
3765 Named_object::message_name() const
3766 {
3767 if (this->package_ == NULL)
3768 return Gogo::message_name(this->name_);
3769 std::string ret = Gogo::message_name(this->package_->name());
3770 ret += '.';
3771 ret += Gogo::message_name(this->name_);
3772 return ret;
3773 }
3774
3775 // Set the type when a declaration is defined.
3776
3777 void
3778 Named_object::set_type_value(Named_type* named_type)
3779 {
3780 gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
3781 Type_declaration* td = this->u_.type_declaration;
3782 td->define_methods(named_type);
3783 Named_object* in_function = td->in_function();
3784 if (in_function != NULL)
3785 named_type->set_in_function(in_function);
3786 delete td;
3787 this->classification_ = NAMED_OBJECT_TYPE;
3788 this->u_.type_value = named_type;
3789 }
3790
3791 // Define a function which was previously declared.
3792
3793 void
3794 Named_object::set_function_value(Function* function)
3795 {
3796 gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
3797 this->classification_ = NAMED_OBJECT_FUNC;
3798 // FIXME: We should free the old value.
3799 this->u_.func_value = function;
3800 }
3801
3802 // Declare an unknown object as a type declaration.
3803
3804 void
3805 Named_object::declare_as_type()
3806 {
3807 gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
3808 Unknown_name* unk = this->u_.unknown_value;
3809 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
3810 this->u_.type_declaration = new Type_declaration(unk->location());
3811 delete unk;
3812 }
3813
3814 // Return the location of a named object.
3815
3816 source_location
3817 Named_object::location() const
3818 {
3819 switch (this->classification_)
3820 {
3821 default:
3822 case NAMED_OBJECT_UNINITIALIZED:
3823 gcc_unreachable();
3824
3825 case NAMED_OBJECT_UNKNOWN:
3826 return this->unknown_value()->location();
3827
3828 case NAMED_OBJECT_CONST:
3829 return this->const_value()->location();
3830
3831 case NAMED_OBJECT_TYPE:
3832 return this->type_value()->location();
3833
3834 case NAMED_OBJECT_TYPE_DECLARATION:
3835 return this->type_declaration_value()->location();
3836
3837 case NAMED_OBJECT_VAR:
3838 return this->var_value()->location();
3839
3840 case NAMED_OBJECT_RESULT_VAR:
3841 return this->result_var_value()->function()->location();
3842
3843 case NAMED_OBJECT_SINK:
3844 gcc_unreachable();
3845
3846 case NAMED_OBJECT_FUNC:
3847 return this->func_value()->location();
3848
3849 case NAMED_OBJECT_FUNC_DECLARATION:
3850 return this->func_declaration_value()->location();
3851
3852 case NAMED_OBJECT_PACKAGE:
3853 return this->package_value()->location();
3854 }
3855 }
3856
3857 // Export a named object.
3858
3859 void
3860 Named_object::export_named_object(Export* exp) const
3861 {
3862 switch (this->classification_)
3863 {
3864 default:
3865 case NAMED_OBJECT_UNINITIALIZED:
3866 case NAMED_OBJECT_UNKNOWN:
3867 gcc_unreachable();
3868
3869 case NAMED_OBJECT_CONST:
3870 this->const_value()->export_const(exp, this->name_);
3871 break;
3872
3873 case NAMED_OBJECT_TYPE:
3874 this->type_value()->export_named_type(exp, this->name_);
3875 break;
3876
3877 case NAMED_OBJECT_TYPE_DECLARATION:
3878 error_at(this->type_declaration_value()->location(),
3879 "attempt to export %<%s%> which was declared but not defined",
3880 this->message_name().c_str());
3881 break;
3882
3883 case NAMED_OBJECT_FUNC_DECLARATION:
3884 this->func_declaration_value()->export_func(exp, this->name_);
3885 break;
3886
3887 case NAMED_OBJECT_VAR:
3888 this->var_value()->export_var(exp, this->name_);
3889 break;
3890
3891 case NAMED_OBJECT_RESULT_VAR:
3892 case NAMED_OBJECT_SINK:
3893 gcc_unreachable();
3894
3895 case NAMED_OBJECT_FUNC:
3896 this->func_value()->export_func(exp, this->name_);
3897 break;
3898 }
3899 }
3900
3901 // Class Bindings.
3902
3903 Bindings::Bindings(Bindings* enclosing)
3904 : enclosing_(enclosing), named_objects_(), bindings_()
3905 {
3906 }
3907
3908 // Clear imports.
3909
3910 void
3911 Bindings::clear_file_scope()
3912 {
3913 Contour::iterator p = this->bindings_.begin();
3914 while (p != this->bindings_.end())
3915 {
3916 bool keep;
3917 if (p->second->package() != NULL)
3918 keep = false;
3919 else if (p->second->is_package())
3920 keep = false;
3921 else if (p->second->is_function()
3922 && !p->second->func_value()->type()->is_method()
3923 && Gogo::unpack_hidden_name(p->second->name()) == "init")
3924 keep = false;
3925 else
3926 keep = true;
3927
3928 if (keep)
3929 ++p;
3930 else
3931 p = this->bindings_.erase(p);
3932 }
3933 }
3934
3935 // Look up a symbol.
3936
3937 Named_object*
3938 Bindings::lookup(const std::string& name) const
3939 {
3940 Contour::const_iterator p = this->bindings_.find(name);
3941 if (p != this->bindings_.end())
3942 return p->second->resolve();
3943 else if (this->enclosing_ != NULL)
3944 return this->enclosing_->lookup(name);
3945 else
3946 return NULL;
3947 }
3948
3949 // Look up a symbol locally.
3950
3951 Named_object*
3952 Bindings::lookup_local(const std::string& name) const
3953 {
3954 Contour::const_iterator p = this->bindings_.find(name);
3955 if (p == this->bindings_.end())
3956 return NULL;
3957 return p->second;
3958 }
3959
3960 // Remove an object from a set of bindings. This is used for a
3961 // special case in thunks for functions which call recover.
3962
3963 void
3964 Bindings::remove_binding(Named_object* no)
3965 {
3966 Contour::iterator pb = this->bindings_.find(no->name());
3967 gcc_assert(pb != this->bindings_.end());
3968 this->bindings_.erase(pb);
3969 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
3970 pn != this->named_objects_.end();
3971 ++pn)
3972 {
3973 if (*pn == no)
3974 {
3975 this->named_objects_.erase(pn);
3976 return;
3977 }
3978 }
3979 gcc_unreachable();
3980 }
3981
3982 // Add a method to the list of objects. This is not added to the
3983 // lookup table. This is so that we have a single list of objects
3984 // declared at the top level, which we walk through when it's time to
3985 // convert to trees.
3986
3987 void
3988 Bindings::add_method(Named_object* method)
3989 {
3990 this->named_objects_.push_back(method);
3991 }
3992
3993 // Add a generic Named_object to a Contour.
3994
3995 Named_object*
3996 Bindings::add_named_object_to_contour(Contour* contour,
3997 Named_object* named_object)
3998 {
3999 gcc_assert(named_object == named_object->resolve());
4000 const std::string& name(named_object->name());
4001 gcc_assert(!Gogo::is_sink_name(name));
4002
4003 std::pair<Contour::iterator, bool> ins =
4004 contour->insert(std::make_pair(name, named_object));
4005 if (!ins.second)
4006 {
4007 // The name was already there.
4008 if (named_object->package() != NULL
4009 && ins.first->second->package() == named_object->package()
4010 && (ins.first->second->classification()
4011 == named_object->classification()))
4012 {
4013 // This is a second import of the same object.
4014 return ins.first->second;
4015 }
4016 ins.first->second = this->new_definition(ins.first->second,
4017 named_object);
4018 return ins.first->second;
4019 }
4020 else
4021 {
4022 // Don't push declarations on the list. We push them on when
4023 // and if we find the definitions. That way we genericize the
4024 // functions in order.
4025 if (!named_object->is_type_declaration()
4026 && !named_object->is_function_declaration()
4027 && !named_object->is_unknown())
4028 this->named_objects_.push_back(named_object);
4029 return named_object;
4030 }
4031 }
4032
4033 // We had an existing named object OLD_OBJECT, and we've seen a new
4034 // one NEW_OBJECT with the same name. FIXME: This does not free the
4035 // new object when we don't need it.
4036
4037 Named_object*
4038 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4039 {
4040 std::string reason;
4041 switch (old_object->classification())
4042 {
4043 default:
4044 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4045 gcc_unreachable();
4046
4047 case Named_object::NAMED_OBJECT_UNKNOWN:
4048 {
4049 Named_object* real = old_object->unknown_value()->real_named_object();
4050 if (real != NULL)
4051 return this->new_definition(real, new_object);
4052 gcc_assert(!new_object->is_unknown());
4053 old_object->unknown_value()->set_real_named_object(new_object);
4054 if (!new_object->is_type_declaration()
4055 && !new_object->is_function_declaration())
4056 this->named_objects_.push_back(new_object);
4057 return new_object;
4058 }
4059
4060 case Named_object::NAMED_OBJECT_CONST:
4061 break;
4062
4063 case Named_object::NAMED_OBJECT_TYPE:
4064 if (new_object->is_type_declaration())
4065 return old_object;
4066 break;
4067
4068 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4069 if (new_object->is_type_declaration())
4070 return old_object;
4071 if (new_object->is_type())
4072 {
4073 old_object->set_type_value(new_object->type_value());
4074 new_object->type_value()->set_named_object(old_object);
4075 this->named_objects_.push_back(old_object);
4076 return old_object;
4077 }
4078 break;
4079
4080 case Named_object::NAMED_OBJECT_VAR:
4081 case Named_object::NAMED_OBJECT_RESULT_VAR:
4082 break;
4083
4084 case Named_object::NAMED_OBJECT_SINK:
4085 gcc_unreachable();
4086
4087 case Named_object::NAMED_OBJECT_FUNC:
4088 if (new_object->is_function_declaration())
4089 {
4090 if (!new_object->func_declaration_value()->asm_name().empty())
4091 sorry("__asm__ for function definitions");
4092 Function_type* old_type = old_object->func_value()->type();
4093 Function_type* new_type =
4094 new_object->func_declaration_value()->type();
4095 if (old_type->is_valid_redeclaration(new_type, &reason))
4096 return old_object;
4097 }
4098 break;
4099
4100 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4101 {
4102 Function_type* old_type = old_object->func_declaration_value()->type();
4103 if (new_object->is_function_declaration())
4104 {
4105 Function_type* new_type =
4106 new_object->func_declaration_value()->type();
4107 if (old_type->is_valid_redeclaration(new_type, &reason))
4108 return old_object;
4109 }
4110 if (new_object->is_function())
4111 {
4112 Function_type* new_type = new_object->func_value()->type();
4113 if (old_type->is_valid_redeclaration(new_type, &reason))
4114 {
4115 if (!old_object->func_declaration_value()->asm_name().empty())
4116 sorry("__asm__ for function definitions");
4117 old_object->set_function_value(new_object->func_value());
4118 this->named_objects_.push_back(old_object);
4119 return old_object;
4120 }
4121 }
4122 }
4123 break;
4124
4125 case Named_object::NAMED_OBJECT_PACKAGE:
4126 if (new_object->is_package()
4127 && (old_object->package_value()->name()
4128 == new_object->package_value()->name()))
4129 return old_object;
4130
4131 break;
4132 }
4133
4134 std::string n = old_object->message_name();
4135 if (reason.empty())
4136 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4137 else
4138 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4139 reason.c_str());
4140
4141 inform(old_object->location(), "previous definition of %qs was here",
4142 n.c_str());
4143
4144 return old_object;
4145 }
4146
4147 // Add a named type.
4148
4149 Named_object*
4150 Bindings::add_named_type(Named_type* named_type)
4151 {
4152 return this->add_named_object(named_type->named_object());
4153 }
4154
4155 // Add a function.
4156
4157 Named_object*
4158 Bindings::add_function(const std::string& name, const Package* package,
4159 Function* function)
4160 {
4161 return this->add_named_object(Named_object::make_function(name, package,
4162 function));
4163 }
4164
4165 // Add a function declaration.
4166
4167 Named_object*
4168 Bindings::add_function_declaration(const std::string& name,
4169 const Package* package,
4170 Function_type* type,
4171 source_location location)
4172 {
4173 Named_object* no = Named_object::make_function_declaration(name, package,
4174 type, location);
4175 return this->add_named_object(no);
4176 }
4177
4178 // Define a type which was previously declared.
4179
4180 void
4181 Bindings::define_type(Named_object* no, Named_type* type)
4182 {
4183 no->set_type_value(type);
4184 this->named_objects_.push_back(no);
4185 }
4186
4187 // Traverse bindings.
4188
4189 int
4190 Bindings::traverse(Traverse* traverse, bool is_global)
4191 {
4192 unsigned int traverse_mask = traverse->traverse_mask();
4193
4194 // We don't use an iterator because we permit the traversal to add
4195 // new global objects.
4196 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4197 {
4198 Named_object* p = this->named_objects_[i];
4199 switch (p->classification())
4200 {
4201 case Named_object::NAMED_OBJECT_CONST:
4202 if ((traverse_mask & Traverse::traverse_constants) != 0)
4203 {
4204 if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4205 return TRAVERSE_EXIT;
4206 }
4207 if ((traverse_mask & Traverse::traverse_types) != 0
4208 || (traverse_mask & Traverse::traverse_expressions) != 0)
4209 {
4210 Type* t = p->const_value()->type();
4211 if (t != NULL
4212 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4213 return TRAVERSE_EXIT;
4214 if (p->const_value()->traverse_expression(traverse)
4215 == TRAVERSE_EXIT)
4216 return TRAVERSE_EXIT;
4217 }
4218 break;
4219
4220 case Named_object::NAMED_OBJECT_VAR:
4221 case Named_object::NAMED_OBJECT_RESULT_VAR:
4222 if ((traverse_mask & Traverse::traverse_variables) != 0)
4223 {
4224 if (traverse->variable(p) == TRAVERSE_EXIT)
4225 return TRAVERSE_EXIT;
4226 }
4227 if (((traverse_mask & Traverse::traverse_types) != 0
4228 || (traverse_mask & Traverse::traverse_expressions) != 0)
4229 && (p->is_result_variable()
4230 || p->var_value()->has_type()))
4231 {
4232 Type* t = (p->is_variable()
4233 ? p->var_value()->type()
4234 : p->result_var_value()->type());
4235 if (t != NULL
4236 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4237 return TRAVERSE_EXIT;
4238 }
4239 if (p->is_variable()
4240 && ((traverse_mask & Traverse::traverse_types) != 0
4241 || (traverse_mask & Traverse::traverse_expressions) != 0))
4242 {
4243 if (p->var_value()->traverse_expression(traverse)
4244 == TRAVERSE_EXIT)
4245 return TRAVERSE_EXIT;
4246 }
4247 break;
4248
4249 case Named_object::NAMED_OBJECT_FUNC:
4250 if ((traverse_mask & Traverse::traverse_functions) != 0)
4251 {
4252 int t = traverse->function(p);
4253 if (t == TRAVERSE_EXIT)
4254 return TRAVERSE_EXIT;
4255 else if (t == TRAVERSE_SKIP_COMPONENTS)
4256 break;
4257 }
4258
4259 if ((traverse_mask
4260 & (Traverse::traverse_variables
4261 | Traverse::traverse_constants
4262 | Traverse::traverse_functions
4263 | Traverse::traverse_blocks
4264 | Traverse::traverse_statements
4265 | Traverse::traverse_expressions
4266 | Traverse::traverse_types)) != 0)
4267 {
4268 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4269 return TRAVERSE_EXIT;
4270 }
4271 break;
4272
4273 case Named_object::NAMED_OBJECT_PACKAGE:
4274 // These are traversed in Gogo::traverse.
4275 gcc_assert(is_global);
4276 break;
4277
4278 case Named_object::NAMED_OBJECT_TYPE:
4279 if ((traverse_mask & Traverse::traverse_types) != 0
4280 || (traverse_mask & Traverse::traverse_expressions) != 0)
4281 {
4282 if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4283 return TRAVERSE_EXIT;
4284 }
4285 break;
4286
4287 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4288 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4289 case Named_object::NAMED_OBJECT_UNKNOWN:
4290 break;
4291
4292 case Named_object::NAMED_OBJECT_SINK:
4293 default:
4294 gcc_unreachable();
4295 }
4296 }
4297
4298 return TRAVERSE_CONTINUE;
4299 }
4300
4301 // Class Package.
4302
4303 Package::Package(const std::string& name, const std::string& unique_prefix,
4304 source_location location)
4305 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4306 priority_(0), location_(location), used_(false), is_imported_(false),
4307 uses_sink_alias_(false)
4308 {
4309 gcc_assert(!name.empty() && !unique_prefix.empty());
4310 }
4311
4312 // Set the priority. We may see multiple priorities for an imported
4313 // package; we want to use the largest one.
4314
4315 void
4316 Package::set_priority(int priority)
4317 {
4318 if (priority > this->priority_)
4319 this->priority_ = priority;
4320 }
4321
4322 // Determine types of constants. Everything else in a package
4323 // (variables, function declarations) should already have a fixed
4324 // type. Constants may have abstract types.
4325
4326 void
4327 Package::determine_types()
4328 {
4329 Bindings* bindings = this->bindings_;
4330 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4331 p != bindings->end_definitions();
4332 ++p)
4333 {
4334 if ((*p)->is_const())
4335 (*p)->const_value()->determine_type();
4336 }
4337 }
4338
4339 // Class Traverse.
4340
4341 // Destructor.
4342
4343 Traverse::~Traverse()
4344 {
4345 if (this->types_seen_ != NULL)
4346 delete this->types_seen_;
4347 if (this->expressions_seen_ != NULL)
4348 delete this->expressions_seen_;
4349 }
4350
4351 // Record that we are looking at a type, and return true if we have
4352 // already seen it.
4353
4354 bool
4355 Traverse::remember_type(const Type* type)
4356 {
4357 if (type->is_error_type())
4358 return true;
4359 gcc_assert((this->traverse_mask() & traverse_types) != 0
4360 || (this->traverse_mask() & traverse_expressions) != 0);
4361 // We only have to remember named types, as they are the only ones
4362 // we can see multiple times in a traversal.
4363 if (type->classification() != Type::TYPE_NAMED)
4364 return false;
4365 if (this->types_seen_ == NULL)
4366 this->types_seen_ = new Types_seen();
4367 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4368 return !ins.second;
4369 }
4370
4371 // Record that we are looking at an expression, and return true if we
4372 // have already seen it.
4373
4374 bool
4375 Traverse::remember_expression(const Expression* expression)
4376 {
4377 gcc_assert((this->traverse_mask() & traverse_types) != 0
4378 || (this->traverse_mask() & traverse_expressions) != 0);
4379 if (this->expressions_seen_ == NULL)
4380 this->expressions_seen_ = new Expressions_seen();
4381 std::pair<Expressions_seen::iterator, bool> ins =
4382 this->expressions_seen_->insert(expression);
4383 return !ins.second;
4384 }
4385
4386 // The default versions of these functions should never be called: the
4387 // traversal mask indicates which functions may be called.
4388
4389 int
4390 Traverse::variable(Named_object*)
4391 {
4392 gcc_unreachable();
4393 }
4394
4395 int
4396 Traverse::constant(Named_object*, bool)
4397 {
4398 gcc_unreachable();
4399 }
4400
4401 int
4402 Traverse::function(Named_object*)
4403 {
4404 gcc_unreachable();
4405 }
4406
4407 int
4408 Traverse::block(Block*)
4409 {
4410 gcc_unreachable();
4411 }
4412
4413 int
4414 Traverse::statement(Block*, size_t*, Statement*)
4415 {
4416 gcc_unreachable();
4417 }
4418
4419 int
4420 Traverse::expression(Expression**)
4421 {
4422 gcc_unreachable();
4423 }
4424
4425 int
4426 Traverse::type(Type*)
4427 {
4428 gcc_unreachable();
4429 }