05417beeb550ec913f3798d92664daf103b25f49
[gcc.git] / gcc / go / gofrontend / gogo-tree.cc
1 // gogo-tree.cc -- convert Go frontend Gogo IR to gcc trees.
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 <gmp.h>
10
11 #ifndef ENABLE_BUILD_WITH_CXX
12 extern "C"
13 {
14 #endif
15
16 #include "toplev.h"
17 #include "tree.h"
18 #include "gimple.h"
19 #include "tree-iterator.h"
20 #include "cgraph.h"
21 #include "langhooks.h"
22 #include "convert.h"
23 #include "output.h"
24 #include "diagnostic.h"
25
26 #ifndef ENABLE_BUILD_WITH_CXX
27 }
28 #endif
29
30 #include "go-c.h"
31 #include "types.h"
32 #include "expressions.h"
33 #include "statements.h"
34 #include "runtime.h"
35 #include "backend.h"
36 #include "gogo.h"
37
38 // Whether we have seen any errors.
39
40 bool
41 saw_errors()
42 {
43 return errorcount != 0 || sorrycount != 0;
44 }
45
46 // A helper function.
47
48 static inline tree
49 get_identifier_from_string(const std::string& str)
50 {
51 return get_identifier_with_length(str.data(), str.length());
52 }
53
54 // Builtin functions.
55
56 static std::map<std::string, tree> builtin_functions;
57
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.
63
64 static void
65 define_builtin(built_in_function bcode, const char* name, const char* libname,
66 tree fntype, bool const_p)
67 {
68 tree decl = add_builtin_function(name, fntype, bcode, BUILT_IN_NORMAL,
69 libname, NULL_TREE);
70 if (const_p)
71 TREE_READONLY(decl) = 1;
72 set_builtin_decl(bcode, decl, true);
73 builtin_functions[name] = decl;
74 if (libname != NULL)
75 {
76 decl = add_builtin_function(libname, fntype, bcode, BUILT_IN_NORMAL,
77 NULL, NULL_TREE);
78 if (const_p)
79 TREE_READONLY(decl) = 1;
80 builtin_functions[libname] = decl;
81 }
82 }
83
84 // Create trees for implicit builtin functions.
85
86 void
87 Gogo::define_builtin_function_trees()
88 {
89 /* We need to define the fetch_and_add functions, since we use them
90 for ++ and --. */
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);
95
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);
100
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);
105
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);
110
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,
116 NULL_TREE),
117 true);
118
119 // We use __builtin_memcmp for struct comparisons.
120 define_builtin(BUILT_IN_MEMCMP, "__builtin_memcmp", "memcmp",
121 build_function_type_list(integer_type_node,
122 const_ptr_type_node,
123 const_ptr_type_node,
124 size_type_node,
125 NULL_TREE),
126 false);
127
128 // We provide some functions for the math library.
129 tree math_function_type = build_function_type_list(double_type_node,
130 double_type_node,
131 NULL_TREE);
132 tree math_function_type_long =
133 build_function_type_list(long_double_type_node, long_double_type_node,
134 long_double_type_node, NULL_TREE);
135 tree math_function_type_two = build_function_type_list(double_type_node,
136 double_type_node,
137 double_type_node,
138 NULL_TREE);
139 tree math_function_type_long_two =
140 build_function_type_list(long_double_type_node, long_double_type_node,
141 long_double_type_node, NULL_TREE);
142 define_builtin(BUILT_IN_ACOS, "__builtin_acos", "acos",
143 math_function_type, true);
144 define_builtin(BUILT_IN_ACOSL, "__builtin_acosl", "acosl",
145 math_function_type_long, true);
146 define_builtin(BUILT_IN_ASIN, "__builtin_asin", "asin",
147 math_function_type, true);
148 define_builtin(BUILT_IN_ASINL, "__builtin_asinl", "asinl",
149 math_function_type_long, true);
150 define_builtin(BUILT_IN_ATAN, "__builtin_atan", "atan",
151 math_function_type, true);
152 define_builtin(BUILT_IN_ATANL, "__builtin_atanl", "atanl",
153 math_function_type_long, true);
154 define_builtin(BUILT_IN_ATAN2, "__builtin_atan2", "atan2",
155 math_function_type_two, true);
156 define_builtin(BUILT_IN_ATAN2L, "__builtin_atan2l", "atan2l",
157 math_function_type_long_two, true);
158 define_builtin(BUILT_IN_CEIL, "__builtin_ceil", "ceil",
159 math_function_type, true);
160 define_builtin(BUILT_IN_CEILL, "__builtin_ceill", "ceill",
161 math_function_type_long, true);
162 define_builtin(BUILT_IN_COS, "__builtin_cos", "cos",
163 math_function_type, true);
164 define_builtin(BUILT_IN_COSL, "__builtin_cosl", "cosl",
165 math_function_type_long, true);
166 define_builtin(BUILT_IN_EXP, "__builtin_exp", "exp",
167 math_function_type, true);
168 define_builtin(BUILT_IN_EXPL, "__builtin_expl", "expl",
169 math_function_type_long, true);
170 define_builtin(BUILT_IN_EXPM1, "__builtin_expm1", "expm1",
171 math_function_type, true);
172 define_builtin(BUILT_IN_EXPM1L, "__builtin_expm1l", "expm1l",
173 math_function_type_long, true);
174 define_builtin(BUILT_IN_FABS, "__builtin_fabs", "fabs",
175 math_function_type, true);
176 define_builtin(BUILT_IN_FABSL, "__builtin_fabsl", "fabsl",
177 math_function_type_long, true);
178 define_builtin(BUILT_IN_FLOOR, "__builtin_floor", "floor",
179 math_function_type, true);
180 define_builtin(BUILT_IN_FLOORL, "__builtin_floorl", "floorl",
181 math_function_type_long, true);
182 define_builtin(BUILT_IN_FMOD, "__builtin_fmod", "fmod",
183 math_function_type_two, true);
184 define_builtin(BUILT_IN_FMODL, "__builtin_fmodl", "fmodl",
185 math_function_type_long_two, true);
186 define_builtin(BUILT_IN_LDEXP, "__builtin_ldexp", "ldexp",
187 build_function_type_list(double_type_node,
188 double_type_node,
189 integer_type_node,
190 NULL_TREE),
191 true);
192 define_builtin(BUILT_IN_LDEXPL, "__builtin_ldexpl", "ldexpl",
193 build_function_type_list(long_double_type_node,
194 long_double_type_node,
195 integer_type_node,
196 NULL_TREE),
197 true);
198 define_builtin(BUILT_IN_LOG, "__builtin_log", "log",
199 math_function_type, true);
200 define_builtin(BUILT_IN_LOGL, "__builtin_logl", "logl",
201 math_function_type_long, true);
202 define_builtin(BUILT_IN_LOG1P, "__builtin_log1p", "log1p",
203 math_function_type, true);
204 define_builtin(BUILT_IN_LOG1PL, "__builtin_log1pl", "log1pl",
205 math_function_type_long, true);
206 define_builtin(BUILT_IN_LOG10, "__builtin_log10", "log10",
207 math_function_type, true);
208 define_builtin(BUILT_IN_LOG10L, "__builtin_log10l", "log10l",
209 math_function_type_long, true);
210 define_builtin(BUILT_IN_LOG2, "__builtin_log2", "log2",
211 math_function_type, true);
212 define_builtin(BUILT_IN_LOG2L, "__builtin_log2l", "log2l",
213 math_function_type_long, true);
214 define_builtin(BUILT_IN_SIN, "__builtin_sin", "sin",
215 math_function_type, true);
216 define_builtin(BUILT_IN_SINL, "__builtin_sinl", "sinl",
217 math_function_type_long, true);
218 define_builtin(BUILT_IN_SQRT, "__builtin_sqrt", "sqrt",
219 math_function_type, true);
220 define_builtin(BUILT_IN_SQRTL, "__builtin_sqrtl", "sqrtl",
221 math_function_type_long, true);
222 define_builtin(BUILT_IN_TAN, "__builtin_tan", "tan",
223 math_function_type, true);
224 define_builtin(BUILT_IN_TANL, "__builtin_tanl", "tanl",
225 math_function_type_long, true);
226 define_builtin(BUILT_IN_TRUNC, "__builtin_trunc", "trunc",
227 math_function_type, true);
228 define_builtin(BUILT_IN_TRUNCL, "__builtin_truncl", "truncl",
229 math_function_type_long, true);
230
231 // We use __builtin_return_address in the thunk we build for
232 // functions which call recover.
233 define_builtin(BUILT_IN_RETURN_ADDRESS, "__builtin_return_address", NULL,
234 build_function_type_list(ptr_type_node,
235 unsigned_type_node,
236 NULL_TREE),
237 false);
238
239 // The compiler uses __builtin_trap for some exception handling
240 // cases.
241 define_builtin(BUILT_IN_TRAP, "__builtin_trap", NULL,
242 build_function_type(void_type_node, void_list_node),
243 false);
244 }
245
246 // Get the name to use for the import control function. If there is a
247 // global function or variable, then we know that that name must be
248 // unique in the link, and we use it as the basis for our name.
249
250 const std::string&
251 Gogo::get_init_fn_name()
252 {
253 if (this->init_fn_name_.empty())
254 {
255 go_assert(this->package_ != NULL);
256 if (this->is_main_package())
257 {
258 // Use a name which the runtime knows.
259 this->init_fn_name_ = "__go_init_main";
260 }
261 else
262 {
263 std::string s = this->pkgpath_symbol();
264 s.append("..import");
265 this->init_fn_name_ = s;
266 }
267 }
268
269 return this->init_fn_name_;
270 }
271
272 // Add statements to INIT_STMT_LIST which run the initialization
273 // functions for imported packages. This is only used for the "main"
274 // package.
275
276 void
277 Gogo::init_imports(tree* init_stmt_list)
278 {
279 go_assert(this->is_main_package());
280
281 if (this->imported_init_fns_.empty())
282 return;
283
284 tree fntype = build_function_type(void_type_node, void_list_node);
285
286 // We must call them in increasing priority order.
287 std::vector<Import_init> v;
288 for (std::set<Import_init>::const_iterator p =
289 this->imported_init_fns_.begin();
290 p != this->imported_init_fns_.end();
291 ++p)
292 v.push_back(*p);
293 std::sort(v.begin(), v.end());
294
295 for (std::vector<Import_init>::const_iterator p = v.begin();
296 p != v.end();
297 ++p)
298 {
299 std::string user_name = p->package_name() + ".init";
300 tree decl = build_decl(UNKNOWN_LOCATION, FUNCTION_DECL,
301 get_identifier_from_string(user_name),
302 fntype);
303 const std::string& init_name(p->init_name());
304 SET_DECL_ASSEMBLER_NAME(decl, get_identifier_from_string(init_name));
305 TREE_PUBLIC(decl) = 1;
306 DECL_EXTERNAL(decl) = 1;
307 append_to_statement_list(build_call_expr(decl, 0), init_stmt_list);
308 }
309 }
310
311 // Register global variables with the garbage collector. We need to
312 // register all variables which can hold a pointer value. They become
313 // roots during the mark phase. We build a struct that is easy to
314 // hook into a list of roots.
315
316 // struct __go_gc_root_list
317 // {
318 // struct __go_gc_root_list* __next;
319 // struct __go_gc_root
320 // {
321 // void* __decl;
322 // size_t __size;
323 // } __roots[];
324 // };
325
326 // The last entry in the roots array has a NULL decl field.
327
328 void
329 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
330 tree* init_stmt_list)
331 {
332 if (var_gc.empty())
333 return;
334
335 size_t count = var_gc.size();
336
337 tree root_type = Gogo::builtin_struct(NULL, "__go_gc_root", NULL_TREE, 2,
338 "__next",
339 ptr_type_node,
340 "__size",
341 sizetype);
342
343 tree index_type = build_index_type(size_int(count));
344 tree array_type = build_array_type(root_type, index_type);
345
346 tree root_list_type = make_node(RECORD_TYPE);
347 root_list_type = Gogo::builtin_struct(NULL, "__go_gc_root_list",
348 root_list_type, 2,
349 "__next",
350 build_pointer_type(root_list_type),
351 "__roots",
352 array_type);
353
354 // Build an initialier for the __roots array.
355
356 VEC(constructor_elt,gc)* roots_init = VEC_alloc(constructor_elt, gc,
357 count + 1);
358
359 size_t i = 0;
360 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
361 p != var_gc.end();
362 ++p, ++i)
363 {
364 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
365
366 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
367 tree field = TYPE_FIELDS(root_type);
368 elt->index = field;
369 Bvariable* bvar = (*p)->get_backend_variable(this, NULL);
370 tree decl = var_to_tree(bvar);
371 go_assert(TREE_CODE(decl) == VAR_DECL);
372 elt->value = build_fold_addr_expr(decl);
373
374 elt = VEC_quick_push(constructor_elt, init, NULL);
375 field = DECL_CHAIN(field);
376 elt->index = field;
377 elt->value = DECL_SIZE_UNIT(decl);
378
379 elt = VEC_quick_push(constructor_elt, roots_init, NULL);
380 elt->index = size_int(i);
381 elt->value = build_constructor(root_type, init);
382 }
383
384 // The list ends with a NULL entry.
385
386 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
387
388 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
389 tree field = TYPE_FIELDS(root_type);
390 elt->index = field;
391 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
392
393 elt = VEC_quick_push(constructor_elt, init, NULL);
394 field = DECL_CHAIN(field);
395 elt->index = field;
396 elt->value = size_zero_node;
397
398 elt = VEC_quick_push(constructor_elt, roots_init, NULL);
399 elt->index = size_int(i);
400 elt->value = build_constructor(root_type, init);
401
402 // Build a constructor for the struct.
403
404 VEC(constructor_elt,gc*) root_list_init = VEC_alloc(constructor_elt, gc, 2);
405
406 elt = VEC_quick_push(constructor_elt, root_list_init, NULL);
407 field = TYPE_FIELDS(root_list_type);
408 elt->index = field;
409 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
410
411 elt = VEC_quick_push(constructor_elt, root_list_init, NULL);
412 field = DECL_CHAIN(field);
413 elt->index = field;
414 elt->value = build_constructor(array_type, roots_init);
415
416 // Build a decl to register.
417
418 tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL,
419 create_tmp_var_name("gc"), root_list_type);
420 DECL_EXTERNAL(decl) = 0;
421 TREE_PUBLIC(decl) = 0;
422 TREE_STATIC(decl) = 1;
423 DECL_ARTIFICIAL(decl) = 1;
424 DECL_INITIAL(decl) = build_constructor(root_list_type, root_list_init);
425 rest_of_decl_compilation(decl, 1, 0);
426
427 static tree register_gc_fndecl;
428 tree call = Gogo::call_builtin(&register_gc_fndecl,
429 Linemap::predeclared_location(),
430 "__go_register_gc_roots",
431 1,
432 void_type_node,
433 build_pointer_type(root_list_type),
434 build_fold_addr_expr(decl));
435 if (call != error_mark_node)
436 append_to_statement_list(call, init_stmt_list);
437 }
438
439 // Build the decl for the initialization function.
440
441 tree
442 Gogo::initialization_function_decl()
443 {
444 // The tedious details of building your own function. There doesn't
445 // seem to be a helper function for this.
446 std::string name = this->package_name() + ".init";
447 tree fndecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL,
448 get_identifier_from_string(name),
449 build_function_type(void_type_node,
450 void_list_node));
451 const std::string& asm_name(this->get_init_fn_name());
452 SET_DECL_ASSEMBLER_NAME(fndecl, get_identifier_from_string(asm_name));
453
454 tree resdecl = build_decl(BUILTINS_LOCATION, RESULT_DECL, NULL_TREE,
455 void_type_node);
456 DECL_ARTIFICIAL(resdecl) = 1;
457 DECL_CONTEXT(resdecl) = fndecl;
458 DECL_RESULT(fndecl) = resdecl;
459
460 TREE_STATIC(fndecl) = 1;
461 TREE_USED(fndecl) = 1;
462 DECL_ARTIFICIAL(fndecl) = 1;
463 TREE_PUBLIC(fndecl) = 1;
464
465 DECL_INITIAL(fndecl) = make_node(BLOCK);
466 TREE_USED(DECL_INITIAL(fndecl)) = 1;
467
468 return fndecl;
469 }
470
471 // Create the magic initialization function. INIT_STMT_LIST is the
472 // code that it needs to run.
473
474 void
475 Gogo::write_initialization_function(tree fndecl, tree init_stmt_list)
476 {
477 // Make sure that we thought we needed an initialization function,
478 // as otherwise we will not have reported it in the export data.
479 go_assert(this->is_main_package() || this->need_init_fn_);
480
481 if (fndecl == NULL_TREE)
482 fndecl = this->initialization_function_decl();
483
484 DECL_SAVED_TREE(fndecl) = init_stmt_list;
485
486 current_function_decl = fndecl;
487 if (DECL_STRUCT_FUNCTION(fndecl) == NULL)
488 push_struct_function(fndecl);
489 else
490 push_cfun(DECL_STRUCT_FUNCTION(fndecl));
491 cfun->function_end_locus = BUILTINS_LOCATION;
492
493 gimplify_function_tree(fndecl);
494
495 cgraph_add_new_function(fndecl, false);
496
497 current_function_decl = NULL_TREE;
498 pop_cfun();
499 }
500
501 // Search for references to VAR in any statements or called functions.
502
503 class Find_var : public Traverse
504 {
505 public:
506 // A hash table we use to avoid looping. The index is the name of a
507 // named object. We only look through objects defined in this
508 // package.
509 typedef Unordered_set(std::string) Seen_objects;
510
511 Find_var(Named_object* var, Seen_objects* seen_objects)
512 : Traverse(traverse_expressions),
513 var_(var), seen_objects_(seen_objects), found_(false)
514 { }
515
516 // Whether the variable was found.
517 bool
518 found() const
519 { return this->found_; }
520
521 int
522 expression(Expression**);
523
524 private:
525 // The variable we are looking for.
526 Named_object* var_;
527 // Names of objects we have already seen.
528 Seen_objects* seen_objects_;
529 // True if the variable was found.
530 bool found_;
531 };
532
533 // See if EXPR refers to VAR, looking through function calls and
534 // variable initializations.
535
536 int
537 Find_var::expression(Expression** pexpr)
538 {
539 Expression* e = *pexpr;
540
541 Var_expression* ve = e->var_expression();
542 if (ve != NULL)
543 {
544 Named_object* v = ve->named_object();
545 if (v == this->var_)
546 {
547 this->found_ = true;
548 return TRAVERSE_EXIT;
549 }
550
551 if (v->is_variable() && v->package() == NULL)
552 {
553 Expression* init = v->var_value()->init();
554 if (init != NULL)
555 {
556 std::pair<Seen_objects::iterator, bool> ins =
557 this->seen_objects_->insert(v->name());
558 if (ins.second)
559 {
560 // This is the first time we have seen this name.
561 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
562 return TRAVERSE_EXIT;
563 }
564 }
565 }
566 }
567
568 // We traverse the code of any function we see. Note that this
569 // means that we will traverse the code of a function whose address
570 // is taken even if it is not called.
571 Func_expression* fe = e->func_expression();
572 if (fe != NULL)
573 {
574 const Named_object* f = fe->named_object();
575 if (f->is_function() && f->package() == NULL)
576 {
577 std::pair<Seen_objects::iterator, bool> ins =
578 this->seen_objects_->insert(f->name());
579 if (ins.second)
580 {
581 // This is the first time we have seen this name.
582 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
583 return TRAVERSE_EXIT;
584 }
585 }
586 }
587
588 return TRAVERSE_CONTINUE;
589 }
590
591 // Return true if EXPR, PREINIT, or DEP refers to VAR.
592
593 static bool
594 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
595 Named_object* var)
596 {
597 Find_var::Seen_objects seen_objects;
598 Find_var find_var(var, &seen_objects);
599 if (expr != NULL)
600 Expression::traverse(&expr, &find_var);
601 if (preinit != NULL)
602 preinit->traverse(&find_var);
603 if (dep != NULL)
604 {
605 Expression* init = dep->var_value()->init();
606 if (init != NULL)
607 Expression::traverse(&init, &find_var);
608 if (dep->var_value()->has_pre_init())
609 dep->var_value()->preinit()->traverse(&find_var);
610 }
611
612 return find_var.found();
613 }
614
615 // Sort variable initializations. If the initialization expression
616 // for variable A refers directly or indirectly to the initialization
617 // expression for variable B, then we must initialize B before A.
618
619 class Var_init
620 {
621 public:
622 Var_init()
623 : var_(NULL), init_(NULL_TREE), waiting_(0)
624 { }
625
626 Var_init(Named_object* var, tree init)
627 : var_(var), init_(init), waiting_(0)
628 { }
629
630 // Return the variable.
631 Named_object*
632 var() const
633 { return this->var_; }
634
635 // Return the initialization expression.
636 tree
637 init() const
638 { return this->init_; }
639
640 // Return the number of variables waiting for this one to be
641 // initialized.
642 size_t
643 waiting() const
644 { return this->waiting_; }
645
646 // Increment the number waiting.
647 void
648 increment_waiting()
649 { ++this->waiting_; }
650
651 private:
652 // The variable being initialized.
653 Named_object* var_;
654 // The initialization expression to run.
655 tree init_;
656 // The number of variables which are waiting for this one.
657 size_t waiting_;
658 };
659
660 typedef std::list<Var_init> Var_inits;
661
662 // Sort the variable initializations. The rule we follow is that we
663 // emit them in the order they appear in the array, except that if the
664 // initialization expression for a variable V1 depends upon another
665 // variable V2 then we initialize V1 after V2.
666
667 static void
668 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
669 {
670 Var_inits ready;
671 while (!var_inits->empty())
672 {
673 Var_inits::iterator p1 = var_inits->begin();
674 Named_object* var = p1->var();
675 Expression* init = var->var_value()->init();
676 Block* preinit = var->var_value()->preinit();
677 Named_object* dep = gogo->var_depends_on(var->var_value());
678
679 // Start walking through the list to see which variables VAR
680 // needs to wait for. We can skip P1->WAITING variables--that
681 // is the number we've already checked.
682 Var_inits::iterator p2 = p1;
683 ++p2;
684 for (size_t i = p1->waiting(); i > 0; --i)
685 ++p2;
686
687 for (; p2 != var_inits->end(); ++p2)
688 {
689 Named_object* p2var = p2->var();
690 if (expression_requires(init, preinit, dep, p2var))
691 {
692 // Check for cycles.
693 if (expression_requires(p2var->var_value()->init(),
694 p2var->var_value()->preinit(),
695 gogo->var_depends_on(p2var->var_value()),
696 var))
697 {
698 error_at(var->location(),
699 ("initialization expressions for %qs and "
700 "%qs depend upon each other"),
701 var->message_name().c_str(),
702 p2var->message_name().c_str());
703 inform(p2->var()->location(), "%qs defined here",
704 p2var->message_name().c_str());
705 p2 = var_inits->end();
706 }
707 else
708 {
709 // We can't emit P1 until P2 is emitted. Move P1.
710 // Note that the WAITING loop always executes at
711 // least once, which is what we want.
712 p2->increment_waiting();
713 Var_inits::iterator p3 = p2;
714 for (size_t i = p2->waiting(); i > 0; --i)
715 ++p3;
716 var_inits->splice(p3, *var_inits, p1);
717 }
718 break;
719 }
720 }
721
722 if (p2 == var_inits->end())
723 {
724 // VAR does not depends upon any other initialization expressions.
725
726 // Check for a loop of VAR on itself. We only do this if
727 // INIT is not NULL and there is no dependency; when INIT is
728 // NULL, it means that PREINIT sets VAR, which we will
729 // interpret as a loop.
730 if (init != NULL && dep == NULL
731 && expression_requires(init, preinit, NULL, var))
732 error_at(var->location(),
733 "initialization expression for %qs depends upon itself",
734 var->message_name().c_str());
735 ready.splice(ready.end(), *var_inits, p1);
736 }
737 }
738
739 // Now READY is the list in the desired initialization order.
740 var_inits->swap(ready);
741 }
742
743 // Write out the global definitions.
744
745 void
746 Gogo::write_globals()
747 {
748 this->convert_named_types();
749 this->build_interface_method_tables();
750
751 Bindings* bindings = this->current_bindings();
752 size_t count_definitions = bindings->size_definitions();
753 size_t count = count_definitions;
754
755 tree* vec = new tree[count];
756
757 tree init_fndecl = NULL_TREE;
758 tree init_stmt_list = NULL_TREE;
759
760 if (this->is_main_package())
761 this->init_imports(&init_stmt_list);
762
763 // A list of variable initializations.
764 Var_inits var_inits;
765
766 // A list of variables which need to be registered with the garbage
767 // collector.
768 std::vector<Named_object*> var_gc;
769 var_gc.reserve(count);
770
771 tree var_init_stmt_list = NULL_TREE;
772 size_t i = 0;
773 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
774 p != bindings->end_definitions();
775 ++p, ++i)
776 {
777 Named_object* no = *p;
778
779 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
780 // There is nothing to do for a package.
781 if (no->is_package())
782 {
783 --i;
784 --count;
785 continue;
786 }
787
788 // There is nothing to do for an object which was imported from
789 // a different package into the global scope.
790 if (no->package() != NULL)
791 {
792 --i;
793 --count;
794 continue;
795 }
796
797 // There is nothing useful we can output for constants which
798 // have ideal or non-integral type.
799 if (no->is_const())
800 {
801 Type* type = no->const_value()->type();
802 if (type == NULL)
803 type = no->const_value()->expr()->type();
804 if (type->is_abstract() || type->integer_type() == NULL)
805 {
806 --i;
807 --count;
808 continue;
809 }
810 }
811
812 if (!no->is_variable())
813 {
814 vec[i] = no->get_tree(this, NULL);
815 if (vec[i] == error_mark_node)
816 {
817 go_assert(saw_errors());
818 --i;
819 --count;
820 continue;
821 }
822 }
823 else
824 {
825 Bvariable* var = no->get_backend_variable(this, NULL);
826 vec[i] = var_to_tree(var);
827 if (vec[i] == error_mark_node)
828 {
829 go_assert(saw_errors());
830 --i;
831 --count;
832 continue;
833 }
834
835 // Check for a sink variable, which may be used to run an
836 // initializer purely for its side effects.
837 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
838
839 tree var_init_tree = NULL_TREE;
840 if (!no->var_value()->has_pre_init())
841 {
842 tree init = no->var_value()->get_init_tree(this, NULL);
843 if (init == error_mark_node)
844 go_assert(saw_errors());
845 else if (init == NULL_TREE)
846 ;
847 else if (TREE_CONSTANT(init))
848 {
849 if (expression_requires(no->var_value()->init(), NULL,
850 this->var_depends_on(no->var_value()),
851 no))
852 error_at(no->location(),
853 "initialization expression for %qs depends "
854 "upon itself",
855 no->message_name().c_str());
856 this->backend()->global_variable_set_init(var,
857 tree_to_expr(init));
858 }
859 else if (is_sink
860 || int_size_in_bytes(TREE_TYPE(init)) == 0
861 || int_size_in_bytes(TREE_TYPE(vec[i])) == 0)
862 var_init_tree = init;
863 else
864 var_init_tree = fold_build2_loc(no->location().gcc_location(),
865 MODIFY_EXPR, void_type_node,
866 vec[i], init);
867 }
868 else
869 {
870 // We are going to create temporary variables which
871 // means that we need an fndecl.
872 if (init_fndecl == NULL_TREE)
873 init_fndecl = this->initialization_function_decl();
874 current_function_decl = init_fndecl;
875 if (DECL_STRUCT_FUNCTION(init_fndecl) == NULL)
876 push_struct_function(init_fndecl);
877 else
878 push_cfun(DECL_STRUCT_FUNCTION(init_fndecl));
879
880 tree var_decl = is_sink ? NULL_TREE : vec[i];
881 var_init_tree = no->var_value()->get_init_block(this, NULL,
882 var_decl);
883
884 current_function_decl = NULL_TREE;
885 pop_cfun();
886 }
887
888 if (var_init_tree != NULL_TREE && var_init_tree != error_mark_node)
889 {
890 if (no->var_value()->init() == NULL
891 && !no->var_value()->has_pre_init())
892 append_to_statement_list(var_init_tree, &var_init_stmt_list);
893 else
894 var_inits.push_back(Var_init(no, var_init_tree));
895 }
896 else if (this->var_depends_on(no->var_value()) != NULL)
897 {
898 // This variable is initialized from something that is
899 // not in its init or preinit. This variable needs to
900 // participate in dependency analysis sorting, in case
901 // some other variable depends on this one.
902 var_inits.push_back(Var_init(no, integer_zero_node));
903 }
904
905 if (!is_sink && no->var_value()->type()->has_pointer())
906 var_gc.push_back(no);
907 }
908 }
909
910 // Register global variables with the garbage collector.
911 this->register_gc_vars(var_gc, &init_stmt_list);
912
913 // Simple variable initializations, after all variables are
914 // registered.
915 append_to_statement_list(var_init_stmt_list, &init_stmt_list);
916
917 // Complex variable initializations, first sorting them into a
918 // workable order.
919 if (!var_inits.empty())
920 {
921 sort_var_inits(this, &var_inits);
922 for (Var_inits::const_iterator p = var_inits.begin();
923 p != var_inits.end();
924 ++p)
925 append_to_statement_list(p->init(), &init_stmt_list);
926 }
927
928 // After all the variables are initialized, call the "init"
929 // functions if there are any.
930 for (std::vector<Named_object*>::const_iterator p =
931 this->init_functions_.begin();
932 p != this->init_functions_.end();
933 ++p)
934 {
935 tree decl = (*p)->get_tree(this, NULL);
936 tree call = build_call_expr(decl, 0);
937 append_to_statement_list(call, &init_stmt_list);
938 }
939
940 // Set up a magic function to do all the initialization actions.
941 // This will be called if this package is imported.
942 if (init_stmt_list != NULL_TREE
943 || this->need_init_fn_
944 || this->is_main_package())
945 this->write_initialization_function(init_fndecl, init_stmt_list);
946
947 // We should not have seen any new bindings created during the
948 // conversion.
949 go_assert(count_definitions == this->current_bindings()->size_definitions());
950
951 // Pass everything back to the middle-end.
952
953 wrapup_global_declarations(vec, count);
954
955 finalize_compilation_unit();
956
957 check_global_declarations(vec, count);
958 emit_debug_global_declarations(vec, count);
959
960 delete[] vec;
961 }
962
963 // Get a tree for the identifier for a named object.
964
965 tree
966 Named_object::get_id(Gogo* gogo)
967 {
968 go_assert(!this->is_variable() && !this->is_result_variable());
969 std::string decl_name;
970 if (this->is_function_declaration()
971 && !this->func_declaration_value()->asm_name().empty())
972 decl_name = this->func_declaration_value()->asm_name();
973 else if (this->is_type()
974 && Linemap::is_predeclared_location(this->type_value()->location()))
975 {
976 // We don't need the package name for builtin types.
977 decl_name = Gogo::unpack_hidden_name(this->name_);
978 }
979 else
980 {
981 std::string package_name;
982 if (this->package_ == NULL)
983 package_name = gogo->package_name();
984 else
985 package_name = this->package_->package_name();
986
987 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
988
989 Function_type* fntype;
990 if (this->is_function())
991 fntype = this->func_value()->type();
992 else if (this->is_function_declaration())
993 fntype = this->func_declaration_value()->type();
994 else
995 fntype = NULL;
996 if (fntype != NULL && fntype->is_method())
997 {
998 decl_name.push_back('.');
999 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
1000 }
1001 }
1002 if (this->is_type())
1003 {
1004 const Named_object* in_function = this->type_value()->in_function();
1005 if (in_function != NULL)
1006 decl_name += '$' + Gogo::unpack_hidden_name(in_function->name());
1007 }
1008 return get_identifier_from_string(decl_name);
1009 }
1010
1011 // Get a tree for a named object.
1012
1013 tree
1014 Named_object::get_tree(Gogo* gogo, Named_object* function)
1015 {
1016 if (this->tree_ != NULL_TREE)
1017 return this->tree_;
1018
1019 tree name;
1020 if (this->classification_ == NAMED_OBJECT_TYPE)
1021 name = NULL_TREE;
1022 else
1023 name = this->get_id(gogo);
1024 tree decl;
1025 switch (this->classification_)
1026 {
1027 case NAMED_OBJECT_CONST:
1028 {
1029 Named_constant* named_constant = this->u_.const_value;
1030 Translate_context subcontext(gogo, function, NULL, NULL);
1031 tree expr_tree = named_constant->expr()->get_tree(&subcontext);
1032 if (expr_tree == error_mark_node)
1033 decl = error_mark_node;
1034 else
1035 {
1036 Type* type = named_constant->type();
1037 if (type != NULL && !type->is_abstract())
1038 {
1039 if (type->is_error())
1040 expr_tree = error_mark_node;
1041 else
1042 {
1043 Btype* btype = type->get_backend(gogo);
1044 expr_tree = fold_convert(type_to_tree(btype), expr_tree);
1045 }
1046 }
1047 if (expr_tree == error_mark_node)
1048 decl = error_mark_node;
1049 else if (INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
1050 {
1051 decl = build_decl(named_constant->location().gcc_location(),
1052 CONST_DECL, name, TREE_TYPE(expr_tree));
1053 DECL_INITIAL(decl) = expr_tree;
1054 TREE_CONSTANT(decl) = 1;
1055 TREE_READONLY(decl) = 1;
1056 }
1057 else
1058 {
1059 // A CONST_DECL is only for an enum constant, so we
1060 // shouldn't use for non-integral types. Instead we
1061 // just return the constant itself, rather than a
1062 // decl.
1063 decl = expr_tree;
1064 }
1065 }
1066 }
1067 break;
1068
1069 case NAMED_OBJECT_TYPE:
1070 {
1071 Named_type* named_type = this->u_.type_value;
1072 tree type_tree = type_to_tree(named_type->get_backend(gogo));
1073 if (type_tree == error_mark_node)
1074 decl = error_mark_node;
1075 else
1076 {
1077 decl = TYPE_NAME(type_tree);
1078 go_assert(decl != NULL_TREE);
1079
1080 // We need to produce a type descriptor for every named
1081 // type, and for a pointer to every named type, since
1082 // other files or packages might refer to them. We need
1083 // to do this even for hidden types, because they might
1084 // still be returned by some function. Simply calling the
1085 // type_descriptor method is enough to create the type
1086 // descriptor, even though we don't do anything with it.
1087 if (this->package_ == NULL)
1088 {
1089 named_type->
1090 type_descriptor_pointer(gogo,
1091 Linemap::predeclared_location());
1092 Type* pn = Type::make_pointer_type(named_type);
1093 pn->type_descriptor_pointer(gogo,
1094 Linemap::predeclared_location());
1095 }
1096 }
1097 }
1098 break;
1099
1100 case NAMED_OBJECT_TYPE_DECLARATION:
1101 error("reference to undefined type %qs",
1102 this->message_name().c_str());
1103 return error_mark_node;
1104
1105 case NAMED_OBJECT_VAR:
1106 case NAMED_OBJECT_RESULT_VAR:
1107 case NAMED_OBJECT_SINK:
1108 go_unreachable();
1109
1110 case NAMED_OBJECT_FUNC:
1111 {
1112 Function* func = this->u_.func_value;
1113 decl = func->get_or_make_decl(gogo, this, name);
1114 if (decl != error_mark_node)
1115 {
1116 if (func->block() != NULL)
1117 {
1118 if (DECL_STRUCT_FUNCTION(decl) == NULL)
1119 push_struct_function(decl);
1120 else
1121 push_cfun(DECL_STRUCT_FUNCTION(decl));
1122
1123 cfun->function_end_locus =
1124 func->block()->end_location().gcc_location();
1125
1126 current_function_decl = decl;
1127
1128 func->build_tree(gogo, this);
1129
1130 gimplify_function_tree(decl);
1131
1132 cgraph_finalize_function(decl, true);
1133
1134 current_function_decl = NULL_TREE;
1135 pop_cfun();
1136 }
1137 }
1138 }
1139 break;
1140
1141 case NAMED_OBJECT_ERRONEOUS:
1142 decl = error_mark_node;
1143 break;
1144
1145 default:
1146 go_unreachable();
1147 }
1148
1149 if (TREE_TYPE(decl) == error_mark_node)
1150 decl = error_mark_node;
1151
1152 tree ret = decl;
1153
1154 this->tree_ = ret;
1155
1156 if (ret != error_mark_node)
1157 go_preserve_from_gc(ret);
1158
1159 return ret;
1160 }
1161
1162 // Get the initial value of a variable as a tree. This does not
1163 // consider whether the variable is in the heap--it returns the
1164 // initial value as though it were always stored in the stack.
1165
1166 tree
1167 Variable::get_init_tree(Gogo* gogo, Named_object* function)
1168 {
1169 go_assert(this->preinit_ == NULL);
1170 if (this->init_ == NULL)
1171 {
1172 go_assert(!this->is_parameter_);
1173 if (this->is_global_ || this->is_in_heap())
1174 return NULL;
1175 Btype* btype = this->type_->get_backend(gogo);
1176 return expr_to_tree(gogo->backend()->zero_expression(btype));
1177 }
1178 else
1179 {
1180 Translate_context context(gogo, function, NULL, NULL);
1181 tree rhs_tree = this->init_->get_tree(&context);
1182 return Expression::convert_for_assignment(&context, this->type(),
1183 this->init_->type(),
1184 rhs_tree, this->location());
1185 }
1186 }
1187
1188 // Get the initial value of a variable when a block is required.
1189 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
1190
1191 tree
1192 Variable::get_init_block(Gogo* gogo, Named_object* function, tree var_decl)
1193 {
1194 go_assert(this->preinit_ != NULL);
1195
1196 // We want to add the variable assignment to the end of the preinit
1197 // block. The preinit block may have a TRY_FINALLY_EXPR and a
1198 // TRY_CATCH_EXPR; if it does, we want to add to the end of the
1199 // regular statements.
1200
1201 Translate_context context(gogo, function, NULL, NULL);
1202 Bblock* bblock = this->preinit_->get_backend(&context);
1203 tree block_tree = block_to_tree(bblock);
1204 if (block_tree == error_mark_node)
1205 return error_mark_node;
1206 go_assert(TREE_CODE(block_tree) == BIND_EXPR);
1207 tree statements = BIND_EXPR_BODY(block_tree);
1208 while (statements != NULL_TREE
1209 && (TREE_CODE(statements) == TRY_FINALLY_EXPR
1210 || TREE_CODE(statements) == TRY_CATCH_EXPR))
1211 statements = TREE_OPERAND(statements, 0);
1212
1213 // It's possible to have pre-init statements without an initializer
1214 // if the pre-init statements set the variable.
1215 if (this->init_ != NULL)
1216 {
1217 tree rhs_tree = this->init_->get_tree(&context);
1218 if (rhs_tree == error_mark_node)
1219 return error_mark_node;
1220 if (var_decl == NULL_TREE)
1221 append_to_statement_list(rhs_tree, &statements);
1222 else
1223 {
1224 tree val = Expression::convert_for_assignment(&context, this->type(),
1225 this->init_->type(),
1226 rhs_tree,
1227 this->location());
1228 if (val == error_mark_node)
1229 return error_mark_node;
1230 tree set = fold_build2_loc(this->location().gcc_location(),
1231 MODIFY_EXPR, void_type_node, var_decl,
1232 val);
1233 append_to_statement_list(set, &statements);
1234 }
1235 }
1236
1237 return block_tree;
1238 }
1239
1240 // Get a tree for a function decl.
1241
1242 tree
1243 Function::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1244 {
1245 if (this->fndecl_ == NULL_TREE)
1246 {
1247 tree functype = type_to_tree(this->type_->get_backend(gogo));
1248 if (functype == error_mark_node)
1249 this->fndecl_ = error_mark_node;
1250 else
1251 {
1252 // The type of a function comes back as a pointer, but we
1253 // want the real function type for a function declaration.
1254 go_assert(POINTER_TYPE_P(functype));
1255 functype = TREE_TYPE(functype);
1256 tree decl = build_decl(this->location().gcc_location(), FUNCTION_DECL,
1257 id, functype);
1258
1259 this->fndecl_ = decl;
1260
1261 if (no->package() != NULL)
1262 ;
1263 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
1264 ;
1265 else if (Gogo::unpack_hidden_name(no->name()) == "init"
1266 && !this->type_->is_method())
1267 ;
1268 else if (Gogo::unpack_hidden_name(no->name()) == "main"
1269 && gogo->is_main_package())
1270 TREE_PUBLIC(decl) = 1;
1271 // Methods have to be public even if they are hidden because
1272 // they can be pulled into type descriptors when using
1273 // anonymous fields.
1274 else if (!Gogo::is_hidden_name(no->name())
1275 || this->type_->is_method())
1276 {
1277 TREE_PUBLIC(decl) = 1;
1278 std::string asm_name = gogo->pkgpath_symbol();
1279 asm_name.append(1, '.');
1280 asm_name.append(Gogo::unpack_hidden_name(no->name()));
1281 if (this->type_->is_method())
1282 {
1283 asm_name.append(1, '.');
1284 Type* rtype = this->type_->receiver()->type();
1285 asm_name.append(rtype->mangled_name(gogo));
1286 }
1287 SET_DECL_ASSEMBLER_NAME(decl,
1288 get_identifier_from_string(asm_name));
1289 }
1290
1291 // Why do we have to do this in the frontend?
1292 tree restype = TREE_TYPE(functype);
1293 tree resdecl =
1294 build_decl(this->location().gcc_location(), RESULT_DECL, NULL_TREE,
1295 restype);
1296 DECL_ARTIFICIAL(resdecl) = 1;
1297 DECL_IGNORED_P(resdecl) = 1;
1298 DECL_CONTEXT(resdecl) = decl;
1299 DECL_RESULT(decl) = resdecl;
1300
1301 if (this->enclosing_ != NULL)
1302 DECL_STATIC_CHAIN(decl) = 1;
1303
1304 // If a function calls the predeclared recover function, we
1305 // can't inline it, because recover behaves differently in a
1306 // function passed directly to defer. If this is a recover
1307 // thunk that we built to test whether a function can be
1308 // recovered, we can't inline it, because that will mess up
1309 // our return address comparison.
1310 if (this->calls_recover_ || this->is_recover_thunk_)
1311 DECL_UNINLINABLE(decl) = 1;
1312
1313 // If this is a thunk created to call a function which calls
1314 // the predeclared recover function, we need to disable
1315 // stack splitting for the thunk.
1316 if (this->is_recover_thunk_)
1317 {
1318 tree attr = get_identifier("__no_split_stack__");
1319 DECL_ATTRIBUTES(decl) = tree_cons(attr, NULL_TREE, NULL_TREE);
1320 }
1321
1322 go_preserve_from_gc(decl);
1323
1324 if (this->closure_var_ != NULL)
1325 {
1326 push_struct_function(decl);
1327
1328 Bvariable* bvar = this->closure_var_->get_backend_variable(gogo,
1329 no);
1330 tree closure_decl = var_to_tree(bvar);
1331 if (closure_decl == error_mark_node)
1332 this->fndecl_ = error_mark_node;
1333 else
1334 {
1335 DECL_ARTIFICIAL(closure_decl) = 1;
1336 DECL_IGNORED_P(closure_decl) = 1;
1337 TREE_USED(closure_decl) = 1;
1338 DECL_ARG_TYPE(closure_decl) = TREE_TYPE(closure_decl);
1339 TREE_READONLY(closure_decl) = 1;
1340
1341 DECL_STRUCT_FUNCTION(decl)->static_chain_decl = closure_decl;
1342 }
1343
1344 pop_cfun();
1345 }
1346 }
1347 }
1348 return this->fndecl_;
1349 }
1350
1351 // Get a tree for a function declaration.
1352
1353 tree
1354 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1355 {
1356 if (this->fndecl_ == NULL_TREE)
1357 {
1358 // Let Go code use an asm declaration to pick up a builtin
1359 // function.
1360 if (!this->asm_name_.empty())
1361 {
1362 std::map<std::string, tree>::const_iterator p =
1363 builtin_functions.find(this->asm_name_);
1364 if (p != builtin_functions.end())
1365 {
1366 this->fndecl_ = p->second;
1367 return this->fndecl_;
1368 }
1369 }
1370
1371 tree functype = type_to_tree(this->fntype_->get_backend(gogo));
1372 tree decl;
1373 if (functype == error_mark_node)
1374 decl = error_mark_node;
1375 else
1376 {
1377 // The type of a function comes back as a pointer, but we
1378 // want the real function type for a function declaration.
1379 go_assert(POINTER_TYPE_P(functype));
1380 functype = TREE_TYPE(functype);
1381 decl = build_decl(this->location().gcc_location(), FUNCTION_DECL, id,
1382 functype);
1383 TREE_PUBLIC(decl) = 1;
1384 DECL_EXTERNAL(decl) = 1;
1385
1386 if (this->asm_name_.empty())
1387 {
1388 std::string asm_name = (no->package() == NULL
1389 ? gogo->pkgpath_symbol()
1390 : no->package()->pkgpath_symbol());
1391 asm_name.append(1, '.');
1392 asm_name.append(Gogo::unpack_hidden_name(no->name()));
1393 if (this->fntype_->is_method())
1394 {
1395 asm_name.append(1, '.');
1396 Type* rtype = this->fntype_->receiver()->type();
1397 asm_name.append(rtype->mangled_name(gogo));
1398 }
1399 SET_DECL_ASSEMBLER_NAME(decl,
1400 get_identifier_from_string(asm_name));
1401 }
1402 }
1403 this->fndecl_ = decl;
1404 go_preserve_from_gc(decl);
1405 }
1406 return this->fndecl_;
1407 }
1408
1409 // We always pass the receiver to a method as a pointer. If the
1410 // receiver is actually declared as a non-pointer type, then we copy
1411 // the value into a local variable, so that it has the right type. In
1412 // this function we create the real PARM_DECL to use, and set
1413 // DEC_INITIAL of the var_decl to be the value passed in.
1414
1415 tree
1416 Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl)
1417 {
1418 if (var_decl == error_mark_node)
1419 return error_mark_node;
1420 go_assert(TREE_CODE(var_decl) == VAR_DECL);
1421 tree val_type = TREE_TYPE(var_decl);
1422 bool is_in_heap = no->var_value()->is_in_heap();
1423 if (is_in_heap)
1424 {
1425 go_assert(POINTER_TYPE_P(val_type));
1426 val_type = TREE_TYPE(val_type);
1427 }
1428
1429 source_location loc = DECL_SOURCE_LOCATION(var_decl);
1430 std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1431 name += ".pointer";
1432 tree id = get_identifier_from_string(name);
1433 tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type));
1434 DECL_CONTEXT(parm_decl) = current_function_decl;
1435 DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl);
1436
1437 go_assert(DECL_INITIAL(var_decl) == NULL_TREE);
1438 tree init = build_fold_indirect_ref_loc(loc, parm_decl);
1439
1440 if (is_in_heap)
1441 {
1442 tree size = TYPE_SIZE_UNIT(val_type);
1443 tree space = gogo->allocate_memory(no->var_value()->type(), size,
1444 no->location());
1445 space = save_expr(space);
1446 space = fold_convert(build_pointer_type(val_type), space);
1447 tree spaceref = build_fold_indirect_ref_loc(no->location().gcc_location(),
1448 space);
1449 TREE_THIS_NOTRAP(spaceref) = 1;
1450 tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node,
1451 spaceref, init);
1452 init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), set, space);
1453 }
1454
1455 DECL_INITIAL(var_decl) = init;
1456
1457 return parm_decl;
1458 }
1459
1460 // If we take the address of a parameter, then we need to copy it into
1461 // the heap. We will access it as a local variable via an
1462 // indirection.
1463
1464 tree
1465 Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree var_decl)
1466 {
1467 if (var_decl == error_mark_node)
1468 return error_mark_node;
1469 go_assert(TREE_CODE(var_decl) == VAR_DECL);
1470 Location loc(DECL_SOURCE_LOCATION(var_decl));
1471
1472 std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1473 name += ".param";
1474 tree id = get_identifier_from_string(name);
1475
1476 tree type = TREE_TYPE(var_decl);
1477 go_assert(POINTER_TYPE_P(type));
1478 type = TREE_TYPE(type);
1479
1480 tree parm_decl = build_decl(loc.gcc_location(), PARM_DECL, id, type);
1481 DECL_CONTEXT(parm_decl) = current_function_decl;
1482 DECL_ARG_TYPE(parm_decl) = type;
1483
1484 tree size = TYPE_SIZE_UNIT(type);
1485 tree space = gogo->allocate_memory(no->var_value()->type(), size, loc);
1486 space = save_expr(space);
1487 space = fold_convert(TREE_TYPE(var_decl), space);
1488 tree spaceref = build_fold_indirect_ref_loc(loc.gcc_location(), space);
1489 TREE_THIS_NOTRAP(spaceref) = 1;
1490 tree init = build2(COMPOUND_EXPR, TREE_TYPE(space),
1491 build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl),
1492 space);
1493 DECL_INITIAL(var_decl) = init;
1494
1495 return parm_decl;
1496 }
1497
1498 // Get a tree for function code.
1499
1500 void
1501 Function::build_tree(Gogo* gogo, Named_object* named_function)
1502 {
1503 tree fndecl = this->fndecl_;
1504 go_assert(fndecl != NULL_TREE);
1505
1506 tree params = NULL_TREE;
1507 tree* pp = &params;
1508
1509 tree declare_vars = NULL_TREE;
1510 for (Bindings::const_definitions_iterator p =
1511 this->block_->bindings()->begin_definitions();
1512 p != this->block_->bindings()->end_definitions();
1513 ++p)
1514 {
1515 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
1516 {
1517 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
1518 *pp = var_to_tree(bvar);
1519
1520 // We always pass the receiver to a method as a pointer. If
1521 // the receiver is declared as a non-pointer type, then we
1522 // copy the value into a local variable.
1523 if ((*p)->var_value()->is_receiver()
1524 && (*p)->var_value()->type()->points_to() == NULL)
1525 {
1526 tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp);
1527 tree var = *pp;
1528 if (var != error_mark_node)
1529 {
1530 go_assert(TREE_CODE(var) == VAR_DECL);
1531 DECL_CHAIN(var) = declare_vars;
1532 declare_vars = var;
1533 }
1534 *pp = parm_decl;
1535 }
1536 else if ((*p)->var_value()->is_in_heap())
1537 {
1538 // If we take the address of a parameter, then we need
1539 // to copy it into the heap.
1540 tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp);
1541 tree var = *pp;
1542 if (var != error_mark_node)
1543 {
1544 go_assert(TREE_CODE(var) == VAR_DECL);
1545 DECL_CHAIN(var) = declare_vars;
1546 declare_vars = var;
1547 }
1548 *pp = parm_decl;
1549 }
1550
1551 if (*pp != error_mark_node)
1552 {
1553 go_assert(TREE_CODE(*pp) == PARM_DECL);
1554 pp = &DECL_CHAIN(*pp);
1555 }
1556 }
1557 else if ((*p)->is_result_variable())
1558 {
1559 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
1560 tree var_decl = var_to_tree(bvar);
1561
1562 Type* type = (*p)->result_var_value()->type();
1563 tree init;
1564 if (!(*p)->result_var_value()->is_in_heap())
1565 {
1566 Btype* btype = type->get_backend(gogo);
1567 init = expr_to_tree(gogo->backend()->zero_expression(btype));
1568 }
1569 else
1570 {
1571 Location loc = (*p)->location();
1572 tree type_tree = type_to_tree(type->get_backend(gogo));
1573 tree space = gogo->allocate_memory(type,
1574 TYPE_SIZE_UNIT(type_tree),
1575 loc);
1576 tree ptr_type_tree = build_pointer_type(type_tree);
1577 init = fold_convert_loc(loc.gcc_location(), ptr_type_tree, space);
1578 }
1579
1580 if (var_decl != error_mark_node)
1581 {
1582 go_assert(TREE_CODE(var_decl) == VAR_DECL);
1583 DECL_INITIAL(var_decl) = init;
1584 DECL_CHAIN(var_decl) = declare_vars;
1585 declare_vars = var_decl;
1586 }
1587 }
1588 }
1589 *pp = NULL_TREE;
1590
1591 DECL_ARGUMENTS(fndecl) = params;
1592
1593 if (this->block_ != NULL)
1594 {
1595 go_assert(DECL_INITIAL(fndecl) == NULL_TREE);
1596
1597 // Declare variables if necessary.
1598 tree bind = NULL_TREE;
1599 tree defer_init = NULL_TREE;
1600 if (declare_vars != NULL_TREE || this->defer_stack_ != NULL)
1601 {
1602 tree block = make_node(BLOCK);
1603 BLOCK_SUPERCONTEXT(block) = fndecl;
1604 DECL_INITIAL(fndecl) = block;
1605 BLOCK_VARS(block) = declare_vars;
1606 TREE_USED(block) = 1;
1607
1608 bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block),
1609 NULL_TREE, block);
1610 TREE_SIDE_EFFECTS(bind) = 1;
1611
1612 if (this->defer_stack_ != NULL)
1613 {
1614 Translate_context dcontext(gogo, named_function, this->block_,
1615 tree_to_block(bind));
1616 Bstatement* bdi = this->defer_stack_->get_backend(&dcontext);
1617 defer_init = stat_to_tree(bdi);
1618 }
1619 }
1620
1621 // Build the trees for all the statements in the function.
1622 Translate_context context(gogo, named_function, NULL, NULL);
1623 Bblock* bblock = this->block_->get_backend(&context);
1624 tree code = block_to_tree(bblock);
1625
1626 tree init = NULL_TREE;
1627 tree except = NULL_TREE;
1628 tree fini = NULL_TREE;
1629
1630 // Initialize variables if necessary.
1631 for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v))
1632 {
1633 tree dv = build1(DECL_EXPR, void_type_node, v);
1634 SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v));
1635 append_to_statement_list(dv, &init);
1636 }
1637
1638 // If we have a defer stack, initialize it at the start of a
1639 // function.
1640 if (defer_init != NULL_TREE && defer_init != error_mark_node)
1641 {
1642 SET_EXPR_LOCATION(defer_init,
1643 this->block_->start_location().gcc_location());
1644 append_to_statement_list(defer_init, &init);
1645
1646 // Clean up the defer stack when we leave the function.
1647 this->build_defer_wrapper(gogo, named_function, &except, &fini);
1648 }
1649
1650 if (code != NULL_TREE && code != error_mark_node)
1651 {
1652 if (init != NULL_TREE)
1653 code = build2(COMPOUND_EXPR, void_type_node, init, code);
1654 if (except != NULL_TREE)
1655 code = build2(TRY_CATCH_EXPR, void_type_node, code,
1656 build2(CATCH_EXPR, void_type_node, NULL, except));
1657 if (fini != NULL_TREE)
1658 code = build2(TRY_FINALLY_EXPR, void_type_node, code, fini);
1659 }
1660
1661 // Stick the code into the block we built for the receiver, if
1662 // we built on.
1663 if (bind != NULL_TREE && code != NULL_TREE && code != error_mark_node)
1664 {
1665 BIND_EXPR_BODY(bind) = code;
1666 code = bind;
1667 }
1668
1669 DECL_SAVED_TREE(fndecl) = code;
1670 }
1671 }
1672
1673 // Build the wrappers around function code needed if the function has
1674 // any defer statements. This sets *EXCEPT to an exception handler
1675 // and *FINI to a finally handler.
1676
1677 void
1678 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
1679 tree *except, tree *fini)
1680 {
1681 Location end_loc = this->block_->end_location();
1682
1683 // Add an exception handler. This is used if a panic occurs. Its
1684 // purpose is to stop the stack unwinding if a deferred function
1685 // calls recover. There are more details in
1686 // libgo/runtime/go-unwind.c.
1687
1688 tree stmt_list = NULL_TREE;
1689
1690 Expression* call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
1691 this->defer_stack(end_loc));
1692 Translate_context context(gogo, named_function, NULL, NULL);
1693 tree call_tree = call->get_tree(&context);
1694 if (call_tree != error_mark_node)
1695 append_to_statement_list(call_tree, &stmt_list);
1696
1697 tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list);
1698 tree set;
1699 if (retval == NULL_TREE)
1700 set = NULL_TREE;
1701 else
1702 set = fold_build2_loc(end_loc.gcc_location(), MODIFY_EXPR, void_type_node,
1703 DECL_RESULT(this->fndecl_), retval);
1704 tree ret_stmt = fold_build1_loc(end_loc.gcc_location(), RETURN_EXPR,
1705 void_type_node, set);
1706 append_to_statement_list(ret_stmt, &stmt_list);
1707
1708 go_assert(*except == NULL_TREE);
1709 *except = stmt_list;
1710
1711 // Add some finally code to run the defer functions. This is used
1712 // both in the normal case, when no panic occurs, and also if a
1713 // panic occurs to run any further defer functions. Of course, it
1714 // is possible for a defer function to call panic which should be
1715 // caught by another defer function. To handle that we use a loop.
1716 // finish:
1717 // try { __go_undefer(); } catch { __go_check_defer(); goto finish; }
1718 // if (return values are named) return named_vals;
1719
1720 stmt_list = NULL;
1721
1722 tree label = create_artificial_label(end_loc.gcc_location());
1723 tree define_label = fold_build1_loc(end_loc.gcc_location(), LABEL_EXPR,
1724 void_type_node, label);
1725 append_to_statement_list(define_label, &stmt_list);
1726
1727 call = Runtime::make_call(Runtime::UNDEFER, end_loc, 1,
1728 this->defer_stack(end_loc));
1729 tree undefer = call->get_tree(&context);
1730
1731 call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
1732 this->defer_stack(end_loc));
1733 tree defer = call->get_tree(&context);
1734
1735 if (undefer == error_mark_node || defer == error_mark_node)
1736 return;
1737
1738 tree jump = fold_build1_loc(end_loc.gcc_location(), GOTO_EXPR, void_type_node,
1739 label);
1740 tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump);
1741 catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body);
1742 tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body);
1743
1744 append_to_statement_list(try_catch, &stmt_list);
1745
1746 if (this->type_->results() != NULL
1747 && !this->type_->results()->empty()
1748 && !this->type_->results()->front().name().empty())
1749 {
1750 // If the result variables are named, and we are returning from
1751 // this function rather than panicing through it, we need to
1752 // return them again, because they might have been changed by a
1753 // defer function. The runtime routines set the defer_stack
1754 // variable to true if we are returning from this function.
1755 retval = this->return_value(gogo, named_function, end_loc,
1756 &stmt_list);
1757 set = fold_build2_loc(end_loc.gcc_location(), MODIFY_EXPR, void_type_node,
1758 DECL_RESULT(this->fndecl_), retval);
1759 ret_stmt = fold_build1_loc(end_loc.gcc_location(), RETURN_EXPR,
1760 void_type_node, set);
1761
1762 Expression* ref =
1763 Expression::make_temporary_reference(this->defer_stack_, end_loc);
1764 tree tref = ref->get_tree(&context);
1765 tree s = build3_loc(end_loc.gcc_location(), COND_EXPR, void_type_node,
1766 tref, ret_stmt, NULL_TREE);
1767
1768 append_to_statement_list(s, &stmt_list);
1769
1770 }
1771
1772 go_assert(*fini == NULL_TREE);
1773 *fini = stmt_list;
1774 }
1775
1776 // Return the value to assign to DECL_RESULT(this->fndecl_). This may
1777 // also add statements to STMT_LIST, which need to be executed before
1778 // the assignment. This is used for a return statement with no
1779 // explicit values.
1780
1781 tree
1782 Function::return_value(Gogo* gogo, Named_object* named_function,
1783 Location location, tree* stmt_list) const
1784 {
1785 const Typed_identifier_list* results = this->type_->results();
1786 if (results == NULL || results->empty())
1787 return NULL_TREE;
1788
1789 go_assert(this->results_ != NULL);
1790 if (this->results_->size() != results->size())
1791 {
1792 go_assert(saw_errors());
1793 return error_mark_node;
1794 }
1795
1796 tree retval;
1797 if (results->size() == 1)
1798 {
1799 Bvariable* bvar =
1800 this->results_->front()->get_backend_variable(gogo,
1801 named_function);
1802 tree ret = var_to_tree(bvar);
1803 if (this->results_->front()->result_var_value()->is_in_heap())
1804 ret = build_fold_indirect_ref_loc(location.gcc_location(), ret);
1805 return ret;
1806 }
1807 else
1808 {
1809 tree rettype = TREE_TYPE(DECL_RESULT(this->fndecl_));
1810 retval = create_tmp_var(rettype, "RESULT");
1811 tree field = TYPE_FIELDS(rettype);
1812 int index = 0;
1813 for (Typed_identifier_list::const_iterator pr = results->begin();
1814 pr != results->end();
1815 ++pr, ++index, field = DECL_CHAIN(field))
1816 {
1817 go_assert(field != NULL);
1818 Named_object* no = (*this->results_)[index];
1819 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
1820 tree val = var_to_tree(bvar);
1821 if (no->result_var_value()->is_in_heap())
1822 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
1823 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
1824 void_type_node,
1825 build3(COMPONENT_REF, TREE_TYPE(field),
1826 retval, field, NULL_TREE),
1827 val);
1828 append_to_statement_list(set, stmt_list);
1829 }
1830 return retval;
1831 }
1832 }
1833
1834 // Return the integer type to use for a size.
1835
1836 GO_EXTERN_C
1837 tree
1838 go_type_for_size(unsigned int bits, int unsignedp)
1839 {
1840 const char* name;
1841 switch (bits)
1842 {
1843 case 8:
1844 name = unsignedp ? "uint8" : "int8";
1845 break;
1846 case 16:
1847 name = unsignedp ? "uint16" : "int16";
1848 break;
1849 case 32:
1850 name = unsignedp ? "uint32" : "int32";
1851 break;
1852 case 64:
1853 name = unsignedp ? "uint64" : "int64";
1854 break;
1855 default:
1856 if (bits == POINTER_SIZE && unsignedp)
1857 name = "uintptr";
1858 else
1859 return NULL_TREE;
1860 }
1861 Type* type = Type::lookup_integer_type(name);
1862 return type_to_tree(type->get_backend(go_get_gogo()));
1863 }
1864
1865 // Return the type to use for a mode.
1866
1867 GO_EXTERN_C
1868 tree
1869 go_type_for_mode(enum machine_mode mode, int unsignedp)
1870 {
1871 // FIXME: This static_cast should be in machmode.h.
1872 enum mode_class mc = static_cast<enum mode_class>(GET_MODE_CLASS(mode));
1873 if (mc == MODE_INT)
1874 return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp);
1875 else if (mc == MODE_FLOAT)
1876 {
1877 Type* type;
1878 switch (GET_MODE_BITSIZE (mode))
1879 {
1880 case 32:
1881 type = Type::lookup_float_type("float32");
1882 break;
1883 case 64:
1884 type = Type::lookup_float_type("float64");
1885 break;
1886 default:
1887 // We have to check for long double in order to support
1888 // i386 excess precision.
1889 if (mode == TYPE_MODE(long_double_type_node))
1890 return long_double_type_node;
1891 return NULL_TREE;
1892 }
1893 return type_to_tree(type->get_backend(go_get_gogo()));
1894 }
1895 else if (mc == MODE_COMPLEX_FLOAT)
1896 {
1897 Type *type;
1898 switch (GET_MODE_BITSIZE (mode))
1899 {
1900 case 64:
1901 type = Type::lookup_complex_type("complex64");
1902 break;
1903 case 128:
1904 type = Type::lookup_complex_type("complex128");
1905 break;
1906 default:
1907 // We have to check for long double in order to support
1908 // i386 excess precision.
1909 if (mode == TYPE_MODE(complex_long_double_type_node))
1910 return complex_long_double_type_node;
1911 return NULL_TREE;
1912 }
1913 return type_to_tree(type->get_backend(go_get_gogo()));
1914 }
1915 else
1916 return NULL_TREE;
1917 }
1918
1919 // Return a tree which allocates SIZE bytes which will holds value of
1920 // type TYPE.
1921
1922 tree
1923 Gogo::allocate_memory(Type* type, tree size, Location location)
1924 {
1925 // If the package imports unsafe, then it may play games with
1926 // pointers that look like integers.
1927 if (this->imported_unsafe_ || type->has_pointer())
1928 {
1929 static tree new_fndecl;
1930 return Gogo::call_builtin(&new_fndecl,
1931 location,
1932 "__go_new",
1933 1,
1934 ptr_type_node,
1935 sizetype,
1936 size);
1937 }
1938 else
1939 {
1940 static tree new_nopointers_fndecl;
1941 return Gogo::call_builtin(&new_nopointers_fndecl,
1942 location,
1943 "__go_new_nopointers",
1944 1,
1945 ptr_type_node,
1946 sizetype,
1947 size);
1948 }
1949 }
1950
1951 // Build a builtin struct with a list of fields. The name is
1952 // STRUCT_NAME. STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE
1953 // node; this exists so that the struct can have fields which point to
1954 // itself. If PTYPE is not NULL, store the result in *PTYPE. There
1955 // are NFIELDS fields. Each field is a name (a const char*) followed
1956 // by a type (a tree).
1957
1958 tree
1959 Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type,
1960 int nfields, ...)
1961 {
1962 if (ptype != NULL && *ptype != NULL_TREE)
1963 return *ptype;
1964
1965 va_list ap;
1966 va_start(ap, nfields);
1967
1968 tree fields = NULL_TREE;
1969 for (int i = 0; i < nfields; ++i)
1970 {
1971 const char* field_name = va_arg(ap, const char*);
1972 tree type = va_arg(ap, tree);
1973 if (type == error_mark_node)
1974 {
1975 if (ptype != NULL)
1976 *ptype = error_mark_node;
1977 return error_mark_node;
1978 }
1979 tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL,
1980 get_identifier(field_name), type);
1981 DECL_CHAIN(field) = fields;
1982 fields = field;
1983 }
1984
1985 va_end(ap);
1986
1987 if (struct_type == NULL_TREE)
1988 struct_type = make_node(RECORD_TYPE);
1989 finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE);
1990
1991 if (ptype != NULL)
1992 {
1993 go_preserve_from_gc(struct_type);
1994 *ptype = struct_type;
1995 }
1996
1997 return struct_type;
1998 }
1999
2000 // Return a type to use for pointer to const char for a string.
2001
2002 tree
2003 Gogo::const_char_pointer_type_tree()
2004 {
2005 static tree type;
2006 if (type == NULL_TREE)
2007 {
2008 tree const_char_type = build_qualified_type(unsigned_char_type_node,
2009 TYPE_QUAL_CONST);
2010 type = build_pointer_type(const_char_type);
2011 go_preserve_from_gc(type);
2012 }
2013 return type;
2014 }
2015
2016 // Return a tree for a string constant.
2017
2018 tree
2019 Gogo::string_constant_tree(const std::string& val)
2020 {
2021 tree index_type = build_index_type(size_int(val.length()));
2022 tree const_char_type = build_qualified_type(unsigned_char_type_node,
2023 TYPE_QUAL_CONST);
2024 tree string_type = build_array_type(const_char_type, index_type);
2025 string_type = build_variant_type_copy(string_type);
2026 TYPE_STRING_FLAG(string_type) = 1;
2027 tree string_val = build_string(val.length(), val.data());
2028 TREE_TYPE(string_val) = string_type;
2029 return string_val;
2030 }
2031
2032 // Return a tree for a Go string constant.
2033
2034 tree
2035 Gogo::go_string_constant_tree(const std::string& val)
2036 {
2037 tree string_type = type_to_tree(Type::make_string_type()->get_backend(this));
2038
2039 VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2);
2040
2041 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
2042 tree field = TYPE_FIELDS(string_type);
2043 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0);
2044 elt->index = field;
2045 tree str = Gogo::string_constant_tree(val);
2046 elt->value = fold_convert(TREE_TYPE(field),
2047 build_fold_addr_expr(str));
2048
2049 elt = VEC_quick_push(constructor_elt, init, NULL);
2050 field = DECL_CHAIN(field);
2051 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0);
2052 elt->index = field;
2053 elt->value = build_int_cst_type(TREE_TYPE(field), val.length());
2054
2055 tree constructor = build_constructor(string_type, init);
2056 TREE_READONLY(constructor) = 1;
2057 TREE_CONSTANT(constructor) = 1;
2058
2059 return constructor;
2060 }
2061
2062 // Return a tree for a pointer to a Go string constant. This is only
2063 // used for type descriptors, so we return a pointer to a constant
2064 // decl.
2065
2066 tree
2067 Gogo::ptr_go_string_constant_tree(const std::string& val)
2068 {
2069 tree pval = this->go_string_constant_tree(val);
2070
2071 tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL,
2072 create_tmp_var_name("SP"), TREE_TYPE(pval));
2073 DECL_EXTERNAL(decl) = 0;
2074 TREE_PUBLIC(decl) = 0;
2075 TREE_USED(decl) = 1;
2076 TREE_READONLY(decl) = 1;
2077 TREE_CONSTANT(decl) = 1;
2078 TREE_STATIC(decl) = 1;
2079 DECL_ARTIFICIAL(decl) = 1;
2080 DECL_INITIAL(decl) = pval;
2081 rest_of_decl_compilation(decl, 1, 0);
2082
2083 return build_fold_addr_expr(decl);
2084 }
2085
2086 // Build a constructor for a slice. SLICE_TYPE_TREE is the type of
2087 // the slice. VALUES is the value pointer and COUNT is the number of
2088 // entries. If CAPACITY is not NULL, it is the capacity; otherwise
2089 // the capacity and the count are the same.
2090
2091 tree
2092 Gogo::slice_constructor(tree slice_type_tree, tree values, tree count,
2093 tree capacity)
2094 {
2095 go_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE);
2096
2097 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
2098
2099 tree field = TYPE_FIELDS(slice_type_tree);
2100 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
2101 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
2102 elt->index = field;
2103 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field))
2104 == TYPE_MAIN_VARIANT(TREE_TYPE(values)));
2105 elt->value = values;
2106
2107 count = fold_convert(sizetype, count);
2108 if (capacity == NULL_TREE)
2109 {
2110 count = save_expr(count);
2111 capacity = count;
2112 }
2113
2114 field = DECL_CHAIN(field);
2115 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
2116 elt = VEC_quick_push(constructor_elt, init, NULL);
2117 elt->index = field;
2118 elt->value = fold_convert(TREE_TYPE(field), count);
2119
2120 field = DECL_CHAIN(field);
2121 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
2122 elt = VEC_quick_push(constructor_elt, init, NULL);
2123 elt->index = field;
2124 elt->value = fold_convert(TREE_TYPE(field), capacity);
2125
2126 return build_constructor(slice_type_tree, init);
2127 }
2128
2129 // Build an interface method table for a type: a list of function
2130 // pointers, one for each interface method. This is used for
2131 // interfaces.
2132
2133 tree
2134 Gogo::interface_method_table_for_type(const Interface_type* interface,
2135 Named_type* type,
2136 bool is_pointer)
2137 {
2138 const Typed_identifier_list* interface_methods = interface->methods();
2139 go_assert(!interface_methods->empty());
2140
2141 std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_")
2142 + interface->mangled_name(this)
2143 + "__"
2144 + type->mangled_name(this));
2145
2146 tree id = get_identifier_from_string(mangled_name);
2147
2148 // See whether this interface has any hidden methods.
2149 bool has_hidden_methods = false;
2150 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2151 p != interface_methods->end();
2152 ++p)
2153 {
2154 if (Gogo::is_hidden_name(p->name()))
2155 {
2156 has_hidden_methods = true;
2157 break;
2158 }
2159 }
2160
2161 // We already know that the named type is convertible to the
2162 // interface. If the interface has hidden methods, and the named
2163 // type is defined in a different package, then the interface
2164 // conversion table will be defined by that other package.
2165 if (has_hidden_methods && type->named_object()->package() != NULL)
2166 {
2167 tree array_type = build_array_type(const_ptr_type_node, NULL);
2168 tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2169 TREE_READONLY(decl) = 1;
2170 TREE_CONSTANT(decl) = 1;
2171 TREE_PUBLIC(decl) = 1;
2172 DECL_EXTERNAL(decl) = 1;
2173 go_preserve_from_gc(decl);
2174 return decl;
2175 }
2176
2177 size_t count = interface_methods->size();
2178 VEC(constructor_elt, gc)* pointers = VEC_alloc(constructor_elt, gc,
2179 count + 1);
2180
2181 // The first element is the type descriptor.
2182 constructor_elt* elt = VEC_quick_push(constructor_elt, pointers, NULL);
2183 elt->index = size_zero_node;
2184 Type* td_type;
2185 if (!is_pointer)
2186 td_type = type;
2187 else
2188 td_type = Type::make_pointer_type(type);
2189 tree tdp = td_type->type_descriptor_pointer(this,
2190 Linemap::predeclared_location());
2191 elt->value = fold_convert(const_ptr_type_node, tdp);
2192
2193 size_t i = 1;
2194 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2195 p != interface_methods->end();
2196 ++p, ++i)
2197 {
2198 bool is_ambiguous;
2199 Method* m = type->method_function(p->name(), &is_ambiguous);
2200 go_assert(m != NULL);
2201
2202 Named_object* no = m->named_object();
2203
2204 tree fnid = no->get_id(this);
2205
2206 tree fndecl;
2207 if (no->is_function())
2208 fndecl = no->func_value()->get_or_make_decl(this, no, fnid);
2209 else if (no->is_function_declaration())
2210 fndecl = no->func_declaration_value()->get_or_make_decl(this, no,
2211 fnid);
2212 else
2213 go_unreachable();
2214 fndecl = build_fold_addr_expr(fndecl);
2215
2216 elt = VEC_quick_push(constructor_elt, pointers, NULL);
2217 elt->index = size_int(i);
2218 elt->value = fold_convert(const_ptr_type_node, fndecl);
2219 }
2220 go_assert(i == count + 1);
2221
2222 tree array_type = build_array_type(const_ptr_type_node,
2223 build_index_type(size_int(count)));
2224 tree constructor = build_constructor(array_type, pointers);
2225
2226 tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2227 TREE_STATIC(decl) = 1;
2228 TREE_USED(decl) = 1;
2229 TREE_READONLY(decl) = 1;
2230 TREE_CONSTANT(decl) = 1;
2231 DECL_INITIAL(decl) = constructor;
2232
2233 // If the interface type has hidden methods, then this is the only
2234 // definition of the table. Otherwise it is a comdat table which
2235 // may be defined in multiple packages.
2236 if (has_hidden_methods)
2237 TREE_PUBLIC(decl) = 1;
2238 else
2239 {
2240 make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2241 resolve_unique_section(decl, 1, 0);
2242 }
2243
2244 rest_of_decl_compilation(decl, 1, 0);
2245
2246 go_preserve_from_gc(decl);
2247
2248 return decl;
2249 }
2250
2251 // Mark a function as a builtin library function.
2252
2253 void
2254 Gogo::mark_fndecl_as_builtin_library(tree fndecl)
2255 {
2256 DECL_EXTERNAL(fndecl) = 1;
2257 TREE_PUBLIC(fndecl) = 1;
2258 DECL_ARTIFICIAL(fndecl) = 1;
2259 TREE_NOTHROW(fndecl) = 1;
2260 DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT;
2261 DECL_VISIBILITY_SPECIFIED(fndecl) = 1;
2262 }
2263
2264 // Build a call to a builtin function.
2265
2266 tree
2267 Gogo::call_builtin(tree* pdecl, Location location, const char* name,
2268 int nargs, tree rettype, ...)
2269 {
2270 if (rettype == error_mark_node)
2271 return error_mark_node;
2272
2273 tree* types = new tree[nargs];
2274 tree* args = new tree[nargs];
2275
2276 va_list ap;
2277 va_start(ap, rettype);
2278 for (int i = 0; i < nargs; ++i)
2279 {
2280 types[i] = va_arg(ap, tree);
2281 args[i] = va_arg(ap, tree);
2282 if (types[i] == error_mark_node || args[i] == error_mark_node)
2283 {
2284 delete[] types;
2285 delete[] args;
2286 return error_mark_node;
2287 }
2288 }
2289 va_end(ap);
2290
2291 if (*pdecl == NULL_TREE)
2292 {
2293 tree fnid = get_identifier(name);
2294
2295 tree argtypes = NULL_TREE;
2296 tree* pp = &argtypes;
2297 for (int i = 0; i < nargs; ++i)
2298 {
2299 *pp = tree_cons(NULL_TREE, types[i], NULL_TREE);
2300 pp = &TREE_CHAIN(*pp);
2301 }
2302 *pp = void_list_node;
2303
2304 tree fntype = build_function_type(rettype, argtypes);
2305
2306 *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype);
2307 Gogo::mark_fndecl_as_builtin_library(*pdecl);
2308 go_preserve_from_gc(*pdecl);
2309 }
2310
2311 tree fnptr = build_fold_addr_expr(*pdecl);
2312 if (CAN_HAVE_LOCATION_P(fnptr))
2313 SET_EXPR_LOCATION(fnptr, location.gcc_location());
2314
2315 tree ret = build_call_array(rettype, fnptr, nargs, args);
2316 SET_EXPR_LOCATION(ret, location.gcc_location());
2317
2318 delete[] types;
2319 delete[] args;
2320
2321 return ret;
2322 }
2323
2324 // Build a call to the runtime error function.
2325
2326 tree
2327 Gogo::runtime_error(int code, Location location)
2328 {
2329 static tree runtime_error_fndecl;
2330 tree ret = Gogo::call_builtin(&runtime_error_fndecl,
2331 location,
2332 "__go_runtime_error",
2333 1,
2334 void_type_node,
2335 integer_type_node,
2336 build_int_cst(integer_type_node, code));
2337 if (ret == error_mark_node)
2338 return error_mark_node;
2339 // The runtime error function panics and does not return.
2340 TREE_NOTHROW(runtime_error_fndecl) = 0;
2341 TREE_THIS_VOLATILE(runtime_error_fndecl) = 1;
2342 return ret;
2343 }
2344
2345 // Return a tree for receiving a value of type TYPE_TREE on CHANNEL.
2346 // TYPE_DESCRIPTOR_TREE is the channel's type descriptor. This does a
2347 // blocking receive and returns the value read from the channel.
2348
2349 tree
2350 Gogo::receive_from_channel(tree type_tree, tree type_descriptor_tree,
2351 tree channel, Location location)
2352 {
2353 if (type_tree == error_mark_node || channel == error_mark_node)
2354 return error_mark_node;
2355
2356 if (int_size_in_bytes(type_tree) <= 8
2357 && !AGGREGATE_TYPE_P(type_tree)
2358 && !FLOAT_TYPE_P(type_tree))
2359 {
2360 static tree receive_small_fndecl;
2361 tree call = Gogo::call_builtin(&receive_small_fndecl,
2362 location,
2363 "__go_receive_small",
2364 2,
2365 uint64_type_node,
2366 TREE_TYPE(type_descriptor_tree),
2367 type_descriptor_tree,
2368 ptr_type_node,
2369 channel);
2370 if (call == error_mark_node)
2371 return error_mark_node;
2372 // This can panic if there are too many operations on a closed
2373 // channel.
2374 TREE_NOTHROW(receive_small_fndecl) = 0;
2375 int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree));
2376 tree int_type_tree = go_type_for_size(bitsize, 1);
2377 return fold_convert_loc(location.gcc_location(), type_tree,
2378 fold_convert_loc(location.gcc_location(),
2379 int_type_tree, call));
2380 }
2381 else
2382 {
2383 tree tmp = create_tmp_var(type_tree, get_name(type_tree));
2384 DECL_IGNORED_P(tmp) = 0;
2385 TREE_ADDRESSABLE(tmp) = 1;
2386 tree make_tmp = build1(DECL_EXPR, void_type_node, tmp);
2387 SET_EXPR_LOCATION(make_tmp, location.gcc_location());
2388 tree tmpaddr = build_fold_addr_expr(tmp);
2389 tmpaddr = fold_convert(ptr_type_node, tmpaddr);
2390 static tree receive_big_fndecl;
2391 tree call = Gogo::call_builtin(&receive_big_fndecl,
2392 location,
2393 "__go_receive_big",
2394 3,
2395 void_type_node,
2396 TREE_TYPE(type_descriptor_tree),
2397 type_descriptor_tree,
2398 ptr_type_node,
2399 channel,
2400 ptr_type_node,
2401 tmpaddr);
2402 if (call == error_mark_node)
2403 return error_mark_node;
2404 // This can panic if there are too many operations on a closed
2405 // channel.
2406 TREE_NOTHROW(receive_big_fndecl) = 0;
2407 return build2(COMPOUND_EXPR, type_tree, make_tmp,
2408 build2(COMPOUND_EXPR, type_tree, call, tmp));
2409 }
2410 }
2411
2412 // Return the type of a function trampoline. This is like
2413 // get_trampoline_type in tree-nested.c.
2414
2415 tree
2416 Gogo::trampoline_type_tree()
2417 {
2418 static tree type_tree;
2419 if (type_tree == NULL_TREE)
2420 {
2421 unsigned int size;
2422 unsigned int align;
2423 go_trampoline_info(&size, &align);
2424 tree t = build_index_type(build_int_cst(integer_type_node, size - 1));
2425 t = build_array_type(char_type_node, t);
2426
2427 type_tree = Gogo::builtin_struct(NULL, "__go_trampoline", NULL_TREE, 1,
2428 "__data", t);
2429 t = TYPE_FIELDS(type_tree);
2430 DECL_ALIGN(t) = align;
2431 DECL_USER_ALIGN(t) = 1;
2432
2433 go_preserve_from_gc(type_tree);
2434 }
2435 return type_tree;
2436 }
2437
2438 // Make a trampoline which calls FNADDR passing CLOSURE.
2439
2440 tree
2441 Gogo::make_trampoline(tree fnaddr, tree closure, Location location)
2442 {
2443 tree trampoline_type = Gogo::trampoline_type_tree();
2444 tree trampoline_size = TYPE_SIZE_UNIT(trampoline_type);
2445
2446 closure = save_expr(closure);
2447
2448 // We allocate the trampoline using a special function which will
2449 // mark it as executable.
2450 static tree trampoline_fndecl;
2451 tree x = Gogo::call_builtin(&trampoline_fndecl,
2452 location,
2453 "__go_allocate_trampoline",
2454 2,
2455 ptr_type_node,
2456 size_type_node,
2457 trampoline_size,
2458 ptr_type_node,
2459 fold_convert_loc(location.gcc_location(),
2460 ptr_type_node, closure));
2461 if (x == error_mark_node)
2462 return error_mark_node;
2463
2464 x = save_expr(x);
2465
2466 // Initialize the trampoline.
2467 tree calldecl = builtin_decl_implicit(BUILT_IN_INIT_HEAP_TRAMPOLINE);
2468 tree ini = build_call_expr(calldecl, 3, x, fnaddr, closure);
2469
2470 // On some targets the trampoline address needs to be adjusted. For
2471 // example, when compiling in Thumb mode on the ARM, the address
2472 // needs to have the low bit set.
2473 x = build_call_expr(builtin_decl_explicit(BUILT_IN_ADJUST_TRAMPOLINE), 1, x);
2474 x = fold_convert(TREE_TYPE(fnaddr), x);
2475
2476 return build2(COMPOUND_EXPR, TREE_TYPE(x), ini, x);
2477 }