OSDN Git Service

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