1 // gogo-tree.cc -- convert Go frontend Gogo IR to gcc trees.
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.
11 #ifndef ENABLE_BUILD_WITH_CXX
19 #include "tree-iterator.h"
21 #include "langhooks.h"
24 #include "diagnostic.h"
26 #ifndef ENABLE_BUILD_WITH_CXX
32 #include "expressions.h"
33 #include "statements.h"
38 // Whether we have seen any errors.
43 return errorcount != 0 || sorrycount != 0;
49 get_identifier_from_string(const std::string& str)
51 return get_identifier_with_length(str.data(), str.length());
56 static std::map<std::string, tree> builtin_functions;
58 // Define a builtin function. BCODE is the builtin function code
59 // defined by builtins.def. NAME is the name of the builtin function.
60 // LIBNAME is the name of the corresponding library function, and is
61 // NULL if there isn't one. FNTYPE is the type of the function.
62 // CONST_P is true if the function has the const attribute.
65 define_builtin(built_in_function bcode, const char* name, const char* libname,
66 tree fntype, bool const_p)
68 tree decl = add_builtin_function(name, fntype, bcode, BUILT_IN_NORMAL,
71 TREE_READONLY(decl) = 1;
72 set_builtin_decl(bcode, decl, true);
73 builtin_functions[name] = decl;
76 decl = add_builtin_function(libname, fntype, bcode, BUILT_IN_NORMAL,
79 TREE_READONLY(decl) = 1;
80 builtin_functions[libname] = decl;
84 // Create trees for implicit builtin functions.
87 Gogo::define_builtin_function_trees()
89 /* We need to define the fetch_and_add functions, since we use them
91 tree t = go_type_for_size(BITS_PER_UNIT, 1);
92 tree p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
93 define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_1, "__sync_fetch_and_add_1", NULL,
94 build_function_type_list(t, p, t, NULL_TREE), false);
96 t = go_type_for_size(BITS_PER_UNIT * 2, 1);
97 p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
98 define_builtin (BUILT_IN_SYNC_ADD_AND_FETCH_2, "__sync_fetch_and_add_2", NULL,
99 build_function_type_list(t, p, t, NULL_TREE), false);
101 t = go_type_for_size(BITS_PER_UNIT * 4, 1);
102 p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
103 define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_4, "__sync_fetch_and_add_4", NULL,
104 build_function_type_list(t, p, t, NULL_TREE), false);
106 t = go_type_for_size(BITS_PER_UNIT * 8, 1);
107 p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
108 define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_8, "__sync_fetch_and_add_8", NULL,
109 build_function_type_list(t, p, t, NULL_TREE), false);
111 // We use __builtin_expect for magic import functions.
112 define_builtin(BUILT_IN_EXPECT, "__builtin_expect", NULL,
113 build_function_type_list(long_integer_type_node,
114 long_integer_type_node,
115 long_integer_type_node,
119 // We use __builtin_memmove for the predeclared copy function.
120 define_builtin(BUILT_IN_MEMMOVE, "__builtin_memmove", "memmove",
121 build_function_type_list(ptr_type_node,
128 // We provide sqrt for the math library.
129 define_builtin(BUILT_IN_SQRT, "__builtin_sqrt", "sqrt",
130 build_function_type_list(double_type_node,
134 define_builtin(BUILT_IN_SQRTL, "__builtin_sqrtl", "sqrtl",
135 build_function_type_list(long_double_type_node,
136 long_double_type_node,
140 // We use __builtin_return_address in the thunk we build for
141 // functions which call recover.
142 define_builtin(BUILT_IN_RETURN_ADDRESS, "__builtin_return_address", NULL,
143 build_function_type_list(ptr_type_node,
148 // The compiler uses __builtin_trap for some exception handling
150 define_builtin(BUILT_IN_TRAP, "__builtin_trap", NULL,
151 build_function_type(void_type_node, void_list_node),
155 // Get the name to use for the import control function. If there is a
156 // global function or variable, then we know that that name must be
157 // unique in the link, and we use it as the basis for our name.
160 Gogo::get_init_fn_name()
162 if (this->init_fn_name_.empty())
164 go_assert(this->package_ != NULL);
165 if (this->is_main_package())
167 // Use a name which the runtime knows.
168 this->init_fn_name_ = "__go_init_main";
172 std::string s = this->unique_prefix();
174 s.append(this->package_name());
175 s.append("..import");
176 this->init_fn_name_ = s;
180 return this->init_fn_name_;
183 // Add statements to INIT_STMT_LIST which run the initialization
184 // functions for imported packages. This is only used for the "main"
188 Gogo::init_imports(tree* init_stmt_list)
190 go_assert(this->is_main_package());
192 if (this->imported_init_fns_.empty())
195 tree fntype = build_function_type(void_type_node, void_list_node);
197 // We must call them in increasing priority order.
198 std::vector<Import_init> v;
199 for (std::set<Import_init>::const_iterator p =
200 this->imported_init_fns_.begin();
201 p != this->imported_init_fns_.end();
204 std::sort(v.begin(), v.end());
206 for (std::vector<Import_init>::const_iterator p = v.begin();
210 std::string user_name = p->package_name() + ".init";
211 tree decl = build_decl(UNKNOWN_LOCATION, FUNCTION_DECL,
212 get_identifier_from_string(user_name),
214 const std::string& init_name(p->init_name());
215 SET_DECL_ASSEMBLER_NAME(decl, get_identifier_from_string(init_name));
216 TREE_PUBLIC(decl) = 1;
217 DECL_EXTERNAL(decl) = 1;
218 append_to_statement_list(build_call_expr(decl, 0), init_stmt_list);
222 // Register global variables with the garbage collector. We need to
223 // register all variables which can hold a pointer value. They become
224 // roots during the mark phase. We build a struct that is easy to
225 // hook into a list of roots.
227 // struct __go_gc_root_list
229 // struct __go_gc_root_list* __next;
230 // struct __go_gc_root
237 // The last entry in the roots array has a NULL decl field.
240 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
241 tree* init_stmt_list)
246 size_t count = var_gc.size();
248 tree root_type = Gogo::builtin_struct(NULL, "__go_gc_root", NULL_TREE, 2,
254 tree index_type = build_index_type(size_int(count));
255 tree array_type = build_array_type(root_type, index_type);
257 tree root_list_type = make_node(RECORD_TYPE);
258 root_list_type = Gogo::builtin_struct(NULL, "__go_gc_root_list",
261 build_pointer_type(root_list_type),
265 // Build an initialier for the __roots array.
267 VEC(constructor_elt,gc)* roots_init = VEC_alloc(constructor_elt, gc,
271 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
275 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
277 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
278 tree field = TYPE_FIELDS(root_type);
280 Bvariable* bvar = (*p)->get_backend_variable(this, NULL);
281 tree decl = var_to_tree(bvar);
282 go_assert(TREE_CODE(decl) == VAR_DECL);
283 elt->value = build_fold_addr_expr(decl);
285 elt = VEC_quick_push(constructor_elt, init, NULL);
286 field = DECL_CHAIN(field);
288 elt->value = DECL_SIZE_UNIT(decl);
290 elt = VEC_quick_push(constructor_elt, roots_init, NULL);
291 elt->index = size_int(i);
292 elt->value = build_constructor(root_type, init);
295 // The list ends with a NULL entry.
297 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
299 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
300 tree field = TYPE_FIELDS(root_type);
302 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
304 elt = VEC_quick_push(constructor_elt, init, NULL);
305 field = DECL_CHAIN(field);
307 elt->value = size_zero_node;
309 elt = VEC_quick_push(constructor_elt, roots_init, NULL);
310 elt->index = size_int(i);
311 elt->value = build_constructor(root_type, init);
313 // Build a constructor for the struct.
315 VEC(constructor_elt,gc*) root_list_init = VEC_alloc(constructor_elt, gc, 2);
317 elt = VEC_quick_push(constructor_elt, root_list_init, NULL);
318 field = TYPE_FIELDS(root_list_type);
320 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
322 elt = VEC_quick_push(constructor_elt, root_list_init, NULL);
323 field = DECL_CHAIN(field);
325 elt->value = build_constructor(array_type, roots_init);
327 // Build a decl to register.
329 tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL,
330 create_tmp_var_name("gc"), root_list_type);
331 DECL_EXTERNAL(decl) = 0;
332 TREE_PUBLIC(decl) = 0;
333 TREE_STATIC(decl) = 1;
334 DECL_ARTIFICIAL(decl) = 1;
335 DECL_INITIAL(decl) = build_constructor(root_list_type, root_list_init);
336 rest_of_decl_compilation(decl, 1, 0);
338 static tree register_gc_fndecl;
339 tree call = Gogo::call_builtin(®ister_gc_fndecl, BUILTINS_LOCATION,
340 "__go_register_gc_roots",
343 build_pointer_type(root_list_type),
344 build_fold_addr_expr(decl));
345 if (call != error_mark_node)
346 append_to_statement_list(call, init_stmt_list);
349 // Build the decl for the initialization function.
352 Gogo::initialization_function_decl()
354 // The tedious details of building your own function. There doesn't
355 // seem to be a helper function for this.
356 std::string name = this->package_name() + ".init";
357 tree fndecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL,
358 get_identifier_from_string(name),
359 build_function_type(void_type_node,
361 const std::string& asm_name(this->get_init_fn_name());
362 SET_DECL_ASSEMBLER_NAME(fndecl, get_identifier_from_string(asm_name));
364 tree resdecl = build_decl(BUILTINS_LOCATION, RESULT_DECL, NULL_TREE,
366 DECL_ARTIFICIAL(resdecl) = 1;
367 DECL_CONTEXT(resdecl) = fndecl;
368 DECL_RESULT(fndecl) = resdecl;
370 TREE_STATIC(fndecl) = 1;
371 TREE_USED(fndecl) = 1;
372 DECL_ARTIFICIAL(fndecl) = 1;
373 TREE_PUBLIC(fndecl) = 1;
375 DECL_INITIAL(fndecl) = make_node(BLOCK);
376 TREE_USED(DECL_INITIAL(fndecl)) = 1;
381 // Create the magic initialization function. INIT_STMT_LIST is the
382 // code that it needs to run.
385 Gogo::write_initialization_function(tree fndecl, tree init_stmt_list)
387 // Make sure that we thought we needed an initialization function,
388 // as otherwise we will not have reported it in the export data.
389 go_assert(this->is_main_package() || this->need_init_fn_);
391 if (fndecl == NULL_TREE)
392 fndecl = this->initialization_function_decl();
394 DECL_SAVED_TREE(fndecl) = init_stmt_list;
396 current_function_decl = fndecl;
397 if (DECL_STRUCT_FUNCTION(fndecl) == NULL)
398 push_struct_function(fndecl);
400 push_cfun(DECL_STRUCT_FUNCTION(fndecl));
401 cfun->function_end_locus = BUILTINS_LOCATION;
403 gimplify_function_tree(fndecl);
405 cgraph_add_new_function(fndecl, false);
406 cgraph_mark_needed_node(cgraph_get_node(fndecl));
408 current_function_decl = NULL_TREE;
412 // Search for references to VAR in any statements or called functions.
414 class Find_var : public Traverse
417 // A hash table we use to avoid looping. The index is the name of a
418 // named object. We only look through objects defined in this
420 typedef Unordered_set(std::string) Seen_objects;
422 Find_var(Named_object* var, Seen_objects* seen_objects)
423 : Traverse(traverse_expressions),
424 var_(var), seen_objects_(seen_objects), found_(false)
427 // Whether the variable was found.
430 { return this->found_; }
433 expression(Expression**);
436 // The variable we are looking for.
438 // Names of objects we have already seen.
439 Seen_objects* seen_objects_;
440 // True if the variable was found.
444 // See if EXPR refers to VAR, looking through function calls and
445 // variable initializations.
448 Find_var::expression(Expression** pexpr)
450 Expression* e = *pexpr;
452 Var_expression* ve = e->var_expression();
455 Named_object* v = ve->named_object();
459 return TRAVERSE_EXIT;
462 if (v->is_variable() && v->package() == NULL)
464 Expression* init = v->var_value()->init();
467 std::pair<Seen_objects::iterator, bool> ins =
468 this->seen_objects_->insert(v->name());
471 // This is the first time we have seen this name.
472 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
473 return TRAVERSE_EXIT;
479 // We traverse the code of any function we see. Note that this
480 // means that we will traverse the code of a function whose address
481 // is taken even if it is not called.
482 Func_expression* fe = e->func_expression();
485 const Named_object* f = fe->named_object();
486 if (f->is_function() && f->package() == NULL)
488 std::pair<Seen_objects::iterator, bool> ins =
489 this->seen_objects_->insert(f->name());
492 // This is the first time we have seen this name.
493 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
494 return TRAVERSE_EXIT;
499 return TRAVERSE_CONTINUE;
502 // Return true if EXPR refers to VAR.
505 expression_requires(Expression* expr, Block* preinit, Named_object* var)
507 Find_var::Seen_objects seen_objects;
508 Find_var find_var(var, &seen_objects);
510 Expression::traverse(&expr, &find_var);
512 preinit->traverse(&find_var);
514 return find_var.found();
517 // Sort variable initializations. If the initialization expression
518 // for variable A refers directly or indirectly to the initialization
519 // expression for variable B, then we must initialize B before A.
525 : var_(NULL), init_(NULL_TREE), waiting_(0)
528 Var_init(Named_object* var, tree init)
529 : var_(var), init_(init), waiting_(0)
532 // Return the variable.
535 { return this->var_; }
537 // Return the initialization expression.
540 { return this->init_; }
542 // Return the number of variables waiting for this one to be
546 { return this->waiting_; }
548 // Increment the number waiting.
551 { ++this->waiting_; }
554 // The variable being initialized.
556 // The initialization expression to run.
558 // The number of variables which are waiting for this one.
562 typedef std::list<Var_init> Var_inits;
564 // Sort the variable initializations. The rule we follow is that we
565 // emit them in the order they appear in the array, except that if the
566 // initialization expression for a variable V1 depends upon another
567 // variable V2 then we initialize V1 after V2.
570 sort_var_inits(Var_inits* var_inits)
573 while (!var_inits->empty())
575 Var_inits::iterator p1 = var_inits->begin();
576 Named_object* var = p1->var();
577 Expression* init = var->var_value()->init();
578 Block* preinit = var->var_value()->preinit();
580 // Start walking through the list to see which variables VAR
581 // needs to wait for. We can skip P1->WAITING variables--that
582 // is the number we've already checked.
583 Var_inits::iterator p2 = p1;
585 for (size_t i = p1->waiting(); i > 0; --i)
588 for (; p2 != var_inits->end(); ++p2)
590 if (expression_requires(init, preinit, p2->var()))
593 if (expression_requires(p2->var()->var_value()->init(),
594 p2->var()->var_value()->preinit(),
597 error_at(var->location(),
598 ("initialization expressions for %qs and "
599 "%qs depend upon each other"),
600 var->message_name().c_str(),
601 p2->var()->message_name().c_str());
602 inform(p2->var()->location(), "%qs defined here",
603 p2->var()->message_name().c_str());
604 p2 = var_inits->end();
608 // We can't emit P1 until P2 is emitted. Move P1.
609 // Note that the WAITING loop always executes at
610 // least once, which is what we want.
611 p2->increment_waiting();
612 Var_inits::iterator p3 = p2;
613 for (size_t i = p2->waiting(); i > 0; --i)
615 var_inits->splice(p3, *var_inits, p1);
621 if (p2 == var_inits->end())
623 // VAR does not depends upon any other initialization expressions.
625 // Check for a loop of VAR on itself. We only do this if
626 // INIT is not NULL; when INIT is NULL, it means that
627 // PREINIT sets VAR, which we will interpret as a loop.
628 if (init != NULL && expression_requires(init, preinit, var))
629 error_at(var->location(),
630 "initialization expression for %qs depends upon itself",
631 var->message_name().c_str());
632 ready.splice(ready.end(), *var_inits, p1);
636 // Now READY is the list in the desired initialization order.
637 var_inits->swap(ready);
640 // Write out the global definitions.
643 Gogo::write_globals()
645 this->convert_named_types();
646 this->build_interface_method_tables();
648 Bindings* bindings = this->current_bindings();
649 size_t count = bindings->size_definitions();
651 tree* vec = new tree[count];
653 tree init_fndecl = NULL_TREE;
654 tree init_stmt_list = NULL_TREE;
656 if (this->is_main_package())
657 this->init_imports(&init_stmt_list);
659 // A list of variable initializations.
662 // A list of variables which need to be registered with the garbage
664 std::vector<Named_object*> var_gc;
665 var_gc.reserve(count);
667 tree var_init_stmt_list = NULL_TREE;
669 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
670 p != bindings->end_definitions();
673 Named_object* no = *p;
675 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
676 // There is nothing to do for a package.
677 if (no->is_package())
684 // There is nothing to do for an object which was imported from
685 // a different package into the global scope.
686 if (no->package() != NULL)
693 // There is nothing useful we can output for constants which
694 // have ideal or non-integeral type.
697 Type* type = no->const_value()->type();
699 type = no->const_value()->expr()->type();
700 if (type->is_abstract() || type->integer_type() == NULL)
708 if (!no->is_variable())
710 vec[i] = no->get_tree(this, NULL);
711 if (vec[i] == error_mark_node)
713 go_assert(saw_errors());
721 Bvariable* var = no->get_backend_variable(this, NULL);
722 vec[i] = var_to_tree(var);
723 if (vec[i] == error_mark_node)
725 go_assert(saw_errors());
731 // Check for a sink variable, which may be used to run an
732 // initializer purely for its side effects.
733 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
735 tree var_init_tree = NULL_TREE;
736 if (!no->var_value()->has_pre_init())
738 tree init = no->var_value()->get_init_tree(this, NULL);
739 if (init == error_mark_node)
740 go_assert(saw_errors());
741 else if (init == NULL_TREE)
743 else if (TREE_CONSTANT(init))
744 this->backend()->global_variable_set_init(var,
747 var_init_tree = init;
749 var_init_tree = fold_build2_loc(no->location(), MODIFY_EXPR,
750 void_type_node, vec[i], init);
754 // We are going to create temporary variables which
755 // means that we need an fndecl.
756 if (init_fndecl == NULL_TREE)
757 init_fndecl = this->initialization_function_decl();
758 current_function_decl = init_fndecl;
759 if (DECL_STRUCT_FUNCTION(init_fndecl) == NULL)
760 push_struct_function(init_fndecl);
762 push_cfun(DECL_STRUCT_FUNCTION(init_fndecl));
764 tree var_decl = is_sink ? NULL_TREE : vec[i];
765 var_init_tree = no->var_value()->get_init_block(this, NULL,
768 current_function_decl = NULL_TREE;
772 if (var_init_tree != NULL_TREE && var_init_tree != error_mark_node)
774 if (no->var_value()->init() == NULL
775 && !no->var_value()->has_pre_init())
776 append_to_statement_list(var_init_tree, &var_init_stmt_list);
778 var_inits.push_back(Var_init(no, var_init_tree));
781 if (!is_sink && no->var_value()->type()->has_pointer())
782 var_gc.push_back(no);
786 // Register global variables with the garbage collector.
787 this->register_gc_vars(var_gc, &init_stmt_list);
789 // Simple variable initializations, after all variables are
791 append_to_statement_list(var_init_stmt_list, &init_stmt_list);
793 // Complex variable initializations, first sorting them into a
795 if (!var_inits.empty())
797 sort_var_inits(&var_inits);
798 for (Var_inits::const_iterator p = var_inits.begin();
799 p != var_inits.end();
801 append_to_statement_list(p->init(), &init_stmt_list);
804 // After all the variables are initialized, call the "init"
805 // functions if there are any.
806 for (std::vector<Named_object*>::const_iterator p =
807 this->init_functions_.begin();
808 p != this->init_functions_.end();
811 tree decl = (*p)->get_tree(this, NULL);
812 tree call = build_call_expr(decl, 0);
813 append_to_statement_list(call, &init_stmt_list);
816 // Set up a magic function to do all the initialization actions.
817 // This will be called if this package is imported.
818 if (init_stmt_list != NULL_TREE
819 || this->need_init_fn_
820 || this->is_main_package())
821 this->write_initialization_function(init_fndecl, init_stmt_list);
823 // Pass everything back to the middle-end.
825 wrapup_global_declarations(vec, count);
827 cgraph_finalize_compilation_unit();
829 check_global_declarations(vec, count);
830 emit_debug_global_declarations(vec, count);
835 // Get a tree for the identifier for a named object.
838 Named_object::get_id(Gogo* gogo)
840 go_assert(!this->is_variable() && !this->is_result_variable());
841 std::string decl_name;
842 if (this->is_function_declaration()
843 && !this->func_declaration_value()->asm_name().empty())
844 decl_name = this->func_declaration_value()->asm_name();
845 else if (this->is_type()
846 && this->type_value()->location() == BUILTINS_LOCATION)
848 // We don't need the package name for builtin types.
849 decl_name = Gogo::unpack_hidden_name(this->name_);
853 std::string package_name;
854 if (this->package_ == NULL)
855 package_name = gogo->package_name();
857 package_name = this->package_->name();
859 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
861 Function_type* fntype;
862 if (this->is_function())
863 fntype = this->func_value()->type();
864 else if (this->is_function_declaration())
865 fntype = this->func_declaration_value()->type();
868 if (fntype != NULL && fntype->is_method())
870 decl_name.push_back('.');
871 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
876 const Named_object* in_function = this->type_value()->in_function();
877 if (in_function != NULL)
878 decl_name += '$' + in_function->name();
880 return get_identifier_from_string(decl_name);
883 // Get a tree for a named object.
886 Named_object::get_tree(Gogo* gogo, Named_object* function)
888 if (this->tree_ != NULL_TREE)
892 if (this->classification_ == NAMED_OBJECT_TYPE)
895 name = this->get_id(gogo);
897 switch (this->classification_)
899 case NAMED_OBJECT_CONST:
901 Named_constant* named_constant = this->u_.const_value;
902 Translate_context subcontext(gogo, function, NULL, NULL);
903 tree expr_tree = named_constant->expr()->get_tree(&subcontext);
904 if (expr_tree == error_mark_node)
905 decl = error_mark_node;
908 Type* type = named_constant->type();
909 if (type != NULL && !type->is_abstract())
911 if (type->is_error())
912 expr_tree = error_mark_node;
915 Btype* btype = type->get_backend(gogo);
916 expr_tree = fold_convert(type_to_tree(btype), expr_tree);
919 if (expr_tree == error_mark_node)
920 decl = error_mark_node;
921 else if (INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
923 decl = build_decl(named_constant->location(), CONST_DECL,
924 name, TREE_TYPE(expr_tree));
925 DECL_INITIAL(decl) = expr_tree;
926 TREE_CONSTANT(decl) = 1;
927 TREE_READONLY(decl) = 1;
931 // A CONST_DECL is only for an enum constant, so we
932 // shouldn't use for non-integral types. Instead we
933 // just return the constant itself, rather than a
941 case NAMED_OBJECT_TYPE:
943 Named_type* named_type = this->u_.type_value;
944 tree type_tree = type_to_tree(named_type->get_backend(gogo));
945 if (type_tree == error_mark_node)
946 decl = error_mark_node;
949 decl = TYPE_NAME(type_tree);
950 go_assert(decl != NULL_TREE);
952 // We need to produce a type descriptor for every named
953 // type, and for a pointer to every named type, since
954 // other files or packages might refer to them. We need
955 // to do this even for hidden types, because they might
956 // still be returned by some function. Simply calling the
957 // type_descriptor method is enough to create the type
958 // descriptor, even though we don't do anything with it.
959 if (this->package_ == NULL)
961 named_type->type_descriptor_pointer(gogo, BUILTINS_LOCATION);
962 Type* pn = Type::make_pointer_type(named_type);
963 pn->type_descriptor_pointer(gogo, BUILTINS_LOCATION);
969 case NAMED_OBJECT_TYPE_DECLARATION:
970 error("reference to undefined type %qs",
971 this->message_name().c_str());
972 return error_mark_node;
974 case NAMED_OBJECT_VAR:
975 case NAMED_OBJECT_RESULT_VAR:
976 case NAMED_OBJECT_SINK:
979 case NAMED_OBJECT_FUNC:
981 Function* func = this->u_.func_value;
982 decl = func->get_or_make_decl(gogo, this, name);
983 if (decl != error_mark_node)
985 if (func->block() != NULL)
987 if (DECL_STRUCT_FUNCTION(decl) == NULL)
988 push_struct_function(decl);
990 push_cfun(DECL_STRUCT_FUNCTION(decl));
992 cfun->function_end_locus = func->block()->end_location();
994 current_function_decl = decl;
996 func->build_tree(gogo, this);
998 gimplify_function_tree(decl);
1000 cgraph_finalize_function(decl, true);
1002 current_function_decl = NULL_TREE;
1013 if (TREE_TYPE(decl) == error_mark_node)
1014 decl = error_mark_node;
1020 if (ret != error_mark_node)
1021 go_preserve_from_gc(ret);
1026 // Get the initial value of a variable as a tree. This does not
1027 // consider whether the variable is in the heap--it returns the
1028 // initial value as though it were always stored in the stack.
1031 Variable::get_init_tree(Gogo* gogo, Named_object* function)
1033 go_assert(this->preinit_ == NULL);
1034 if (this->init_ == NULL)
1036 go_assert(!this->is_parameter_);
1037 if (this->is_global_ || this->is_in_heap())
1039 Btype* btype = this->type_->get_backend(gogo);
1040 return expr_to_tree(gogo->backend()->zero_expression(btype));
1044 Translate_context context(gogo, function, NULL, NULL);
1045 tree rhs_tree = this->init_->get_tree(&context);
1046 return Expression::convert_for_assignment(&context, this->type(),
1047 this->init_->type(),
1048 rhs_tree, this->location());
1052 // Get the initial value of a variable when a block is required.
1053 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
1056 Variable::get_init_block(Gogo* gogo, Named_object* function, tree var_decl)
1058 go_assert(this->preinit_ != NULL);
1060 // We want to add the variable assignment to the end of the preinit
1061 // block. The preinit block may have a TRY_FINALLY_EXPR and a
1062 // TRY_CATCH_EXPR; if it does, we want to add to the end of the
1063 // regular statements.
1065 Translate_context context(gogo, function, NULL, NULL);
1066 Bblock* bblock = this->preinit_->get_backend(&context);
1067 tree block_tree = block_to_tree(bblock);
1068 if (block_tree == error_mark_node)
1069 return error_mark_node;
1070 go_assert(TREE_CODE(block_tree) == BIND_EXPR);
1071 tree statements = BIND_EXPR_BODY(block_tree);
1072 while (statements != NULL_TREE
1073 && (TREE_CODE(statements) == TRY_FINALLY_EXPR
1074 || TREE_CODE(statements) == TRY_CATCH_EXPR))
1075 statements = TREE_OPERAND(statements, 0);
1077 // It's possible to have pre-init statements without an initializer
1078 // if the pre-init statements set the variable.
1079 if (this->init_ != NULL)
1081 tree rhs_tree = this->init_->get_tree(&context);
1082 if (rhs_tree == error_mark_node)
1083 return error_mark_node;
1084 if (var_decl == NULL_TREE)
1085 append_to_statement_list(rhs_tree, &statements);
1088 tree val = Expression::convert_for_assignment(&context, this->type(),
1089 this->init_->type(),
1092 if (val == error_mark_node)
1093 return error_mark_node;
1094 tree set = fold_build2_loc(this->location(), MODIFY_EXPR,
1095 void_type_node, var_decl, val);
1096 append_to_statement_list(set, &statements);
1103 // Get a tree for a function decl.
1106 Function::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1108 if (this->fndecl_ == NULL_TREE)
1110 tree functype = type_to_tree(this->type_->get_backend(gogo));
1111 if (functype == error_mark_node)
1112 this->fndecl_ = error_mark_node;
1115 // The type of a function comes back as a pointer, but we
1116 // want the real function type for a function declaration.
1117 go_assert(POINTER_TYPE_P(functype));
1118 functype = TREE_TYPE(functype);
1119 tree decl = build_decl(this->location(), FUNCTION_DECL, id, functype);
1121 this->fndecl_ = decl;
1123 if (no->package() != NULL)
1125 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
1127 else if (Gogo::unpack_hidden_name(no->name()) == "init"
1128 && !this->type_->is_method())
1130 else if (Gogo::unpack_hidden_name(no->name()) == "main"
1131 && gogo->is_main_package())
1132 TREE_PUBLIC(decl) = 1;
1133 // Methods have to be public even if they are hidden because
1134 // they can be pulled into type descriptors when using
1135 // anonymous fields.
1136 else if (!Gogo::is_hidden_name(no->name())
1137 || this->type_->is_method())
1139 TREE_PUBLIC(decl) = 1;
1140 std::string asm_name = gogo->unique_prefix();
1141 asm_name.append(1, '.');
1142 asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id));
1143 SET_DECL_ASSEMBLER_NAME(decl,
1144 get_identifier_from_string(asm_name));
1147 // Why do we have to do this in the frontend?
1148 tree restype = TREE_TYPE(functype);
1149 tree resdecl = build_decl(this->location(), RESULT_DECL, NULL_TREE,
1151 DECL_ARTIFICIAL(resdecl) = 1;
1152 DECL_IGNORED_P(resdecl) = 1;
1153 DECL_CONTEXT(resdecl) = decl;
1154 DECL_RESULT(decl) = resdecl;
1156 if (this->enclosing_ != NULL)
1157 DECL_STATIC_CHAIN(decl) = 1;
1159 // If a function calls the predeclared recover function, we
1160 // can't inline it, because recover behaves differently in a
1161 // function passed directly to defer. If this is a recover
1162 // thunk that we built to test whether a function can be
1163 // recovered, we can't inline it, because that will mess up
1164 // our return address comparison.
1165 if (this->calls_recover_ || this->is_recover_thunk_)
1166 DECL_UNINLINABLE(decl) = 1;
1168 // If this is a thunk created to call a function which calls
1169 // the predeclared recover function, we need to disable
1170 // stack splitting for the thunk.
1171 if (this->is_recover_thunk_)
1173 tree attr = get_identifier("__no_split_stack__");
1174 DECL_ATTRIBUTES(decl) = tree_cons(attr, NULL_TREE, NULL_TREE);
1177 go_preserve_from_gc(decl);
1179 if (this->closure_var_ != NULL)
1181 push_struct_function(decl);
1183 Bvariable* bvar = this->closure_var_->get_backend_variable(gogo,
1185 tree closure_decl = var_to_tree(bvar);
1186 if (closure_decl == error_mark_node)
1187 this->fndecl_ = error_mark_node;
1190 DECL_ARTIFICIAL(closure_decl) = 1;
1191 DECL_IGNORED_P(closure_decl) = 1;
1192 TREE_USED(closure_decl) = 1;
1193 DECL_ARG_TYPE(closure_decl) = TREE_TYPE(closure_decl);
1194 TREE_READONLY(closure_decl) = 1;
1196 DECL_STRUCT_FUNCTION(decl)->static_chain_decl = closure_decl;
1203 return this->fndecl_;
1206 // Get a tree for a function declaration.
1209 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1211 if (this->fndecl_ == NULL_TREE)
1213 // Let Go code use an asm declaration to pick up a builtin
1215 if (!this->asm_name_.empty())
1217 std::map<std::string, tree>::const_iterator p =
1218 builtin_functions.find(this->asm_name_);
1219 if (p != builtin_functions.end())
1221 this->fndecl_ = p->second;
1222 return this->fndecl_;
1226 tree functype = type_to_tree(this->fntype_->get_backend(gogo));
1228 if (functype == error_mark_node)
1229 decl = error_mark_node;
1232 // The type of a function comes back as a pointer, but we
1233 // want the real function type for a function declaration.
1234 go_assert(POINTER_TYPE_P(functype));
1235 functype = TREE_TYPE(functype);
1236 decl = build_decl(this->location(), FUNCTION_DECL, id, functype);
1237 TREE_PUBLIC(decl) = 1;
1238 DECL_EXTERNAL(decl) = 1;
1240 if (this->asm_name_.empty())
1242 std::string asm_name = (no->package() == NULL
1243 ? gogo->unique_prefix()
1244 : no->package()->unique_prefix());
1245 asm_name.append(1, '.');
1246 asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id));
1247 SET_DECL_ASSEMBLER_NAME(decl,
1248 get_identifier_from_string(asm_name));
1251 this->fndecl_ = decl;
1252 go_preserve_from_gc(decl);
1254 return this->fndecl_;
1257 // We always pass the receiver to a method as a pointer. If the
1258 // receiver is actually declared as a non-pointer type, then we copy
1259 // the value into a local variable, so that it has the right type. In
1260 // this function we create the real PARM_DECL to use, and set
1261 // DEC_INITIAL of the var_decl to be the value passed in.
1264 Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl)
1266 if (var_decl == error_mark_node)
1267 return error_mark_node;
1268 go_assert(TREE_CODE(var_decl) == VAR_DECL);
1269 tree val_type = TREE_TYPE(var_decl);
1270 bool is_in_heap = no->var_value()->is_in_heap();
1273 go_assert(POINTER_TYPE_P(val_type));
1274 val_type = TREE_TYPE(val_type);
1277 source_location loc = DECL_SOURCE_LOCATION(var_decl);
1278 std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1280 tree id = get_identifier_from_string(name);
1281 tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type));
1282 DECL_CONTEXT(parm_decl) = current_function_decl;
1283 DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl);
1285 go_assert(DECL_INITIAL(var_decl) == NULL_TREE);
1286 tree init = build_fold_indirect_ref_loc(loc, parm_decl);
1290 tree size = TYPE_SIZE_UNIT(val_type);
1291 tree space = gogo->allocate_memory(no->var_value()->type(), size,
1293 space = save_expr(space);
1294 space = fold_convert(build_pointer_type(val_type), space);
1295 tree spaceref = build_fold_indirect_ref_loc(no->location(), space);
1296 TREE_THIS_NOTRAP(spaceref) = 1;
1297 tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node,
1299 init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), set, space);
1302 DECL_INITIAL(var_decl) = init;
1307 // If we take the address of a parameter, then we need to copy it into
1308 // the heap. We will access it as a local variable via an
1312 Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree var_decl)
1314 if (var_decl == error_mark_node)
1315 return error_mark_node;
1316 go_assert(TREE_CODE(var_decl) == VAR_DECL);
1317 source_location loc = DECL_SOURCE_LOCATION(var_decl);
1319 std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1321 tree id = get_identifier_from_string(name);
1323 tree type = TREE_TYPE(var_decl);
1324 go_assert(POINTER_TYPE_P(type));
1325 type = TREE_TYPE(type);
1327 tree parm_decl = build_decl(loc, PARM_DECL, id, type);
1328 DECL_CONTEXT(parm_decl) = current_function_decl;
1329 DECL_ARG_TYPE(parm_decl) = type;
1331 tree size = TYPE_SIZE_UNIT(type);
1332 tree space = gogo->allocate_memory(no->var_value()->type(), size, loc);
1333 space = save_expr(space);
1334 space = fold_convert(TREE_TYPE(var_decl), space);
1335 tree spaceref = build_fold_indirect_ref_loc(loc, space);
1336 TREE_THIS_NOTRAP(spaceref) = 1;
1337 tree init = build2(COMPOUND_EXPR, TREE_TYPE(space),
1338 build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl),
1340 DECL_INITIAL(var_decl) = init;
1345 // Get a tree for function code.
1348 Function::build_tree(Gogo* gogo, Named_object* named_function)
1350 tree fndecl = this->fndecl_;
1351 go_assert(fndecl != NULL_TREE);
1353 tree params = NULL_TREE;
1356 tree declare_vars = NULL_TREE;
1357 for (Bindings::const_definitions_iterator p =
1358 this->block_->bindings()->begin_definitions();
1359 p != this->block_->bindings()->end_definitions();
1362 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
1364 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
1365 *pp = var_to_tree(bvar);
1367 // We always pass the receiver to a method as a pointer. If
1368 // the receiver is declared as a non-pointer type, then we
1369 // copy the value into a local variable.
1370 if ((*p)->var_value()->is_receiver()
1371 && (*p)->var_value()->type()->points_to() == NULL)
1373 tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp);
1375 if (var != error_mark_node)
1377 go_assert(TREE_CODE(var) == VAR_DECL);
1378 DECL_CHAIN(var) = declare_vars;
1383 else if ((*p)->var_value()->is_in_heap())
1385 // If we take the address of a parameter, then we need
1386 // to copy it into the heap.
1387 tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp);
1389 if (var != error_mark_node)
1391 go_assert(TREE_CODE(var) == VAR_DECL);
1392 DECL_CHAIN(var) = declare_vars;
1398 if (*pp != error_mark_node)
1400 go_assert(TREE_CODE(*pp) == PARM_DECL);
1401 pp = &DECL_CHAIN(*pp);
1404 else if ((*p)->is_result_variable())
1406 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
1407 tree var_decl = var_to_tree(bvar);
1409 Type* type = (*p)->result_var_value()->type();
1411 if (!(*p)->result_var_value()->is_in_heap())
1413 Btype* btype = type->get_backend(gogo);
1414 init = expr_to_tree(gogo->backend()->zero_expression(btype));
1418 source_location loc = (*p)->location();
1419 tree type_tree = type_to_tree(type->get_backend(gogo));
1420 tree space = gogo->allocate_memory(type,
1421 TYPE_SIZE_UNIT(type_tree),
1423 tree ptr_type_tree = build_pointer_type(type_tree);
1424 init = fold_convert_loc(loc, ptr_type_tree, space);
1427 if (var_decl != error_mark_node)
1429 go_assert(TREE_CODE(var_decl) == VAR_DECL);
1430 DECL_INITIAL(var_decl) = init;
1431 DECL_CHAIN(var_decl) = declare_vars;
1432 declare_vars = var_decl;
1438 DECL_ARGUMENTS(fndecl) = params;
1440 if (this->block_ != NULL)
1442 go_assert(DECL_INITIAL(fndecl) == NULL_TREE);
1444 // Declare variables if necessary.
1445 tree bind = NULL_TREE;
1446 tree defer_init = NULL_TREE;
1447 if (declare_vars != NULL_TREE || this->defer_stack_ != NULL)
1449 tree block = make_node(BLOCK);
1450 BLOCK_SUPERCONTEXT(block) = fndecl;
1451 DECL_INITIAL(fndecl) = block;
1452 BLOCK_VARS(block) = declare_vars;
1453 TREE_USED(block) = 1;
1455 bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block),
1457 TREE_SIDE_EFFECTS(bind) = 1;
1459 if (this->defer_stack_ != NULL)
1461 Translate_context dcontext(gogo, named_function, this->block_,
1462 tree_to_block(bind));
1463 Bstatement* bdi = this->defer_stack_->get_backend(&dcontext);
1464 defer_init = stat_to_tree(bdi);
1468 // Build the trees for all the statements in the function.
1469 Translate_context context(gogo, named_function, NULL, NULL);
1470 Bblock* bblock = this->block_->get_backend(&context);
1471 tree code = block_to_tree(bblock);
1473 tree init = NULL_TREE;
1474 tree except = NULL_TREE;
1475 tree fini = NULL_TREE;
1477 // Initialize variables if necessary.
1478 for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v))
1480 tree dv = build1(DECL_EXPR, void_type_node, v);
1481 SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v));
1482 append_to_statement_list(dv, &init);
1485 // If we have a defer stack, initialize it at the start of a
1487 if (defer_init != NULL_TREE && defer_init != error_mark_node)
1489 SET_EXPR_LOCATION(defer_init, this->block_->start_location());
1490 append_to_statement_list(defer_init, &init);
1492 // Clean up the defer stack when we leave the function.
1493 this->build_defer_wrapper(gogo, named_function, &except, &fini);
1496 if (code != NULL_TREE && code != error_mark_node)
1498 if (init != NULL_TREE)
1499 code = build2(COMPOUND_EXPR, void_type_node, init, code);
1500 if (except != NULL_TREE)
1501 code = build2(TRY_CATCH_EXPR, void_type_node, code,
1502 build2(CATCH_EXPR, void_type_node, NULL, except));
1503 if (fini != NULL_TREE)
1504 code = build2(TRY_FINALLY_EXPR, void_type_node, code, fini);
1507 // Stick the code into the block we built for the receiver, if
1509 if (bind != NULL_TREE && code != NULL_TREE && code != error_mark_node)
1511 BIND_EXPR_BODY(bind) = code;
1515 DECL_SAVED_TREE(fndecl) = code;
1519 // Build the wrappers around function code needed if the function has
1520 // any defer statements. This sets *EXCEPT to an exception handler
1521 // and *FINI to a finally handler.
1524 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
1525 tree *except, tree *fini)
1527 source_location end_loc = this->block_->end_location();
1529 // Add an exception handler. This is used if a panic occurs. Its
1530 // purpose is to stop the stack unwinding if a deferred function
1531 // calls recover. There are more details in
1532 // libgo/runtime/go-unwind.c.
1534 tree stmt_list = NULL_TREE;
1536 Expression* call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
1537 this->defer_stack(end_loc));
1538 Translate_context context(gogo, named_function, NULL, NULL);
1539 tree call_tree = call->get_tree(&context);
1540 if (call_tree != error_mark_node)
1541 append_to_statement_list(call_tree, &stmt_list);
1543 tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list);
1545 if (retval == NULL_TREE)
1548 set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node,
1549 DECL_RESULT(this->fndecl_), retval);
1550 tree ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set);
1551 append_to_statement_list(ret_stmt, &stmt_list);
1553 go_assert(*except == NULL_TREE);
1554 *except = stmt_list;
1556 // Add some finally code to run the defer functions. This is used
1557 // both in the normal case, when no panic occurs, and also if a
1558 // panic occurs to run any further defer functions. Of course, it
1559 // is possible for a defer function to call panic which should be
1560 // caught by another defer function. To handle that we use a loop.
1562 // try { __go_undefer(); } catch { __go_check_defer(); goto finish; }
1563 // if (return values are named) return named_vals;
1567 tree label = create_artificial_label(end_loc);
1568 tree define_label = fold_build1_loc(end_loc, LABEL_EXPR, void_type_node,
1570 append_to_statement_list(define_label, &stmt_list);
1572 call = Runtime::make_call(Runtime::UNDEFER, end_loc, 1,
1573 this->defer_stack(end_loc));
1574 tree undefer = call->get_tree(&context);
1576 call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
1577 this->defer_stack(end_loc));
1578 tree defer = call->get_tree(&context);
1580 if (undefer == error_mark_node || defer == error_mark_node)
1583 tree jump = fold_build1_loc(end_loc, GOTO_EXPR, void_type_node, label);
1584 tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump);
1585 catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body);
1586 tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body);
1588 append_to_statement_list(try_catch, &stmt_list);
1590 if (this->type_->results() != NULL
1591 && !this->type_->results()->empty()
1592 && !this->type_->results()->front().name().empty())
1594 // If the result variables are named, and we are returning from
1595 // this function rather than panicing through it, we need to
1596 // return them again, because they might have been changed by a
1597 // defer function. The runtime routines set the defer_stack
1598 // variable to true if we are returning from this function.
1599 retval = this->return_value(gogo, named_function, end_loc,
1601 set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node,
1602 DECL_RESULT(this->fndecl_), retval);
1603 ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set);
1606 Expression::make_temporary_reference(this->defer_stack_, end_loc);
1607 tree tref = ref->get_tree(&context);
1608 tree s = build3_loc(end_loc, COND_EXPR, void_type_node, tref,
1609 ret_stmt, NULL_TREE);
1611 append_to_statement_list(s, &stmt_list);
1615 go_assert(*fini == NULL_TREE);
1619 // Return the value to assign to DECL_RESULT(this->fndecl_). This may
1620 // also add statements to STMT_LIST, which need to be executed before
1621 // the assignment. This is used for a return statement with no
1625 Function::return_value(Gogo* gogo, Named_object* named_function,
1626 source_location location, tree* stmt_list) const
1628 const Typed_identifier_list* results = this->type_->results();
1629 if (results == NULL || results->empty())
1632 go_assert(this->results_ != NULL);
1633 if (this->results_->size() != results->size())
1635 go_assert(saw_errors());
1636 return error_mark_node;
1640 if (results->size() == 1)
1643 this->results_->front()->get_backend_variable(gogo,
1645 tree ret = var_to_tree(bvar);
1646 if (this->results_->front()->result_var_value()->is_in_heap())
1647 ret = build_fold_indirect_ref_loc(location, ret);
1652 tree rettype = TREE_TYPE(DECL_RESULT(this->fndecl_));
1653 retval = create_tmp_var(rettype, "RESULT");
1654 tree field = TYPE_FIELDS(rettype);
1656 for (Typed_identifier_list::const_iterator pr = results->begin();
1657 pr != results->end();
1658 ++pr, ++index, field = DECL_CHAIN(field))
1660 go_assert(field != NULL);
1661 Named_object* no = (*this->results_)[index];
1662 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
1663 tree val = var_to_tree(bvar);
1664 if (no->result_var_value()->is_in_heap())
1665 val = build_fold_indirect_ref_loc(location, val);
1666 tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node,
1667 build3(COMPONENT_REF, TREE_TYPE(field),
1668 retval, field, NULL_TREE),
1670 append_to_statement_list(set, stmt_list);
1676 // Return the integer type to use for a size.
1680 go_type_for_size(unsigned int bits, int unsignedp)
1686 name = unsignedp ? "uint8" : "int8";
1689 name = unsignedp ? "uint16" : "int16";
1692 name = unsignedp ? "uint32" : "int32";
1695 name = unsignedp ? "uint64" : "int64";
1698 if (bits == POINTER_SIZE && unsignedp)
1703 Type* type = Type::lookup_integer_type(name);
1704 return type_to_tree(type->get_backend(go_get_gogo()));
1707 // Return the type to use for a mode.
1711 go_type_for_mode(enum machine_mode mode, int unsignedp)
1713 // FIXME: This static_cast should be in machmode.h.
1714 enum mode_class mc = static_cast<enum mode_class>(GET_MODE_CLASS(mode));
1716 return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp);
1717 else if (mc == MODE_FLOAT)
1720 switch (GET_MODE_BITSIZE (mode))
1723 type = Type::lookup_float_type("float32");
1726 type = Type::lookup_float_type("float64");
1729 // We have to check for long double in order to support
1730 // i386 excess precision.
1731 if (mode == TYPE_MODE(long_double_type_node))
1732 return long_double_type_node;
1735 return type_to_tree(type->get_backend(go_get_gogo()));
1737 else if (mc == MODE_COMPLEX_FLOAT)
1740 switch (GET_MODE_BITSIZE (mode))
1743 type = Type::lookup_complex_type("complex64");
1746 type = Type::lookup_complex_type("complex128");
1749 // We have to check for long double in order to support
1750 // i386 excess precision.
1751 if (mode == TYPE_MODE(complex_long_double_type_node))
1752 return complex_long_double_type_node;
1755 return type_to_tree(type->get_backend(go_get_gogo()));
1761 // Return a tree which allocates SIZE bytes which will holds value of
1765 Gogo::allocate_memory(Type* type, tree size, source_location location)
1767 // If the package imports unsafe, then it may play games with
1768 // pointers that look like integers.
1769 if (this->imported_unsafe_ || type->has_pointer())
1771 static tree new_fndecl;
1772 return Gogo::call_builtin(&new_fndecl,
1782 static tree new_nopointers_fndecl;
1783 return Gogo::call_builtin(&new_nopointers_fndecl,
1785 "__go_new_nopointers",
1793 // Build a builtin struct with a list of fields. The name is
1794 // STRUCT_NAME. STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE
1795 // node; this exists so that the struct can have fields which point to
1796 // itself. If PTYPE is not NULL, store the result in *PTYPE. There
1797 // are NFIELDS fields. Each field is a name (a const char*) followed
1798 // by a type (a tree).
1801 Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type,
1804 if (ptype != NULL && *ptype != NULL_TREE)
1808 va_start(ap, nfields);
1810 tree fields = NULL_TREE;
1811 for (int i = 0; i < nfields; ++i)
1813 const char* field_name = va_arg(ap, const char*);
1814 tree type = va_arg(ap, tree);
1815 if (type == error_mark_node)
1818 *ptype = error_mark_node;
1819 return error_mark_node;
1821 tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL,
1822 get_identifier(field_name), type);
1823 DECL_CHAIN(field) = fields;
1829 if (struct_type == NULL_TREE)
1830 struct_type = make_node(RECORD_TYPE);
1831 finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE);
1835 go_preserve_from_gc(struct_type);
1836 *ptype = struct_type;
1842 // Return a type to use for pointer to const char for a string.
1845 Gogo::const_char_pointer_type_tree()
1848 if (type == NULL_TREE)
1850 tree const_char_type = build_qualified_type(unsigned_char_type_node,
1852 type = build_pointer_type(const_char_type);
1853 go_preserve_from_gc(type);
1858 // Return a tree for a string constant.
1861 Gogo::string_constant_tree(const std::string& val)
1863 tree index_type = build_index_type(size_int(val.length()));
1864 tree const_char_type = build_qualified_type(unsigned_char_type_node,
1866 tree string_type = build_array_type(const_char_type, index_type);
1867 string_type = build_variant_type_copy(string_type);
1868 TYPE_STRING_FLAG(string_type) = 1;
1869 tree string_val = build_string(val.length(), val.data());
1870 TREE_TYPE(string_val) = string_type;
1874 // Return a tree for a Go string constant.
1877 Gogo::go_string_constant_tree(const std::string& val)
1879 tree string_type = type_to_tree(Type::make_string_type()->get_backend(this));
1881 VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2);
1883 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
1884 tree field = TYPE_FIELDS(string_type);
1885 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0);
1887 tree str = Gogo::string_constant_tree(val);
1888 elt->value = fold_convert(TREE_TYPE(field),
1889 build_fold_addr_expr(str));
1891 elt = VEC_quick_push(constructor_elt, init, NULL);
1892 field = DECL_CHAIN(field);
1893 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0);
1895 elt->value = build_int_cst_type(TREE_TYPE(field), val.length());
1897 tree constructor = build_constructor(string_type, init);
1898 TREE_READONLY(constructor) = 1;
1899 TREE_CONSTANT(constructor) = 1;
1904 // Return a tree for a pointer to a Go string constant. This is only
1905 // used for type descriptors, so we return a pointer to a constant
1909 Gogo::ptr_go_string_constant_tree(const std::string& val)
1911 tree pval = this->go_string_constant_tree(val);
1913 tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL,
1914 create_tmp_var_name("SP"), TREE_TYPE(pval));
1915 DECL_EXTERNAL(decl) = 0;
1916 TREE_PUBLIC(decl) = 0;
1917 TREE_USED(decl) = 1;
1918 TREE_READONLY(decl) = 1;
1919 TREE_CONSTANT(decl) = 1;
1920 TREE_STATIC(decl) = 1;
1921 DECL_ARTIFICIAL(decl) = 1;
1922 DECL_INITIAL(decl) = pval;
1923 rest_of_decl_compilation(decl, 1, 0);
1925 return build_fold_addr_expr(decl);
1928 // Build a constructor for a slice. SLICE_TYPE_TREE is the type of
1929 // the slice. VALUES is the value pointer and COUNT is the number of
1930 // entries. If CAPACITY is not NULL, it is the capacity; otherwise
1931 // the capacity and the count are the same.
1934 Gogo::slice_constructor(tree slice_type_tree, tree values, tree count,
1937 go_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE);
1939 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
1941 tree field = TYPE_FIELDS(slice_type_tree);
1942 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
1943 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
1945 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field))
1946 == TYPE_MAIN_VARIANT(TREE_TYPE(values)));
1947 elt->value = values;
1949 count = fold_convert(sizetype, count);
1950 if (capacity == NULL_TREE)
1952 count = save_expr(count);
1956 field = DECL_CHAIN(field);
1957 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
1958 elt = VEC_quick_push(constructor_elt, init, NULL);
1960 elt->value = fold_convert(TREE_TYPE(field), count);
1962 field = DECL_CHAIN(field);
1963 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
1964 elt = VEC_quick_push(constructor_elt, init, NULL);
1966 elt->value = fold_convert(TREE_TYPE(field), capacity);
1968 return build_constructor(slice_type_tree, init);
1971 // Build an interface method table for a type: a list of function
1972 // pointers, one for each interface method. This is used for
1976 Gogo::interface_method_table_for_type(const Interface_type* interface,
1980 const Typed_identifier_list* interface_methods = interface->methods();
1981 go_assert(!interface_methods->empty());
1983 std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_")
1984 + interface->mangled_name(this)
1986 + type->mangled_name(this));
1988 tree id = get_identifier_from_string(mangled_name);
1990 // See whether this interface has any hidden methods.
1991 bool has_hidden_methods = false;
1992 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
1993 p != interface_methods->end();
1996 if (Gogo::is_hidden_name(p->name()))
1998 has_hidden_methods = true;
2003 // We already know that the named type is convertible to the
2004 // interface. If the interface has hidden methods, and the named
2005 // type is defined in a different package, then the interface
2006 // conversion table will be defined by that other package.
2007 if (has_hidden_methods && type->named_object()->package() != NULL)
2009 tree array_type = build_array_type(const_ptr_type_node, NULL);
2010 tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2011 TREE_READONLY(decl) = 1;
2012 TREE_CONSTANT(decl) = 1;
2013 TREE_PUBLIC(decl) = 1;
2014 DECL_EXTERNAL(decl) = 1;
2015 go_preserve_from_gc(decl);
2019 size_t count = interface_methods->size();
2020 VEC(constructor_elt, gc)* pointers = VEC_alloc(constructor_elt, gc,
2023 // The first element is the type descriptor.
2024 constructor_elt* elt = VEC_quick_push(constructor_elt, pointers, NULL);
2025 elt->index = size_zero_node;
2030 td_type = Type::make_pointer_type(type);
2031 tree tdp = td_type->type_descriptor_pointer(this, BUILTINS_LOCATION);
2032 elt->value = fold_convert(const_ptr_type_node, tdp);
2035 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2036 p != interface_methods->end();
2040 Method* m = type->method_function(p->name(), &is_ambiguous);
2041 go_assert(m != NULL);
2043 Named_object* no = m->named_object();
2045 tree fnid = no->get_id(this);
2048 if (no->is_function())
2049 fndecl = no->func_value()->get_or_make_decl(this, no, fnid);
2050 else if (no->is_function_declaration())
2051 fndecl = no->func_declaration_value()->get_or_make_decl(this, no,
2055 fndecl = build_fold_addr_expr(fndecl);
2057 elt = VEC_quick_push(constructor_elt, pointers, NULL);
2058 elt->index = size_int(i);
2059 elt->value = fold_convert(const_ptr_type_node, fndecl);
2061 go_assert(i == count + 1);
2063 tree array_type = build_array_type(const_ptr_type_node,
2064 build_index_type(size_int(count)));
2065 tree constructor = build_constructor(array_type, pointers);
2067 tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2068 TREE_STATIC(decl) = 1;
2069 TREE_USED(decl) = 1;
2070 TREE_READONLY(decl) = 1;
2071 TREE_CONSTANT(decl) = 1;
2072 DECL_INITIAL(decl) = constructor;
2074 // If the interface type has hidden methods, then this is the only
2075 // definition of the table. Otherwise it is a comdat table which
2076 // may be defined in multiple packages.
2077 if (has_hidden_methods)
2078 TREE_PUBLIC(decl) = 1;
2081 make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2082 resolve_unique_section(decl, 1, 0);
2085 rest_of_decl_compilation(decl, 1, 0);
2087 go_preserve_from_gc(decl);
2092 // Mark a function as a builtin library function.
2095 Gogo::mark_fndecl_as_builtin_library(tree fndecl)
2097 DECL_EXTERNAL(fndecl) = 1;
2098 TREE_PUBLIC(fndecl) = 1;
2099 DECL_ARTIFICIAL(fndecl) = 1;
2100 TREE_NOTHROW(fndecl) = 1;
2101 DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT;
2102 DECL_VISIBILITY_SPECIFIED(fndecl) = 1;
2105 // Build a call to a builtin function.
2108 Gogo::call_builtin(tree* pdecl, source_location location, const char* name,
2109 int nargs, tree rettype, ...)
2111 if (rettype == error_mark_node)
2112 return error_mark_node;
2114 tree* types = new tree[nargs];
2115 tree* args = new tree[nargs];
2118 va_start(ap, rettype);
2119 for (int i = 0; i < nargs; ++i)
2121 types[i] = va_arg(ap, tree);
2122 args[i] = va_arg(ap, tree);
2123 if (types[i] == error_mark_node || args[i] == error_mark_node)
2127 return error_mark_node;
2132 if (*pdecl == NULL_TREE)
2134 tree fnid = get_identifier(name);
2136 tree argtypes = NULL_TREE;
2137 tree* pp = &argtypes;
2138 for (int i = 0; i < nargs; ++i)
2140 *pp = tree_cons(NULL_TREE, types[i], NULL_TREE);
2141 pp = &TREE_CHAIN(*pp);
2143 *pp = void_list_node;
2145 tree fntype = build_function_type(rettype, argtypes);
2147 *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype);
2148 Gogo::mark_fndecl_as_builtin_library(*pdecl);
2149 go_preserve_from_gc(*pdecl);
2152 tree fnptr = build_fold_addr_expr(*pdecl);
2153 if (CAN_HAVE_LOCATION_P(fnptr))
2154 SET_EXPR_LOCATION(fnptr, location);
2156 tree ret = build_call_array(rettype, fnptr, nargs, args);
2157 SET_EXPR_LOCATION(ret, location);
2165 // Build a call to the runtime error function.
2168 Gogo::runtime_error(int code, source_location location)
2170 static tree runtime_error_fndecl;
2171 tree ret = Gogo::call_builtin(&runtime_error_fndecl,
2173 "__go_runtime_error",
2177 build_int_cst(integer_type_node, code));
2178 if (ret == error_mark_node)
2179 return error_mark_node;
2180 // The runtime error function panics and does not return.
2181 TREE_NOTHROW(runtime_error_fndecl) = 0;
2182 TREE_THIS_VOLATILE(runtime_error_fndecl) = 1;
2186 // Return a tree for receiving a value of type TYPE_TREE on CHANNEL.
2187 // This does a blocking receive and returns the value read from the
2188 // channel. If FOR_SELECT is true, this is being done because it was
2189 // chosen in a select statement.
2192 Gogo::receive_from_channel(tree type_tree, tree channel, bool for_select,
2193 source_location location)
2195 if (type_tree == error_mark_node || channel == error_mark_node)
2196 return error_mark_node;
2198 if (int_size_in_bytes(type_tree) <= 8
2199 && !AGGREGATE_TYPE_P(type_tree)
2200 && !FLOAT_TYPE_P(type_tree))
2202 static tree receive_small_fndecl;
2203 tree call = Gogo::call_builtin(&receive_small_fndecl,
2205 "__go_receive_small",
2213 : boolean_false_node));
2214 if (call == error_mark_node)
2215 return error_mark_node;
2216 // This can panic if there are too many operations on a closed
2218 TREE_NOTHROW(receive_small_fndecl) = 0;
2219 int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree));
2220 tree int_type_tree = go_type_for_size(bitsize, 1);
2221 return fold_convert_loc(location, type_tree,
2222 fold_convert_loc(location, int_type_tree,
2227 tree tmp = create_tmp_var(type_tree, get_name(type_tree));
2228 DECL_IGNORED_P(tmp) = 0;
2229 TREE_ADDRESSABLE(tmp) = 1;
2230 tree make_tmp = build1(DECL_EXPR, void_type_node, tmp);
2231 SET_EXPR_LOCATION(make_tmp, location);
2232 tree tmpaddr = build_fold_addr_expr(tmp);
2233 tmpaddr = fold_convert(ptr_type_node, tmpaddr);
2234 static tree receive_big_fndecl;
2235 tree call = Gogo::call_builtin(&receive_big_fndecl,
2247 : boolean_false_node));
2248 if (call == error_mark_node)
2249 return error_mark_node;
2250 // This can panic if there are too many operations on a closed
2252 TREE_NOTHROW(receive_big_fndecl) = 0;
2253 return build2(COMPOUND_EXPR, type_tree, make_tmp,
2254 build2(COMPOUND_EXPR, type_tree, call, tmp));
2258 // Return the type of a function trampoline. This is like
2259 // get_trampoline_type in tree-nested.c.
2262 Gogo::trampoline_type_tree()
2264 static tree type_tree;
2265 if (type_tree == NULL_TREE)
2269 go_trampoline_info(&size, &align);
2270 tree t = build_index_type(build_int_cst(integer_type_node, size - 1));
2271 t = build_array_type(char_type_node, t);
2273 type_tree = Gogo::builtin_struct(NULL, "__go_trampoline", NULL_TREE, 1,
2275 t = TYPE_FIELDS(type_tree);
2276 DECL_ALIGN(t) = align;
2277 DECL_USER_ALIGN(t) = 1;
2279 go_preserve_from_gc(type_tree);
2284 // Make a trampoline which calls FNADDR passing CLOSURE.
2287 Gogo::make_trampoline(tree fnaddr, tree closure, source_location location)
2289 tree trampoline_type = Gogo::trampoline_type_tree();
2290 tree trampoline_size = TYPE_SIZE_UNIT(trampoline_type);
2292 closure = save_expr(closure);
2294 // We allocate the trampoline using a special function which will
2295 // mark it as executable.
2296 static tree trampoline_fndecl;
2297 tree x = Gogo::call_builtin(&trampoline_fndecl,
2299 "__go_allocate_trampoline",
2305 fold_convert_loc(location, ptr_type_node,
2307 if (x == error_mark_node)
2308 return error_mark_node;
2312 // Initialize the trampoline.
2313 tree ini = build_call_expr(builtin_decl_implicit(BUILT_IN_INIT_TRAMPOLINE),
2314 3, x, fnaddr, closure);
2316 // On some targets the trampoline address needs to be adjusted. For
2317 // example, when compiling in Thumb mode on the ARM, the address
2318 // needs to have the low bit set.
2319 x = build_call_expr(builtin_decl_explicit(BUILT_IN_ADJUST_TRAMPOLINE), 1, x);
2320 x = fold_convert(TREE_TYPE(fnaddr), x);
2322 return build2(COMPOUND_EXPR, TREE_TYPE(x), ini, x);