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