OSDN Git Service

Rewrite conversion of named types to backend representation.
[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 "gogo.h"
35
36 // Whether we have seen any errors.
37
38 bool
39 saw_errors()
40 {
41   return errorcount != 0 || sorrycount != 0;
42 }
43
44 // A helper function.
45
46 static inline tree
47 get_identifier_from_string(const std::string& str)
48 {
49   return get_identifier_with_length(str.data(), str.length());
50 }
51
52 // Builtin functions.
53
54 static std::map<std::string, tree> builtin_functions;
55
56 // Define a builtin function.  BCODE is the builtin function code
57 // defined by builtins.def.  NAME is the name of the builtin function.
58 // LIBNAME is the name of the corresponding library function, and is
59 // NULL if there isn't one.  FNTYPE is the type of the function.
60 // CONST_P is true if the function has the const attribute.
61
62 static void
63 define_builtin(built_in_function bcode, const char* name, const char* libname,
64                tree fntype, bool const_p)
65 {
66   tree decl = add_builtin_function(name, fntype, bcode, BUILT_IN_NORMAL,
67                                    libname, NULL_TREE);
68   if (const_p)
69     TREE_READONLY(decl) = 1;
70   built_in_decls[bcode] = decl;
71   implicit_built_in_decls[bcode] = decl;
72   builtin_functions[name] = decl;
73   if (libname != NULL)
74     {
75       decl = add_builtin_function(libname, fntype, bcode, BUILT_IN_NORMAL,
76                                   NULL, NULL_TREE);
77       if (const_p)
78         TREE_READONLY(decl) = 1;
79       builtin_functions[libname] = decl;
80     }
81 }
82
83 // Create trees for implicit builtin functions.
84
85 void
86 Gogo::define_builtin_function_trees()
87 {
88   /* We need to define the fetch_and_add functions, since we use them
89      for ++ and --.  */
90   tree t = go_type_for_size(BITS_PER_UNIT, 1);
91   tree p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
92   define_builtin(BUILT_IN_ADD_AND_FETCH_1, "__sync_fetch_and_add_1", NULL,
93                  build_function_type_list(t, p, t, NULL_TREE), false);
94
95   t = go_type_for_size(BITS_PER_UNIT * 2, 1);
96   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
97   define_builtin (BUILT_IN_ADD_AND_FETCH_2, "__sync_fetch_and_add_2", NULL,
98                   build_function_type_list(t, p, t, NULL_TREE), false);
99
100   t = go_type_for_size(BITS_PER_UNIT * 4, 1);
101   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
102   define_builtin(BUILT_IN_ADD_AND_FETCH_4, "__sync_fetch_and_add_4", NULL,
103                  build_function_type_list(t, p, t, NULL_TREE), false);
104
105   t = go_type_for_size(BITS_PER_UNIT * 8, 1);
106   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
107   define_builtin(BUILT_IN_ADD_AND_FETCH_8, "__sync_fetch_and_add_8", NULL,
108                  build_function_type_list(t, p, t, NULL_TREE), false);
109
110   // We use __builtin_expect for magic import functions.
111   define_builtin(BUILT_IN_EXPECT, "__builtin_expect", NULL,
112                  build_function_type_list(long_integer_type_node,
113                                           long_integer_type_node,
114                                           long_integer_type_node,
115                                           NULL_TREE),
116                  true);
117
118   // We use __builtin_memmove for the predeclared copy function.
119   define_builtin(BUILT_IN_MEMMOVE, "__builtin_memmove", "memmove",
120                  build_function_type_list(ptr_type_node,
121                                           ptr_type_node,
122                                           const_ptr_type_node,
123                                           size_type_node,
124                                           NULL_TREE),
125                  false);
126
127   // We provide sqrt for the math library.
128   define_builtin(BUILT_IN_SQRT, "__builtin_sqrt", "sqrt",
129                  build_function_type_list(double_type_node,
130                                           double_type_node,
131                                           NULL_TREE),
132                  true);
133   define_builtin(BUILT_IN_SQRTL, "__builtin_sqrtl", "sqrtl",
134                  build_function_type_list(long_double_type_node,
135                                           long_double_type_node,
136                                           NULL_TREE),
137                  true);
138
139   // We use __builtin_return_address in the thunk we build for
140   // functions which call recover.
141   define_builtin(BUILT_IN_RETURN_ADDRESS, "__builtin_return_address", NULL,
142                  build_function_type_list(ptr_type_node,
143                                           unsigned_type_node,
144                                           NULL_TREE),
145                  false);
146
147   // The compiler uses __builtin_trap for some exception handling
148   // cases.
149   define_builtin(BUILT_IN_TRAP, "__builtin_trap", NULL,
150                  build_function_type(void_type_node, void_list_node),
151                  false);
152 }
153
154 // Get the name to use for the import control function.  If there is a
155 // global function or variable, then we know that that name must be
156 // unique in the link, and we use it as the basis for our name.
157
158 const std::string&
159 Gogo::get_init_fn_name()
160 {
161   if (this->init_fn_name_.empty())
162     {
163       gcc_assert(this->package_ != NULL);
164       if (this->is_main_package())
165         {
166           // Use a name which the runtime knows.
167           this->init_fn_name_ = "__go_init_main";
168         }
169       else
170         {
171           std::string s = this->unique_prefix();
172           s.append(1, '.');
173           s.append(this->package_name());
174           s.append("..import");
175           this->init_fn_name_ = s;
176         }
177     }
178
179   return this->init_fn_name_;
180 }
181
182 // Add statements to INIT_STMT_LIST which run the initialization
183 // functions for imported packages.  This is only used for the "main"
184 // package.
185
186 void
187 Gogo::init_imports(tree* init_stmt_list)
188 {
189   gcc_assert(this->is_main_package());
190
191   if (this->imported_init_fns_.empty())
192     return;
193
194   tree fntype = build_function_type(void_type_node, void_list_node);
195
196   // We must call them in increasing priority order.
197   std::vector<Import_init> v;
198   for (std::set<Import_init>::const_iterator p =
199          this->imported_init_fns_.begin();
200        p != this->imported_init_fns_.end();
201        ++p)
202     v.push_back(*p);
203   std::sort(v.begin(), v.end());
204
205   for (std::vector<Import_init>::const_iterator p = v.begin();
206        p != v.end();
207        ++p)
208     {
209       std::string user_name = p->package_name() + ".init";
210       tree decl = build_decl(UNKNOWN_LOCATION, FUNCTION_DECL,
211                              get_identifier_from_string(user_name),
212                              fntype);
213       const std::string& init_name(p->init_name());
214       SET_DECL_ASSEMBLER_NAME(decl, get_identifier_from_string(init_name));
215       TREE_PUBLIC(decl) = 1;
216       DECL_EXTERNAL(decl) = 1;
217       append_to_statement_list(build_call_expr(decl, 0), init_stmt_list);
218     }
219 }
220
221 // Register global variables with the garbage collector.  We need to
222 // register all variables which can hold a pointer value.  They become
223 // roots during the mark phase.  We build a struct that is easy to
224 // hook into a list of roots.
225
226 // struct __go_gc_root_list
227 // {
228 //   struct __go_gc_root_list* __next;
229 //   struct __go_gc_root
230 //   {
231 //     void* __decl;
232 //     size_t __size;
233 //   } __roots[];
234 // };
235
236 // The last entry in the roots array has a NULL decl field.
237
238 void
239 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
240                        tree* init_stmt_list)
241 {
242   if (var_gc.empty())
243     return;
244
245   size_t count = var_gc.size();
246
247   tree root_type = Gogo::builtin_struct(NULL, "__go_gc_root", NULL_TREE, 2,
248                                         "__next",
249                                         ptr_type_node,
250                                         "__size",
251                                         sizetype);
252
253   tree index_type = build_index_type(size_int(count));
254   tree array_type = build_array_type(root_type, index_type);
255
256   tree root_list_type = make_node(RECORD_TYPE);
257   root_list_type = Gogo::builtin_struct(NULL, "__go_gc_root_list",
258                                         root_list_type, 2,
259                                         "__next",
260                                         build_pointer_type(root_list_type),
261                                         "__roots",
262                                         array_type);
263
264   // Build an initialier for the __roots array.
265
266   VEC(constructor_elt,gc)* roots_init = VEC_alloc(constructor_elt, gc,
267                                                   count + 1);
268
269   size_t i = 0;
270   for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
271        p != var_gc.end();
272        ++p, ++i)
273     {
274       VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
275
276       constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
277       tree field = TYPE_FIELDS(root_type);
278       elt->index = field;
279       tree decl = (*p)->get_tree(this, NULL);
280       gcc_assert(TREE_CODE(decl) == VAR_DECL);
281       elt->value = build_fold_addr_expr(decl);
282
283       elt = VEC_quick_push(constructor_elt, init, NULL);
284       field = DECL_CHAIN(field);
285       elt->index = field;
286       elt->value = DECL_SIZE_UNIT(decl);
287
288       elt = VEC_quick_push(constructor_elt, roots_init, NULL);
289       elt->index = size_int(i);
290       elt->value = build_constructor(root_type, init);
291     }
292
293   // The list ends with a NULL entry.
294
295   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
296
297   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
298   tree field = TYPE_FIELDS(root_type);
299   elt->index = field;
300   elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
301
302   elt = VEC_quick_push(constructor_elt, init, NULL);
303   field = DECL_CHAIN(field);
304   elt->index = field;
305   elt->value = size_zero_node;
306
307   elt = VEC_quick_push(constructor_elt, roots_init, NULL);
308   elt->index = size_int(i);
309   elt->value = build_constructor(root_type, init);
310
311   // Build a constructor for the struct.
312
313   VEC(constructor_elt,gc*) root_list_init = VEC_alloc(constructor_elt, gc, 2);
314
315   elt = VEC_quick_push(constructor_elt, root_list_init, NULL);
316   field = TYPE_FIELDS(root_list_type);
317   elt->index = field;
318   elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
319
320   elt = VEC_quick_push(constructor_elt, root_list_init, NULL);
321   field = DECL_CHAIN(field);
322   elt->index = field;
323   elt->value = build_constructor(array_type, roots_init);
324
325   // Build a decl to register.
326
327   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL,
328                          create_tmp_var_name("gc"), root_list_type);
329   DECL_EXTERNAL(decl) = 0;
330   TREE_PUBLIC(decl) = 0;
331   TREE_STATIC(decl) = 1;
332   DECL_ARTIFICIAL(decl) = 1;
333   DECL_INITIAL(decl) = build_constructor(root_list_type, root_list_init);
334   rest_of_decl_compilation(decl, 1, 0);
335
336   static tree register_gc_fndecl;
337   tree call = Gogo::call_builtin(&register_gc_fndecl, BUILTINS_LOCATION,
338                                  "__go_register_gc_roots",
339                                  1,
340                                  void_type_node,
341                                  build_pointer_type(root_list_type),
342                                  build_fold_addr_expr(decl));
343   if (call != error_mark_node)
344     append_to_statement_list(call, init_stmt_list);
345 }
346
347 // Build the decl for the initialization function.
348
349 tree
350 Gogo::initialization_function_decl()
351 {
352   // The tedious details of building your own function.  There doesn't
353   // seem to be a helper function for this.
354   std::string name = this->package_name() + ".init";
355   tree fndecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL,
356                            get_identifier_from_string(name),
357                            build_function_type(void_type_node,
358                                                void_list_node));
359   const std::string& asm_name(this->get_init_fn_name());
360   SET_DECL_ASSEMBLER_NAME(fndecl, get_identifier_from_string(asm_name));
361
362   tree resdecl = build_decl(BUILTINS_LOCATION, RESULT_DECL, NULL_TREE,
363                             void_type_node);
364   DECL_ARTIFICIAL(resdecl) = 1;
365   DECL_CONTEXT(resdecl) = fndecl;
366   DECL_RESULT(fndecl) = resdecl;
367
368   TREE_STATIC(fndecl) = 1;
369   TREE_USED(fndecl) = 1;
370   DECL_ARTIFICIAL(fndecl) = 1;
371   TREE_PUBLIC(fndecl) = 1;
372
373   DECL_INITIAL(fndecl) = make_node(BLOCK);
374   TREE_USED(DECL_INITIAL(fndecl)) = 1;
375
376   return fndecl;
377 }
378
379 // Create the magic initialization function.  INIT_STMT_LIST is the
380 // code that it needs to run.
381
382 void
383 Gogo::write_initialization_function(tree fndecl, tree init_stmt_list)
384 {
385   // Make sure that we thought we needed an initialization function,
386   // as otherwise we will not have reported it in the export data.
387   gcc_assert(this->is_main_package() || this->need_init_fn_);
388
389   if (fndecl == NULL_TREE)
390     fndecl = this->initialization_function_decl();
391
392   DECL_SAVED_TREE(fndecl) = init_stmt_list;
393
394   current_function_decl = fndecl;
395   if (DECL_STRUCT_FUNCTION(fndecl) == NULL)
396     push_struct_function(fndecl);
397   else
398     push_cfun(DECL_STRUCT_FUNCTION(fndecl));
399   cfun->function_end_locus = BUILTINS_LOCATION;
400
401   gimplify_function_tree(fndecl);
402
403   cgraph_add_new_function(fndecl, false);
404   cgraph_mark_needed_node(cgraph_node(fndecl));
405
406   current_function_decl = NULL_TREE;
407   pop_cfun();
408 }
409
410 // Search for references to VAR in any statements or called functions.
411
412 class Find_var : public Traverse
413 {
414  public:
415   // A hash table we use to avoid looping.  The index is the name of a
416   // named object.  We only look through objects defined in this
417   // package.
418   typedef Unordered_set(std::string) Seen_objects;
419
420   Find_var(Named_object* var, Seen_objects* seen_objects)
421     : Traverse(traverse_expressions),
422       var_(var), seen_objects_(seen_objects), found_(false)
423   { }
424
425   // Whether the variable was found.
426   bool
427   found() const
428   { return this->found_; }
429
430   int
431   expression(Expression**);
432
433  private:
434   // The variable we are looking for.
435   Named_object* var_;
436   // Names of objects we have already seen.
437   Seen_objects* seen_objects_;
438   // True if the variable was found.
439   bool found_;
440 };
441
442 // See if EXPR refers to VAR, looking through function calls and
443 // variable initializations.
444
445 int
446 Find_var::expression(Expression** pexpr)
447 {
448   Expression* e = *pexpr;
449
450   Var_expression* ve = e->var_expression();
451   if (ve != NULL)
452     {
453       Named_object* v = ve->named_object();
454       if (v == this->var_)
455         {
456           this->found_ = true;
457           return TRAVERSE_EXIT;
458         }
459
460       if (v->is_variable() && v->package() == NULL)
461         {
462           Expression* init = v->var_value()->init();
463           if (init != NULL)
464             {
465               std::pair<Seen_objects::iterator, bool> ins =
466                 this->seen_objects_->insert(v->name());
467               if (ins.second)
468                 {
469                   // This is the first time we have seen this name.
470                   if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
471                     return TRAVERSE_EXIT;
472                 }
473             }
474         }
475     }
476
477   // We traverse the code of any function we see.  Note that this
478   // means that we will traverse the code of a function whose address
479   // is taken even if it is not called.
480   Func_expression* fe = e->func_expression();
481   if (fe != NULL)
482     {
483       const Named_object* f = fe->named_object();
484       if (f->is_function() && f->package() == NULL)
485         {
486           std::pair<Seen_objects::iterator, bool> ins =
487             this->seen_objects_->insert(f->name());
488           if (ins.second)
489             {
490               // This is the first time we have seen this name.
491               if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
492                 return TRAVERSE_EXIT;
493             }
494         }
495     }
496
497   return TRAVERSE_CONTINUE;
498 }
499
500 // Return true if EXPR refers to VAR.
501
502 static bool
503 expression_requires(Expression* expr, Block* preinit, Named_object* var)
504 {
505   Find_var::Seen_objects seen_objects;
506   Find_var find_var(var, &seen_objects);
507   if (expr != NULL)
508     Expression::traverse(&expr, &find_var);
509   if (preinit != NULL)
510     preinit->traverse(&find_var);
511   
512   return find_var.found();
513 }
514
515 // Sort variable initializations.  If the initialization expression
516 // for variable A refers directly or indirectly to the initialization
517 // expression for variable B, then we must initialize B before A.
518
519 class Var_init
520 {
521  public:
522   Var_init()
523     : var_(NULL), init_(NULL_TREE), waiting_(0)
524   { }
525
526   Var_init(Named_object* var, tree init)
527     : var_(var), init_(init), waiting_(0)
528   { }
529
530   // Return the variable.
531   Named_object*
532   var() const
533   { return this->var_; }
534
535   // Return the initialization expression.
536   tree
537   init() const
538   { return this->init_; }
539
540   // Return the number of variables waiting for this one to be
541   // initialized.
542   size_t
543   waiting() const
544   { return this->waiting_; }
545
546   // Increment the number waiting.
547   void
548   increment_waiting()
549   { ++this->waiting_; }
550
551  private:
552   // The variable being initialized.
553   Named_object* var_;
554   // The initialization expression to run.
555   tree init_;
556   // The number of variables which are waiting for this one.
557   size_t waiting_;
558 };
559
560 typedef std::list<Var_init> Var_inits;
561
562 // Sort the variable initializations.  The rule we follow is that we
563 // emit them in the order they appear in the array, except that if the
564 // initialization expression for a variable V1 depends upon another
565 // variable V2 then we initialize V1 after V2.
566
567 static void
568 sort_var_inits(Var_inits* var_inits)
569 {
570   Var_inits ready;
571   while (!var_inits->empty())
572     {
573       Var_inits::iterator p1 = var_inits->begin();
574       Named_object* var = p1->var();
575       Expression* init = var->var_value()->init();
576       Block* preinit = var->var_value()->preinit();
577
578       // Start walking through the list to see which variables VAR
579       // needs to wait for.  We can skip P1->WAITING variables--that
580       // is the number we've already checked.
581       Var_inits::iterator p2 = p1;
582       ++p2;
583       for (size_t i = p1->waiting(); i > 0; --i)
584         ++p2;
585
586       for (; p2 != var_inits->end(); ++p2)
587         {
588           if (expression_requires(init, preinit, p2->var()))
589             {
590               // Check for cycles.
591               if (expression_requires(p2->var()->var_value()->init(),
592                                       p2->var()->var_value()->preinit(),
593                                       var))
594                 {
595                   error_at(var->location(),
596                            ("initialization expressions for %qs and "
597                             "%qs depend upon each other"),
598                            var->message_name().c_str(),
599                            p2->var()->message_name().c_str());
600                   inform(p2->var()->location(), "%qs defined here",
601                          p2->var()->message_name().c_str());
602                   p2 = var_inits->end();
603                 }
604               else
605                 {
606                   // We can't emit P1 until P2 is emitted.  Move P1.
607                   // Note that the WAITING loop always executes at
608                   // least once, which is what we want.
609                   p2->increment_waiting();
610                   Var_inits::iterator p3 = p2;
611                   for (size_t i = p2->waiting(); i > 0; --i)
612                     ++p3;
613                   var_inits->splice(p3, *var_inits, p1);
614                 }
615               break;
616             }
617         }
618
619       if (p2 == var_inits->end())
620         {
621           // VAR does not depends upon any other initialization expressions.
622
623           // Check for a loop of VAR on itself.  We only do this if
624           // INIT is not NULL; when INIT is NULL, it means that
625           // PREINIT sets VAR, which we will interpret as a loop.
626           if (init != NULL && expression_requires(init, preinit, var))
627             error_at(var->location(),
628                      "initialization expression for %qs depends upon itself",
629                      var->message_name().c_str());
630           ready.splice(ready.end(), *var_inits, p1);
631         }
632     }
633
634   // Now READY is the list in the desired initialization order.
635   var_inits->swap(ready);
636 }
637
638 // Write out the global definitions.
639
640 void
641 Gogo::write_globals()
642 {
643   this->convert_named_types();
644   this->build_interface_method_tables();
645
646   Bindings* bindings = this->current_bindings();
647   size_t count = bindings->size_definitions();
648
649   tree* vec = new tree[count];
650
651   tree init_fndecl = NULL_TREE;
652   tree init_stmt_list = NULL_TREE;
653
654   if (this->is_main_package())
655     this->init_imports(&init_stmt_list);
656
657   // A list of variable initializations.
658   Var_inits var_inits;
659
660   // A list of variables which need to be registered with the garbage
661   // collector.
662   std::vector<Named_object*> var_gc;
663   var_gc.reserve(count);
664
665   tree var_init_stmt_list = NULL_TREE;
666   size_t i = 0;
667   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
668        p != bindings->end_definitions();
669        ++p, ++i)
670     {
671       Named_object* no = *p;
672
673       gcc_assert(!no->is_type_declaration() && !no->is_function_declaration());
674       // There is nothing to do for a package.
675       if (no->is_package())
676         {
677           --i;
678           --count;
679           continue;
680         }
681
682       // There is nothing to do for an object which was imported from
683       // a different package into the global scope.
684       if (no->package() != NULL)
685         {
686           --i;
687           --count;
688           continue;
689         }
690
691       // There is nothing useful we can output for constants which
692       // have ideal or non-integeral type.
693       if (no->is_const())
694         {
695           Type* type = no->const_value()->type();
696           if (type == NULL)
697             type = no->const_value()->expr()->type();
698           if (type->is_abstract() || type->integer_type() == NULL)
699             {
700               --i;
701               --count;
702               continue;
703             }
704         }
705
706       vec[i] = no->get_tree(this, NULL);
707
708       if (vec[i] == error_mark_node)
709         {
710           gcc_assert(saw_errors());
711           --i;
712           --count;
713           continue;
714         }
715
716       // If a variable is initialized to a non-constant value, do the
717       // initialization in an initialization function.
718       if (TREE_CODE(vec[i]) == VAR_DECL)
719         {
720           gcc_assert(no->is_variable());
721
722           // Check for a sink variable, which may be used to run
723           // an initializer purely for its side effects.
724           bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
725
726           tree var_init_tree = NULL_TREE;
727           if (!no->var_value()->has_pre_init())
728             {
729               tree init = no->var_value()->get_init_tree(this, NULL);
730               if (init == error_mark_node)
731                 gcc_assert(saw_errors());
732               else if (init == NULL_TREE)
733                 ;
734               else if (TREE_CONSTANT(init))
735                 DECL_INITIAL(vec[i]) = init;
736               else if (is_sink)
737                 var_init_tree = init;
738               else
739                 var_init_tree = fold_build2_loc(no->location(), MODIFY_EXPR,
740                                                 void_type_node, vec[i], init);
741             }
742           else
743             {
744               // We are going to create temporary variables which
745               // means that we need an fndecl.
746               if (init_fndecl == NULL_TREE)
747                 init_fndecl = this->initialization_function_decl();
748               current_function_decl = init_fndecl;
749               if (DECL_STRUCT_FUNCTION(init_fndecl) == NULL)
750                 push_struct_function(init_fndecl);
751               else
752                 push_cfun(DECL_STRUCT_FUNCTION(init_fndecl));
753
754               tree var_decl = is_sink ? NULL_TREE : vec[i];
755               var_init_tree = no->var_value()->get_init_block(this, NULL,
756                                                               var_decl);
757
758               current_function_decl = NULL_TREE;
759               pop_cfun();
760             }
761
762           if (var_init_tree != NULL_TREE && var_init_tree != error_mark_node)
763             {
764               if (no->var_value()->init() == NULL
765                   && !no->var_value()->has_pre_init())
766                 append_to_statement_list(var_init_tree, &var_init_stmt_list);
767               else
768                 var_inits.push_back(Var_init(no, var_init_tree));
769             }
770
771           if (!is_sink && no->var_value()->type()->has_pointer())
772             var_gc.push_back(no);
773         }
774     }
775
776   // Register global variables with the garbage collector.
777   this->register_gc_vars(var_gc, &init_stmt_list);
778
779   // Simple variable initializations, after all variables are
780   // registered.
781   append_to_statement_list(var_init_stmt_list, &init_stmt_list);
782
783   // Complex variable initializations, first sorting them into a
784   // workable order.
785   if (!var_inits.empty())
786     {
787       sort_var_inits(&var_inits);
788       for (Var_inits::const_iterator p = var_inits.begin();
789            p != var_inits.end();
790            ++p)
791         append_to_statement_list(p->init(), &init_stmt_list);
792     }
793
794   // After all the variables are initialized, call the "init"
795   // functions if there are any.
796   for (std::vector<Named_object*>::const_iterator p =
797          this->init_functions_.begin();
798        p != this->init_functions_.end();
799        ++p)
800     {
801       tree decl = (*p)->get_tree(this, NULL);
802       tree call = build_call_expr(decl, 0);
803       append_to_statement_list(call, &init_stmt_list);
804     }
805
806   // Set up a magic function to do all the initialization actions.
807   // This will be called if this package is imported.
808   if (init_stmt_list != NULL_TREE
809       || this->need_init_fn_
810       || this->is_main_package())
811     this->write_initialization_function(init_fndecl, init_stmt_list);
812
813   // Pass everything back to the middle-end.
814
815   wrapup_global_declarations(vec, count);
816
817   cgraph_finalize_compilation_unit();
818
819   check_global_declarations(vec, count);
820   emit_debug_global_declarations(vec, count);
821
822   delete[] vec;
823 }
824
825 // Get a tree for the identifier for a named object.
826
827 tree
828 Named_object::get_id(Gogo* gogo)
829 {
830   std::string decl_name;
831   if (this->is_function_declaration()
832       && !this->func_declaration_value()->asm_name().empty())
833     decl_name = this->func_declaration_value()->asm_name();
834   else if ((this->is_variable() && !this->var_value()->is_global())
835            || (this->is_type()
836                && this->type_value()->location() == BUILTINS_LOCATION))
837     {
838       // We don't need the package name for local variables or builtin
839       // types.
840       decl_name = Gogo::unpack_hidden_name(this->name_);
841     }
842   else if (this->is_function()
843            && !this->func_value()->is_method()
844            && this->package_ == NULL
845            && Gogo::unpack_hidden_name(this->name_) == "init")
846     {
847       // A single package can have multiple "init" functions, which
848       // means that we need to give them different names.
849       static int init_index;
850       char buf[20];
851       snprintf(buf, sizeof buf, "%d", init_index);
852       ++init_index;
853       decl_name = gogo->package_name() + ".init." + buf;
854     }
855   else
856     {
857       std::string package_name;
858       if (this->package_ == NULL)
859         package_name = gogo->package_name();
860       else
861         package_name = this->package_->name();
862
863       decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
864
865       Function_type* fntype;
866       if (this->is_function())
867         fntype = this->func_value()->type();
868       else if (this->is_function_declaration())
869         fntype = this->func_declaration_value()->type();
870       else
871         fntype = NULL;
872       if (fntype != NULL && fntype->is_method())
873         {
874           decl_name.push_back('.');
875           decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
876         }
877     }
878   if (this->is_type())
879     {
880       const Named_object* in_function = this->type_value()->in_function();
881       if (in_function != NULL)
882         decl_name += '$' + in_function->name();
883     }
884   return get_identifier_from_string(decl_name);
885 }
886
887 // Get a tree for a named object.
888
889 tree
890 Named_object::get_tree(Gogo* gogo, Named_object* function)
891 {
892   if (this->tree_ != NULL_TREE)
893     {
894       // If this is a variable whose address is taken, we must rebuild
895       // the INDIRECT_REF each time to avoid invalid sharing.
896       tree ret = this->tree_;
897       if (((this->classification_ == NAMED_OBJECT_VAR
898             && this->var_value()->is_in_heap())
899            || (this->classification_ == NAMED_OBJECT_RESULT_VAR
900                && this->result_var_value()->is_in_heap()))
901           && ret != error_mark_node)
902         {
903           gcc_assert(TREE_CODE(ret) == INDIRECT_REF);
904           ret = build_fold_indirect_ref(TREE_OPERAND(ret, 0));
905           TREE_THIS_NOTRAP(ret) = 1;
906         }
907       return ret;
908     }
909
910   tree name;
911   if (this->classification_ == NAMED_OBJECT_TYPE)
912     name = NULL_TREE;
913   else
914     name = this->get_id(gogo);
915   tree decl;
916   switch (this->classification_)
917     {
918     case NAMED_OBJECT_CONST:
919       {
920         Named_constant* named_constant = this->u_.const_value;
921         Translate_context subcontext(gogo, function, NULL, NULL_TREE);
922         tree expr_tree = named_constant->expr()->get_tree(&subcontext);
923         if (expr_tree == error_mark_node)
924           decl = error_mark_node;
925         else
926           {
927             Type* type = named_constant->type();
928             if (type != NULL && !type->is_abstract())
929               expr_tree = fold_convert(type->get_tree(gogo), expr_tree);
930             if (expr_tree == error_mark_node)
931               decl = error_mark_node;
932             else if (INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
933               {
934                 decl = build_decl(named_constant->location(), CONST_DECL,
935                                   name, TREE_TYPE(expr_tree));
936                 DECL_INITIAL(decl) = expr_tree;
937                 TREE_CONSTANT(decl) = 1;
938                 TREE_READONLY(decl) = 1;
939               }
940             else
941               {
942                 // A CONST_DECL is only for an enum constant, so we
943                 // shouldn't use for non-integral types.  Instead we
944                 // just return the constant itself, rather than a
945                 // decl.
946                 decl = expr_tree;
947               }
948           }
949       }
950       break;
951
952     case NAMED_OBJECT_TYPE:
953       {
954         Named_type* named_type = this->u_.type_value;
955         tree type_tree = named_type->get_tree(gogo);
956         if (type_tree == error_mark_node)
957           decl = error_mark_node;
958         else
959           {
960             decl = TYPE_NAME(type_tree);
961             gcc_assert(decl != NULL_TREE);
962
963             // We need to produce a type descriptor for every named
964             // type, and for a pointer to every named type, since
965             // other files or packages might refer to them.  We need
966             // to do this even for hidden types, because they might
967             // still be returned by some function.  Simply calling the
968             // type_descriptor method is enough to create the type
969             // descriptor, even though we don't do anything with it.
970             if (this->package_ == NULL)
971               {
972                 named_type->type_descriptor_pointer(gogo);
973                 Type* pn = Type::make_pointer_type(named_type);
974                 pn->type_descriptor_pointer(gogo);
975               }
976           }
977       }
978       break;
979
980     case NAMED_OBJECT_TYPE_DECLARATION:
981       error("reference to undefined type %qs",
982             this->message_name().c_str());
983       return error_mark_node;
984
985     case NAMED_OBJECT_VAR:
986       {
987         Variable* var = this->u_.var_value;
988         Type* type = var->type();
989         if (type->is_error_type()
990             || (type->is_undefined()
991                 && (!var->is_global() || this->package() == NULL)))
992           {
993             // Force the error for an undefined type, just in case.
994             type->base();
995             decl = error_mark_node;
996           }
997         else
998           {
999             tree var_type = type->get_tree(gogo);
1000             bool is_parameter = var->is_parameter();
1001             if (var->is_receiver() && type->points_to() == NULL)
1002               is_parameter = false;
1003             if (var->is_in_heap())
1004               {
1005                 is_parameter = false;
1006                 var_type = build_pointer_type(var_type);
1007               }
1008             decl = build_decl(var->location(),
1009                               is_parameter ? PARM_DECL : VAR_DECL,
1010                               name, var_type);
1011             if (!var->is_global())
1012               {
1013                 tree fnid = function->get_id(gogo);
1014                 tree fndecl = function->func_value()->get_or_make_decl(gogo,
1015                                                                        function,
1016                                                                        fnid);
1017                 DECL_CONTEXT(decl) = fndecl;
1018               }
1019             if (is_parameter)
1020               DECL_ARG_TYPE(decl) = TREE_TYPE(decl);
1021
1022             if (var->is_global())
1023               {
1024                 const Package* package = this->package();
1025                 if (package == NULL)
1026                   TREE_STATIC(decl) = 1;
1027                 else
1028                   DECL_EXTERNAL(decl) = 1;
1029                 if (!Gogo::is_hidden_name(this->name_))
1030                   {
1031                     TREE_PUBLIC(decl) = 1;
1032                     std::string asm_name = (package == NULL
1033                                             ? gogo->unique_prefix()
1034                                             : package->unique_prefix());
1035                     asm_name.append(1, '.');
1036                     asm_name.append(IDENTIFIER_POINTER(name),
1037                                     IDENTIFIER_LENGTH(name));
1038                     tree asm_id = get_identifier_from_string(asm_name);
1039                     SET_DECL_ASSEMBLER_NAME(decl, asm_id);
1040                   }
1041               }
1042
1043             // FIXME: We should only set this for variables which are
1044             // actually used somewhere.
1045             TREE_USED(decl) = 1;
1046           }
1047       }
1048       break;
1049
1050     case NAMED_OBJECT_RESULT_VAR:
1051       {
1052         Result_variable* result = this->u_.result_var_value;
1053         Type* type = result->type();
1054         if (type->is_error_type() || type->is_undefined())
1055           {
1056             // Force the error.
1057             type->base();
1058             decl = error_mark_node;
1059           }
1060         else
1061           {
1062             gcc_assert(result->function() == function->func_value());
1063             source_location loc = function->location();
1064             tree result_type = type->get_tree(gogo);
1065             tree init;
1066             if (!result->is_in_heap())
1067               init = type->get_init_tree(gogo, false);
1068             else
1069               {
1070                 tree space = gogo->allocate_memory(type,
1071                                                    TYPE_SIZE_UNIT(result_type),
1072                                                    loc);
1073                 result_type = build_pointer_type(result_type);
1074                 tree subinit = type->get_init_tree(gogo, true);
1075                 if (subinit == NULL_TREE)
1076                   init = fold_convert_loc(loc, result_type, space);
1077                 else
1078                   {
1079                     space = save_expr(space);
1080                     space = fold_convert_loc(loc, result_type, space);
1081                     tree spaceref = build_fold_indirect_ref_loc(loc, space);
1082                     TREE_THIS_NOTRAP(spaceref) = 1;
1083                     tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node,
1084                                                spaceref, subinit);
1085                     init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space),
1086                                            set, space);
1087                   }
1088               }
1089             decl = build_decl(loc, VAR_DECL, name, result_type);
1090             tree fnid = function->get_id(gogo);
1091             tree fndecl = function->func_value()->get_or_make_decl(gogo,
1092                                                                    function,
1093                                                                    fnid);
1094             DECL_CONTEXT(decl) = fndecl;
1095             DECL_INITIAL(decl) = init;
1096             TREE_USED(decl) = 1;
1097           }
1098       }
1099       break;
1100
1101     case NAMED_OBJECT_SINK:
1102       gcc_unreachable();
1103
1104     case NAMED_OBJECT_FUNC:
1105       {
1106         Function* func = this->u_.func_value;
1107         decl = func->get_or_make_decl(gogo, this, name);
1108         if (decl != error_mark_node)
1109           {
1110             if (func->block() != NULL)
1111               {
1112                 if (DECL_STRUCT_FUNCTION(decl) == NULL)
1113                   push_struct_function(decl);
1114                 else
1115                   push_cfun(DECL_STRUCT_FUNCTION(decl));
1116
1117                 cfun->function_end_locus = func->block()->end_location();
1118
1119                 current_function_decl = decl;
1120
1121                 func->build_tree(gogo, this);
1122
1123                 gimplify_function_tree(decl);
1124
1125                 cgraph_finalize_function(decl, true);
1126
1127                 current_function_decl = NULL_TREE;
1128                 pop_cfun();
1129               }
1130           }
1131       }
1132       break;
1133
1134     default:
1135       gcc_unreachable();
1136     }
1137
1138   if (TREE_TYPE(decl) == error_mark_node)
1139     decl = error_mark_node;
1140
1141   tree ret = decl;
1142
1143   // If this is a local variable whose address is taken, then we
1144   // actually store it in the heap.  For uses of the variable we need
1145   // to return a reference to that heap location.
1146   if (((this->classification_ == NAMED_OBJECT_VAR
1147         && this->var_value()->is_in_heap())
1148        || (this->classification_ == NAMED_OBJECT_RESULT_VAR
1149            && this->result_var_value()->is_in_heap()))
1150       && ret != error_mark_node)
1151     {
1152       gcc_assert(POINTER_TYPE_P(TREE_TYPE(ret)));
1153       ret = build_fold_indirect_ref(ret);
1154       TREE_THIS_NOTRAP(ret) = 1;
1155     }
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   gcc_assert(this->preinit_ == NULL);
1173   if (this->init_ == NULL)
1174     {
1175       gcc_assert(!this->is_parameter_);
1176       return this->type_->get_init_tree(gogo, this->is_global_);
1177     }
1178   else
1179     {
1180       Translate_context context(gogo, function, NULL, NULL_TREE);
1181       tree rhs_tree = this->init_->get_tree(&context);
1182       return Expression::convert_for_assignment(&context, this->type(),
1183                                                 this->init_->type(),
1184                                                 rhs_tree, this->location());
1185     }
1186 }
1187
1188 // Get the initial value of a variable when a block is required.
1189 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
1190
1191 tree
1192 Variable::get_init_block(Gogo* gogo, Named_object* function, tree var_decl)
1193 {
1194   gcc_assert(this->preinit_ != NULL);
1195
1196   // We want to add the variable assignment to the end of the preinit
1197   // block.  The preinit block may have a TRY_FINALLY_EXPR and a
1198   // TRY_CATCH_EXPR; if it does, we want to add to the end of the
1199   // regular statements.
1200
1201   Translate_context context(gogo, function, NULL, NULL_TREE);
1202   tree block_tree = this->preinit_->get_tree(&context);
1203   if (block_tree == error_mark_node)
1204     return error_mark_node;
1205   gcc_assert(TREE_CODE(block_tree) == BIND_EXPR);
1206   tree statements = BIND_EXPR_BODY(block_tree);
1207   while (statements != NULL_TREE
1208          && (TREE_CODE(statements) == TRY_FINALLY_EXPR
1209              || TREE_CODE(statements) == TRY_CATCH_EXPR))
1210     statements = TREE_OPERAND(statements, 0);
1211
1212   // It's possible to have pre-init statements without an initializer
1213   // if the pre-init statements set the variable.
1214   if (this->init_ != NULL)
1215     {
1216       tree rhs_tree = this->init_->get_tree(&context);
1217       if (rhs_tree == error_mark_node)
1218         return error_mark_node;
1219       if (var_decl == NULL_TREE)
1220         append_to_statement_list(rhs_tree, &statements);
1221       else
1222         {
1223           tree val = Expression::convert_for_assignment(&context, this->type(),
1224                                                         this->init_->type(),
1225                                                         rhs_tree,
1226                                                         this->location());
1227           if (val == error_mark_node)
1228             return error_mark_node;
1229           tree set = fold_build2_loc(this->location(), MODIFY_EXPR,
1230                                      void_type_node, var_decl, val);
1231           append_to_statement_list(set, &statements);
1232         }
1233     }
1234
1235   return block_tree;
1236 }
1237
1238 // Get a tree for a function decl.
1239
1240 tree
1241 Function::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1242 {
1243   if (this->fndecl_ == NULL_TREE)
1244     {
1245       tree functype = this->type_->get_tree(gogo);
1246       if (functype == error_mark_node)
1247         this->fndecl_ = error_mark_node;
1248       else
1249         {
1250           // The type of a function comes back as a pointer, but we
1251           // want the real function type for a function declaration.
1252           gcc_assert(POINTER_TYPE_P(functype));
1253           functype = TREE_TYPE(functype);
1254           tree decl = build_decl(this->location(), FUNCTION_DECL, id, functype);
1255
1256           this->fndecl_ = decl;
1257
1258           if (no->package() != NULL)
1259             ;
1260           else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
1261             ;
1262           else if (Gogo::unpack_hidden_name(no->name()) == "init"
1263                    && !this->type_->is_method())
1264             ;
1265           else if (Gogo::unpack_hidden_name(no->name()) == "main"
1266                    && gogo->is_main_package())
1267             TREE_PUBLIC(decl) = 1;
1268           // Methods have to be public even if they are hidden because
1269           // they can be pulled into type descriptors when using
1270           // anonymous fields.
1271           else if (!Gogo::is_hidden_name(no->name())
1272                    || this->type_->is_method())
1273             {
1274               TREE_PUBLIC(decl) = 1;
1275               std::string asm_name = gogo->unique_prefix();
1276               asm_name.append(1, '.');
1277               asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id));
1278               SET_DECL_ASSEMBLER_NAME(decl,
1279                                       get_identifier_from_string(asm_name));
1280             }
1281
1282           // Why do we have to do this in the frontend?
1283           tree restype = TREE_TYPE(functype);
1284           tree resdecl = build_decl(this->location(), RESULT_DECL, NULL_TREE,
1285                                     restype);
1286           DECL_ARTIFICIAL(resdecl) = 1;
1287           DECL_IGNORED_P(resdecl) = 1;
1288           DECL_CONTEXT(resdecl) = decl;
1289           DECL_RESULT(decl) = resdecl;
1290
1291           if (this->enclosing_ != NULL)
1292             DECL_STATIC_CHAIN(decl) = 1;
1293
1294           // If a function calls the predeclared recover function, we
1295           // can't inline it, because recover behaves differently in a
1296           // function passed directly to defer.
1297           if (this->calls_recover_ && !this->is_recover_thunk_)
1298             DECL_UNINLINABLE(decl) = 1;
1299
1300           // If this is a thunk created to call a function which calls
1301           // the predeclared recover function, we need to disable
1302           // stack splitting for the thunk.
1303           if (this->is_recover_thunk_)
1304             {
1305               tree attr = get_identifier("__no_split_stack__");
1306               DECL_ATTRIBUTES(decl) = tree_cons(attr, NULL_TREE, NULL_TREE);
1307             }
1308
1309           go_preserve_from_gc(decl);
1310
1311           if (this->closure_var_ != NULL)
1312             {
1313               push_struct_function(decl);
1314
1315               tree closure_decl = this->closure_var_->get_tree(gogo, no);
1316               if (closure_decl == error_mark_node)
1317                 this->fndecl_ = error_mark_node;
1318               else
1319                 {
1320                   DECL_ARTIFICIAL(closure_decl) = 1;
1321                   DECL_IGNORED_P(closure_decl) = 1;
1322                   TREE_USED(closure_decl) = 1;
1323                   DECL_ARG_TYPE(closure_decl) = TREE_TYPE(closure_decl);
1324                   TREE_READONLY(closure_decl) = 1;
1325
1326                   DECL_STRUCT_FUNCTION(decl)->static_chain_decl = closure_decl;
1327                 }
1328
1329               pop_cfun();
1330             }
1331         }
1332     }
1333   return this->fndecl_;
1334 }
1335
1336 // Get a tree for a function declaration.
1337
1338 tree
1339 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1340 {
1341   if (this->fndecl_ == NULL_TREE)
1342     {
1343       // Let Go code use an asm declaration to pick up a builtin
1344       // function.
1345       if (!this->asm_name_.empty())
1346         {
1347           std::map<std::string, tree>::const_iterator p =
1348             builtin_functions.find(this->asm_name_);
1349           if (p != builtin_functions.end())
1350             {
1351               this->fndecl_ = p->second;
1352               return this->fndecl_;
1353             }
1354         }
1355
1356       tree functype = this->fntype_->get_tree(gogo);
1357       tree decl;
1358       if (functype == error_mark_node)
1359         decl = error_mark_node;
1360       else
1361         {
1362           // The type of a function comes back as a pointer, but we
1363           // want the real function type for a function declaration.
1364           gcc_assert(POINTER_TYPE_P(functype));
1365           functype = TREE_TYPE(functype);
1366           decl = build_decl(this->location(), FUNCTION_DECL, id, functype);
1367           TREE_PUBLIC(decl) = 1;
1368           DECL_EXTERNAL(decl) = 1;
1369
1370           if (this->asm_name_.empty())
1371             {
1372               std::string asm_name = (no->package() == NULL
1373                                       ? gogo->unique_prefix()
1374                                       : no->package()->unique_prefix());
1375               asm_name.append(1, '.');
1376               asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id));
1377               SET_DECL_ASSEMBLER_NAME(decl,
1378                                       get_identifier_from_string(asm_name));
1379             }
1380         }
1381       this->fndecl_ = decl;
1382       go_preserve_from_gc(decl);
1383     }
1384   return this->fndecl_;
1385 }
1386
1387 // We always pass the receiver to a method as a pointer.  If the
1388 // receiver is actually declared as a non-pointer type, then we copy
1389 // the value into a local variable, so that it has the right type.  In
1390 // this function we create the real PARM_DECL to use, and set
1391 // DEC_INITIAL of the var_decl to be the value passed in.
1392
1393 tree
1394 Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl)
1395 {
1396   if (var_decl == error_mark_node)
1397     return error_mark_node;
1398   // If the function takes the address of a receiver which is passed
1399   // by value, then we will have an INDIRECT_REF here.  We need to get
1400   // the real variable.
1401   bool is_in_heap = no->var_value()->is_in_heap();
1402   tree val_type;
1403   if (TREE_CODE(var_decl) != INDIRECT_REF)
1404     {
1405       gcc_assert(!is_in_heap);
1406       val_type = TREE_TYPE(var_decl);
1407     }
1408   else
1409     {
1410       gcc_assert(is_in_heap);
1411       var_decl = TREE_OPERAND(var_decl, 0);
1412       if (var_decl == error_mark_node)
1413         return error_mark_node;
1414       gcc_assert(POINTER_TYPE_P(TREE_TYPE(var_decl)));
1415       val_type = TREE_TYPE(TREE_TYPE(var_decl));
1416     }
1417   gcc_assert(TREE_CODE(var_decl) == VAR_DECL);
1418   source_location loc = DECL_SOURCE_LOCATION(var_decl);
1419   std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1420   name += ".pointer";
1421   tree id = get_identifier_from_string(name);
1422   tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type));
1423   DECL_CONTEXT(parm_decl) = current_function_decl;
1424   DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl);
1425
1426   gcc_assert(DECL_INITIAL(var_decl) == NULL_TREE);
1427   // The receiver might be passed as a null pointer.
1428   tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node, parm_decl,
1429                                fold_convert_loc(loc, TREE_TYPE(parm_decl),
1430                                                 null_pointer_node));
1431   tree ind = build_fold_indirect_ref_loc(loc, parm_decl);
1432   TREE_THIS_NOTRAP(ind) = 1;
1433   tree zero_init = no->var_value()->type()->get_init_tree(gogo, false);
1434   tree init = fold_build3_loc(loc, COND_EXPR, TREE_TYPE(ind),
1435                               check, ind, zero_init);
1436
1437   if (is_in_heap)
1438     {
1439       tree size = TYPE_SIZE_UNIT(val_type);
1440       tree space = gogo->allocate_memory(no->var_value()->type(), size,
1441                                          no->location());
1442       space = save_expr(space);
1443       space = fold_convert(build_pointer_type(val_type), space);
1444       tree spaceref = build_fold_indirect_ref_loc(no->location(), space);
1445       TREE_THIS_NOTRAP(spaceref) = 1;
1446       tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node,
1447                                    parm_decl,
1448                                    fold_convert_loc(loc, TREE_TYPE(parm_decl),
1449                                                     null_pointer_node));
1450       tree parmref = build_fold_indirect_ref_loc(no->location(), parm_decl);
1451       TREE_THIS_NOTRAP(parmref) = 1;
1452       tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node,
1453                                  spaceref, parmref);
1454       init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space),
1455                              build3(COND_EXPR, void_type_node,
1456                                     check, set, NULL_TREE),
1457                              space);
1458     }
1459
1460   DECL_INITIAL(var_decl) = init;
1461
1462   return parm_decl;
1463 }
1464
1465 // If we take the address of a parameter, then we need to copy it into
1466 // the heap.  We will access it as a local variable via an
1467 // indirection.
1468
1469 tree
1470 Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree ref)
1471 {
1472   if (ref == error_mark_node)
1473     return error_mark_node;
1474
1475   gcc_assert(TREE_CODE(ref) == INDIRECT_REF);
1476
1477   tree var_decl = TREE_OPERAND(ref, 0);
1478   if (var_decl == error_mark_node)
1479     return error_mark_node;
1480   gcc_assert(TREE_CODE(var_decl) == VAR_DECL);
1481   source_location loc = DECL_SOURCE_LOCATION(var_decl);
1482
1483   std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1484   name += ".param";
1485   tree id = get_identifier_from_string(name);
1486
1487   tree type = TREE_TYPE(var_decl);
1488   gcc_assert(POINTER_TYPE_P(type));
1489   type = TREE_TYPE(type);
1490
1491   tree parm_decl = build_decl(loc, PARM_DECL, id, type);
1492   DECL_CONTEXT(parm_decl) = current_function_decl;
1493   DECL_ARG_TYPE(parm_decl) = type;
1494
1495   tree size = TYPE_SIZE_UNIT(type);
1496   tree space = gogo->allocate_memory(no->var_value()->type(), size, loc);
1497   space = save_expr(space);
1498   space = fold_convert(TREE_TYPE(var_decl), space);
1499   tree spaceref = build_fold_indirect_ref_loc(loc, space);
1500   TREE_THIS_NOTRAP(spaceref) = 1;
1501   tree init = build2(COMPOUND_EXPR, TREE_TYPE(space),
1502                      build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl),
1503                      space);
1504   DECL_INITIAL(var_decl) = init;
1505
1506   return parm_decl;
1507 }
1508
1509 // Get a tree for function code.
1510
1511 void
1512 Function::build_tree(Gogo* gogo, Named_object* named_function)
1513 {
1514   tree fndecl = this->fndecl_;
1515   gcc_assert(fndecl != NULL_TREE);
1516
1517   tree params = NULL_TREE;
1518   tree* pp = &params;
1519
1520   tree declare_vars = NULL_TREE;
1521   for (Bindings::const_definitions_iterator p =
1522          this->block_->bindings()->begin_definitions();
1523        p != this->block_->bindings()->end_definitions();
1524        ++p)
1525     {
1526       if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
1527         {
1528           *pp = (*p)->get_tree(gogo, named_function);
1529
1530           // We always pass the receiver to a method as a pointer.  If
1531           // the receiver is declared as a non-pointer type, then we
1532           // copy the value into a local variable.
1533           if ((*p)->var_value()->is_receiver()
1534               && (*p)->var_value()->type()->points_to() == NULL)
1535             {
1536               tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp);
1537               tree var = *pp;
1538               if (TREE_CODE(var) == INDIRECT_REF)
1539                 var = TREE_OPERAND(var, 0);
1540               if (var != error_mark_node)
1541                 {
1542                   gcc_assert(TREE_CODE(var) == VAR_DECL);
1543                   DECL_CHAIN(var) = declare_vars;
1544                   declare_vars = var;
1545                 }
1546               *pp = parm_decl;
1547             }
1548           else if ((*p)->var_value()->is_in_heap())
1549             {
1550               // If we take the address of a parameter, then we need
1551               // to copy it into the heap.
1552               tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp);
1553               if (*pp != error_mark_node)
1554                 {
1555                   gcc_assert(TREE_CODE(*pp) == INDIRECT_REF);
1556                   tree var_decl = TREE_OPERAND(*pp, 0);
1557                   if (var_decl != error_mark_node)
1558                     {
1559                       gcc_assert(TREE_CODE(var_decl) == VAR_DECL);
1560                       DECL_CHAIN(var_decl) = declare_vars;
1561                       declare_vars = var_decl;
1562                     }
1563                 }
1564               *pp = parm_decl;
1565             }
1566
1567           if (*pp != error_mark_node)
1568             {
1569               gcc_assert(TREE_CODE(*pp) == PARM_DECL);
1570               pp = &DECL_CHAIN(*pp);
1571             }
1572         }
1573       else if ((*p)->is_result_variable())
1574         {
1575           tree var_decl = (*p)->get_tree(gogo, named_function);
1576           if (var_decl != error_mark_node
1577               && (*p)->result_var_value()->is_in_heap())
1578             {
1579               gcc_assert(TREE_CODE(var_decl) == INDIRECT_REF);
1580               var_decl = TREE_OPERAND(var_decl, 0);
1581             }
1582           if (var_decl != error_mark_node)
1583             {
1584               gcc_assert(TREE_CODE(var_decl) == VAR_DECL);
1585               DECL_CHAIN(var_decl) = declare_vars;
1586               declare_vars = var_decl;
1587             }
1588         }
1589     }
1590   *pp = NULL_TREE;
1591
1592   DECL_ARGUMENTS(fndecl) = params;
1593
1594   if (this->block_ != NULL)
1595     {
1596       gcc_assert(DECL_INITIAL(fndecl) == NULL_TREE);
1597
1598       // Declare variables if necessary.
1599       tree bind = NULL_TREE;
1600       if (declare_vars != NULL_TREE)
1601         {
1602           tree block = make_node(BLOCK);
1603           BLOCK_SUPERCONTEXT(block) = fndecl;
1604           DECL_INITIAL(fndecl) = block;
1605           BLOCK_VARS(block) = declare_vars;
1606           TREE_USED(block) = 1;
1607           bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block),
1608                         NULL_TREE, block);
1609           TREE_SIDE_EFFECTS(bind) = 1;
1610         }
1611
1612       // Build the trees for all the statements in the function.
1613       Translate_context context(gogo, named_function, NULL, NULL_TREE);
1614       tree code = this->block_->get_tree(&context);
1615
1616       tree init = NULL_TREE;
1617       tree except = NULL_TREE;
1618       tree fini = NULL_TREE;
1619
1620       // Initialize variables if necessary.
1621       for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v))
1622         {
1623           tree dv = build1(DECL_EXPR, void_type_node, v);
1624           SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v));
1625           append_to_statement_list(dv, &init);
1626         }
1627
1628       // If we have a defer stack, initialize it at the start of a
1629       // function.
1630       if (this->defer_stack_ != NULL_TREE)
1631         {
1632           tree defer_init = build1(DECL_EXPR, void_type_node,
1633                                    this->defer_stack_);
1634           SET_EXPR_LOCATION(defer_init, this->block_->start_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   source_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   tree stmt_list = NULL_TREE;
1679   static tree check_fndecl;
1680   tree call = Gogo::call_builtin(&check_fndecl,
1681                                  end_loc,
1682                                  "__go_check_defer",
1683                                  1,
1684                                  void_type_node,
1685                                  ptr_type_node,
1686                                  this->defer_stack(end_loc));
1687   if (call != error_mark_node)
1688     append_to_statement_list(call, &stmt_list);
1689
1690   tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list);
1691   tree set;
1692   if (retval == NULL_TREE)
1693     set = NULL_TREE;
1694   else
1695     set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node,
1696                           DECL_RESULT(this->fndecl_), retval);
1697   tree ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set);
1698   append_to_statement_list(ret_stmt, &stmt_list);
1699
1700   gcc_assert(*except == NULL_TREE);
1701   *except = stmt_list;
1702
1703   // Add some finally code to run the defer functions.  This is used
1704   // both in the normal case, when no panic occurs, and also if a
1705   // panic occurs to run any further defer functions.  Of course, it
1706   // is possible for a defer function to call panic which should be
1707   // caught by another defer function.  To handle that we use a loop.
1708   //  finish:
1709   //   try { __go_undefer(); } catch { __go_check_defer(); goto finish; }
1710   //   if (return values are named) return named_vals;
1711
1712   stmt_list = NULL;
1713
1714   tree label = create_artificial_label(end_loc);
1715   tree define_label = fold_build1_loc(end_loc, LABEL_EXPR, void_type_node,
1716                                       label);
1717   append_to_statement_list(define_label, &stmt_list);
1718
1719   static tree undefer_fndecl;
1720   tree undefer = Gogo::call_builtin(&undefer_fndecl,
1721                                     end_loc,
1722                                     "__go_undefer",
1723                                     1,
1724                                     void_type_node,
1725                                     ptr_type_node,
1726                                     this->defer_stack(end_loc));
1727   if (undefer_fndecl != NULL_TREE)
1728     TREE_NOTHROW(undefer_fndecl) = 0;
1729
1730   tree defer = Gogo::call_builtin(&check_fndecl,
1731                                   end_loc,
1732                                   "__go_check_defer",
1733                                   1,
1734                                   void_type_node,
1735                                   ptr_type_node,
1736                                   this->defer_stack(end_loc));
1737   tree jump = fold_build1_loc(end_loc, GOTO_EXPR, void_type_node, label);
1738   tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump);
1739   catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body);
1740   tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body);
1741
1742   append_to_statement_list(try_catch, &stmt_list);
1743
1744   if (this->type_->results() != NULL
1745       && !this->type_->results()->empty()
1746       && !this->type_->results()->front().name().empty())
1747     {
1748       // If the result variables are named, we need to return them
1749       // again, because they might have been changed by a defer
1750       // function.
1751       retval = this->return_value(gogo, named_function, end_loc,
1752                                   &stmt_list);
1753       set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node,
1754                             DECL_RESULT(this->fndecl_), retval);
1755       ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set);
1756       append_to_statement_list(ret_stmt, &stmt_list);
1757     }
1758   
1759   gcc_assert(*fini == NULL_TREE);
1760   *fini = stmt_list;
1761 }
1762
1763 // Return the value to assign to DECL_RESULT(this->fndecl_).  This may
1764 // also add statements to STMT_LIST, which need to be executed before
1765 // the assignment.  This is used for a return statement with no
1766 // explicit values.
1767
1768 tree
1769 Function::return_value(Gogo* gogo, Named_object* named_function,
1770                        source_location location, tree* stmt_list) const
1771 {
1772   const Typed_identifier_list* results = this->type_->results();
1773   if (results == NULL || results->empty())
1774     return NULL_TREE;
1775
1776   // In the case of an exception handler created for functions with
1777   // defer statements, the result variables may be unnamed.
1778   bool is_named = !results->front().name().empty();
1779   if (is_named)
1780     gcc_assert(this->named_results_ != NULL
1781                && this->named_results_->size() == results->size());
1782
1783   tree retval;
1784   if (results->size() == 1)
1785     {
1786       if (is_named)
1787         return this->named_results_->front()->get_tree(gogo, named_function);
1788       else
1789         return results->front().type()->get_init_tree(gogo, false);
1790     }
1791   else
1792     {
1793       tree rettype = TREE_TYPE(DECL_RESULT(this->fndecl_));
1794       retval = create_tmp_var(rettype, "RESULT");
1795       tree field = TYPE_FIELDS(rettype);
1796       int index = 0;
1797       for (Typed_identifier_list::const_iterator pr = results->begin();
1798            pr != results->end();
1799            ++pr, ++index, field = DECL_CHAIN(field))
1800         {
1801           gcc_assert(field != NULL);
1802           tree val;
1803           if (is_named)
1804             val = (*this->named_results_)[index]->get_tree(gogo,
1805                                                            named_function);
1806           else
1807             val = pr->type()->get_init_tree(gogo, false);
1808           tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node,
1809                                      build3(COMPONENT_REF, TREE_TYPE(field),
1810                                             retval, field, NULL_TREE),
1811                                      val);
1812           append_to_statement_list(set, stmt_list);
1813         }
1814       return retval;
1815     }
1816 }
1817
1818 // Get the tree for the variable holding the defer stack for this
1819 // function.  At least at present, the value of this variable is not
1820 // used.  However, a pointer to this variable is used as a marker for
1821 // the functions on the defer stack associated with this function.
1822 // Doing things this way permits inlining a function which uses defer.
1823
1824 tree
1825 Function::defer_stack(source_location location)
1826 {
1827   if (this->defer_stack_ == NULL_TREE)
1828     {
1829       tree var = create_tmp_var(ptr_type_node, "DEFER");
1830       DECL_INITIAL(var) = null_pointer_node;
1831       DECL_SOURCE_LOCATION(var) = location;
1832       TREE_ADDRESSABLE(var) = 1;
1833       this->defer_stack_ = var;
1834     }
1835   return fold_convert_loc(location, ptr_type_node,
1836                           build_fold_addr_expr_loc(location,
1837                                                    this->defer_stack_));
1838 }
1839
1840 // Get a tree for the statements in a block.
1841
1842 tree
1843 Block::get_tree(Translate_context* context)
1844 {
1845   Gogo* gogo = context->gogo();
1846
1847   tree block = make_node(BLOCK);
1848
1849   // Put the new block into the block tree.
1850
1851   if (context->block() == NULL)
1852     {
1853       tree fndecl;
1854       if (context->function() != NULL)
1855         fndecl = context->function()->func_value()->get_decl();
1856       else
1857         fndecl = current_function_decl;
1858       gcc_assert(fndecl != NULL_TREE);
1859
1860       // We may have already created a block for the receiver.
1861       if (DECL_INITIAL(fndecl) == NULL_TREE)
1862         {
1863           BLOCK_SUPERCONTEXT(block) = fndecl;
1864           DECL_INITIAL(fndecl) = block;
1865         }
1866       else
1867         {
1868           tree superblock_tree = DECL_INITIAL(fndecl);
1869           BLOCK_SUPERCONTEXT(block) = superblock_tree;
1870           gcc_assert(BLOCK_CHAIN(block) == NULL_TREE);
1871           BLOCK_CHAIN(block) = block;
1872         }
1873     }
1874   else
1875     {
1876       tree superblock_tree = context->block_tree();
1877       BLOCK_SUPERCONTEXT(block) = superblock_tree;
1878       tree* pp;
1879       for (pp = &BLOCK_SUBBLOCKS(superblock_tree);
1880            *pp != NULL_TREE;
1881            pp = &BLOCK_CHAIN(*pp))
1882         ;
1883       *pp = block;
1884     }
1885
1886   // Expand local variables in the block.
1887
1888   tree* pp = &BLOCK_VARS(block);
1889   for (Bindings::const_definitions_iterator pv =
1890          this->bindings_->begin_definitions();
1891        pv != this->bindings_->end_definitions();
1892        ++pv)
1893     {
1894       if ((!(*pv)->is_variable() || !(*pv)->var_value()->is_parameter())
1895           && !(*pv)->is_result_variable()
1896           && !(*pv)->is_const())
1897         {
1898           tree var = (*pv)->get_tree(gogo, context->function());
1899           if (var != error_mark_node && TREE_TYPE(var) != error_mark_node)
1900             {
1901               if ((*pv)->is_variable() && (*pv)->var_value()->is_in_heap())
1902                 {
1903                   gcc_assert(TREE_CODE(var) == INDIRECT_REF);
1904                   var = TREE_OPERAND(var, 0);
1905                   gcc_assert(TREE_CODE(var) == VAR_DECL);
1906                 }
1907               *pp = var;
1908               pp = &DECL_CHAIN(*pp);
1909             }
1910         }
1911     }
1912   *pp = NULL_TREE;
1913
1914   Translate_context subcontext(context->gogo(), context->function(),
1915                                this, block);
1916
1917   tree statements = NULL_TREE;
1918
1919   // Expand the statements.
1920
1921   for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
1922        p != this->statements_.end();
1923        ++p)
1924     {
1925       tree statement = (*p)->get_tree(&subcontext);
1926       if (statement != error_mark_node)
1927         append_to_statement_list(statement, &statements);
1928     }
1929
1930   TREE_USED(block) = 1;
1931
1932   tree bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block), statements,
1933                      block);
1934   TREE_SIDE_EFFECTS(bind) = 1;
1935
1936   return bind;
1937 }
1938
1939 // Get the LABEL_DECL for a label.
1940
1941 tree
1942 Label::get_decl()
1943 {
1944   if (this->decl_ == NULL)
1945     {
1946       tree id = get_identifier_from_string(this->name_);
1947       this->decl_ = build_decl(this->location_, LABEL_DECL, id, void_type_node);
1948       DECL_CONTEXT(this->decl_) = current_function_decl;
1949     }
1950   return this->decl_;
1951 }
1952
1953 // Return an expression for the address of this label.
1954
1955 tree
1956 Label::get_addr(source_location location)
1957 {
1958   tree decl = this->get_decl();
1959   TREE_USED(decl) = 1;
1960   TREE_ADDRESSABLE(decl) = 1;
1961   return fold_convert_loc(location, ptr_type_node,
1962                           build_fold_addr_expr_loc(location, decl));
1963 }
1964
1965 // Get the LABEL_DECL for an unnamed label.
1966
1967 tree
1968 Unnamed_label::get_decl()
1969 {
1970   if (this->decl_ == NULL)
1971     this->decl_ = create_artificial_label(this->location_);
1972   return this->decl_;
1973 }
1974
1975 // Get the LABEL_EXPR for an unnamed label.
1976
1977 tree
1978 Unnamed_label::get_definition()
1979 {
1980   tree t = build1(LABEL_EXPR, void_type_node, this->get_decl());
1981   SET_EXPR_LOCATION(t, this->location_);
1982   return t;
1983 }
1984
1985 // Return a goto to this label.
1986
1987 tree
1988 Unnamed_label::get_goto(source_location location)
1989 {
1990   tree t = build1(GOTO_EXPR, void_type_node, this->get_decl());
1991   SET_EXPR_LOCATION(t, location);
1992   return t;
1993 }
1994
1995 // Return the integer type to use for a size.
1996
1997 GO_EXTERN_C
1998 tree
1999 go_type_for_size(unsigned int bits, int unsignedp)
2000 {
2001   const char* name;
2002   switch (bits)
2003     {
2004     case 8:
2005       name = unsignedp ? "uint8" : "int8";
2006       break;
2007     case 16:
2008       name = unsignedp ? "uint16" : "int16";
2009       break;
2010     case 32:
2011       name = unsignedp ? "uint32" : "int32";
2012       break;
2013     case 64:
2014       name = unsignedp ? "uint64" : "int64";
2015       break;
2016     default:
2017       if (bits == POINTER_SIZE && unsignedp)
2018         name = "uintptr";
2019       else
2020         return NULL_TREE;
2021     }
2022   Type* type = Type::lookup_integer_type(name);
2023   return type->get_tree(go_get_gogo());
2024 }
2025
2026 // Return the type to use for a mode.
2027
2028 GO_EXTERN_C
2029 tree
2030 go_type_for_mode(enum machine_mode mode, int unsignedp)
2031 {
2032   // FIXME: This static_cast should be in machmode.h.
2033   enum mode_class mc = static_cast<enum mode_class>(GET_MODE_CLASS(mode));
2034   if (mc == MODE_INT)
2035     return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp);
2036   else if (mc == MODE_FLOAT)
2037     {
2038       Type* type;
2039       switch (GET_MODE_BITSIZE (mode))
2040         {
2041         case 32:
2042           type = Type::lookup_float_type("float32");
2043           break;
2044         case 64:
2045           type = Type::lookup_float_type("float64");
2046           break;
2047         default:
2048           // We have to check for long double in order to support
2049           // i386 excess precision.
2050           if (mode == TYPE_MODE(long_double_type_node))
2051             return long_double_type_node;
2052           return NULL_TREE;
2053         }
2054       return type->float_type()->type_tree();
2055     }
2056   else if (mc == MODE_COMPLEX_FLOAT)
2057     {
2058       Type *type;
2059       switch (GET_MODE_BITSIZE (mode))
2060         {
2061         case 64:
2062           type = Type::lookup_complex_type("complex64");
2063           break;
2064         case 128:
2065           type = Type::lookup_complex_type("complex128");
2066           break;
2067         default:
2068           // We have to check for long double in order to support
2069           // i386 excess precision.
2070           if (mode == TYPE_MODE(complex_long_double_type_node))
2071             return complex_long_double_type_node;
2072           return NULL_TREE;
2073         }
2074       return type->complex_type()->type_tree();
2075     }
2076   else
2077     return NULL_TREE;
2078 }
2079
2080 // Return a tree which allocates SIZE bytes which will holds value of
2081 // type TYPE.
2082
2083 tree
2084 Gogo::allocate_memory(Type* type, tree size, source_location location)
2085 {
2086   // If the package imports unsafe, then it may play games with
2087   // pointers that look like integers.
2088   if (this->imported_unsafe_ || type->has_pointer())
2089     {
2090       static tree new_fndecl;
2091       return Gogo::call_builtin(&new_fndecl,
2092                                 location,
2093                                 "__go_new",
2094                                 1,
2095                                 ptr_type_node,
2096                                 sizetype,
2097                                 size);
2098     }
2099   else
2100     {
2101       static tree new_nopointers_fndecl;
2102       return Gogo::call_builtin(&new_nopointers_fndecl,
2103                                 location,
2104                                 "__go_new_nopointers",
2105                                 1,
2106                                 ptr_type_node,
2107                                 sizetype,
2108                                 size);
2109     }
2110 }
2111
2112 // Build a builtin struct with a list of fields.  The name is
2113 // STRUCT_NAME.  STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE
2114 // node; this exists so that the struct can have fields which point to
2115 // itself.  If PTYPE is not NULL, store the result in *PTYPE.  There
2116 // are NFIELDS fields.  Each field is a name (a const char*) followed
2117 // by a type (a tree).
2118
2119 tree
2120 Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type,
2121                      int nfields, ...)
2122 {
2123   if (ptype != NULL && *ptype != NULL_TREE)
2124     return *ptype;
2125
2126   va_list ap;
2127   va_start(ap, nfields);
2128
2129   tree fields = NULL_TREE;
2130   for (int i = 0; i < nfields; ++i)
2131     {
2132       const char* field_name = va_arg(ap, const char*);
2133       tree type = va_arg(ap, tree);
2134       if (type == error_mark_node)
2135         {
2136           if (ptype != NULL)
2137             *ptype = error_mark_node;
2138           return error_mark_node;
2139         }
2140       tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL,
2141                               get_identifier(field_name), type);
2142       DECL_CHAIN(field) = fields;
2143       fields = field;
2144     }
2145
2146   va_end(ap);
2147
2148   if (struct_type == NULL_TREE)
2149     struct_type = make_node(RECORD_TYPE);
2150   finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE);
2151
2152   if (ptype != NULL)
2153     {
2154       go_preserve_from_gc(struct_type);
2155       *ptype = struct_type;
2156     }
2157
2158   return struct_type;
2159 }
2160
2161 // Return a type to use for pointer to const char for a string.
2162
2163 tree
2164 Gogo::const_char_pointer_type_tree()
2165 {
2166   static tree type;
2167   if (type == NULL_TREE)
2168     {
2169       tree const_char_type = build_qualified_type(unsigned_char_type_node,
2170                                                   TYPE_QUAL_CONST);
2171       type = build_pointer_type(const_char_type);
2172       go_preserve_from_gc(type);
2173     }
2174   return type;
2175 }
2176
2177 // Return a tree for a string constant.
2178
2179 tree
2180 Gogo::string_constant_tree(const std::string& val)
2181 {
2182   tree index_type = build_index_type(size_int(val.length()));
2183   tree const_char_type = build_qualified_type(unsigned_char_type_node,
2184                                               TYPE_QUAL_CONST);
2185   tree string_type = build_array_type(const_char_type, index_type);
2186   string_type = build_variant_type_copy(string_type);
2187   TYPE_STRING_FLAG(string_type) = 1;
2188   tree string_val = build_string(val.length(), val.data());
2189   TREE_TYPE(string_val) = string_type;
2190   return string_val;
2191 }
2192
2193 // Return a tree for a Go string constant.
2194
2195 tree
2196 Gogo::go_string_constant_tree(const std::string& val)
2197 {
2198   tree string_type = Type::make_string_type()->get_tree(this);
2199
2200   VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2);
2201
2202   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
2203   tree field = TYPE_FIELDS(string_type);
2204   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0);
2205   elt->index = field;
2206   tree str = Gogo::string_constant_tree(val);
2207   elt->value = fold_convert(TREE_TYPE(field),
2208                             build_fold_addr_expr(str));
2209
2210   elt = VEC_quick_push(constructor_elt, init, NULL);
2211   field = DECL_CHAIN(field);
2212   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0);
2213   elt->index = field;
2214   elt->value = build_int_cst_type(TREE_TYPE(field), val.length());
2215
2216   tree constructor = build_constructor(string_type, init);
2217   TREE_READONLY(constructor) = 1;
2218   TREE_CONSTANT(constructor) = 1;
2219
2220   return constructor;
2221 }
2222
2223 // Return a tree for a pointer to a Go string constant.  This is only
2224 // used for type descriptors, so we return a pointer to a constant
2225 // decl.
2226
2227 tree
2228 Gogo::ptr_go_string_constant_tree(const std::string& val)
2229 {
2230   tree pval = this->go_string_constant_tree(val);
2231
2232   tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL,
2233                          create_tmp_var_name("SP"), TREE_TYPE(pval));
2234   DECL_EXTERNAL(decl) = 0;
2235   TREE_PUBLIC(decl) = 0;
2236   TREE_USED(decl) = 1;
2237   TREE_READONLY(decl) = 1;
2238   TREE_CONSTANT(decl) = 1;
2239   TREE_STATIC(decl) = 1;
2240   DECL_ARTIFICIAL(decl) = 1;
2241   DECL_INITIAL(decl) = pval;
2242   rest_of_decl_compilation(decl, 1, 0);
2243
2244   return build_fold_addr_expr(decl);
2245 }
2246
2247 // Build the type of the struct that holds a slice for the given
2248 // element type.
2249
2250 tree
2251 Gogo::slice_type_tree(tree element_type_tree)
2252 {
2253   // We use int for the count and capacity fields in a slice header.
2254   // This matches 6g.  The language definition guarantees that we
2255   // can't allocate space of a size which does not fit in int
2256   // anyhow. FIXME: integer_type_node is the the C type "int" but is
2257   // not necessarily the Go type "int".  They will differ when the C
2258   // type "int" has fewer than 32 bits.
2259   return Gogo::builtin_struct(NULL, "__go_slice", NULL_TREE, 3,
2260                               "__values",
2261                               build_pointer_type(element_type_tree),
2262                               "__count",
2263                               integer_type_node,
2264                               "__capacity",
2265                               integer_type_node);
2266 }
2267
2268 // Given the tree for a slice type, return the tree for the type of
2269 // the elements of the slice.
2270
2271 tree
2272 Gogo::slice_element_type_tree(tree slice_type_tree)
2273 {
2274   gcc_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE
2275              && POINTER_TYPE_P(TREE_TYPE(TYPE_FIELDS(slice_type_tree))));
2276   return TREE_TYPE(TREE_TYPE(TYPE_FIELDS(slice_type_tree)));
2277 }
2278
2279 // Build a constructor for a slice.  SLICE_TYPE_TREE is the type of
2280 // the slice.  VALUES is the value pointer and COUNT is the number of
2281 // entries.  If CAPACITY is not NULL, it is the capacity; otherwise
2282 // the capacity and the count are the same.
2283
2284 tree
2285 Gogo::slice_constructor(tree slice_type_tree, tree values, tree count,
2286                         tree capacity)
2287 {
2288   gcc_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE);
2289
2290   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
2291
2292   tree field = TYPE_FIELDS(slice_type_tree);
2293   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
2294   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
2295   elt->index = field;
2296   gcc_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field))
2297              == TYPE_MAIN_VARIANT(TREE_TYPE(values)));
2298   elt->value = values;
2299
2300   count = fold_convert(sizetype, count);
2301   if (capacity == NULL_TREE)
2302     {
2303       count = save_expr(count);
2304       capacity = count;
2305     }
2306
2307   field = DECL_CHAIN(field);
2308   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
2309   elt = VEC_quick_push(constructor_elt, init, NULL);
2310   elt->index = field;
2311   elt->value = fold_convert(TREE_TYPE(field), count);
2312
2313   field = DECL_CHAIN(field);
2314   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
2315   elt = VEC_quick_push(constructor_elt, init, NULL);
2316   elt->index = field;
2317   elt->value = fold_convert(TREE_TYPE(field), capacity);
2318
2319   return build_constructor(slice_type_tree, init);
2320 }
2321
2322 // Build a constructor for an empty slice.
2323
2324 tree
2325 Gogo::empty_slice_constructor(tree slice_type_tree)
2326 {
2327   tree element_field = TYPE_FIELDS(slice_type_tree);
2328   tree ret = Gogo::slice_constructor(slice_type_tree,
2329                                      fold_convert(TREE_TYPE(element_field),
2330                                                   null_pointer_node),
2331                                      size_zero_node,
2332                                      size_zero_node);
2333   TREE_CONSTANT(ret) = 1;
2334   return ret;
2335 }
2336
2337 // Build a map descriptor for a map of type MAPTYPE.
2338
2339 tree
2340 Gogo::map_descriptor(Map_type* maptype)
2341 {
2342   if (this->map_descriptors_ == NULL)
2343     this->map_descriptors_ = new Map_descriptors(10);
2344
2345   std::pair<const Map_type*, tree> val(maptype, NULL);
2346   std::pair<Map_descriptors::iterator, bool> ins =
2347     this->map_descriptors_->insert(val);
2348   Map_descriptors::iterator p = ins.first;
2349   if (!ins.second)
2350     {
2351       if (p->second == error_mark_node)
2352         return error_mark_node;
2353       gcc_assert(p->second != NULL_TREE && DECL_P(p->second));
2354       return build_fold_addr_expr(p->second);
2355     }
2356
2357   Type* keytype = maptype->key_type();
2358   Type* valtype = maptype->val_type();
2359
2360   std::string mangled_name = ("__go_map_" + maptype->mangled_name(this));
2361
2362   tree id = get_identifier_from_string(mangled_name);
2363
2364   // Get the type of the map descriptor.  This is __go_map_descriptor
2365   // in libgo/map.h.
2366
2367   tree struct_type = this->map_descriptor_type();
2368
2369   // The map entry type is a struct with three fields.  This struct is
2370   // specific to MAPTYPE.  Build it.
2371
2372   tree map_entry_type = make_node(RECORD_TYPE);
2373
2374   map_entry_type = Gogo::builtin_struct(NULL, "__map", map_entry_type, 3,
2375                                         "__next",
2376                                         build_pointer_type(map_entry_type),
2377                                         "__key",
2378                                         keytype->get_tree(this),
2379                                         "__val",
2380                                         valtype->get_tree(this));
2381   if (map_entry_type == error_mark_node)
2382     {
2383       p->second = error_mark_node;
2384       return error_mark_node;
2385     }
2386
2387   tree map_entry_key_field = DECL_CHAIN(TYPE_FIELDS(map_entry_type));
2388   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_key_field)),
2389                     "__key") == 0);
2390
2391   tree map_entry_val_field = DECL_CHAIN(map_entry_key_field);
2392   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_val_field)),
2393                     "__val") == 0);
2394
2395   // Initialize the entries.
2396
2397   tree map_descriptor_field = TYPE_FIELDS(struct_type);
2398   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_descriptor_field)),
2399                     "__map_descriptor") == 0);
2400   tree entry_size_field = DECL_CHAIN(map_descriptor_field);
2401   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(entry_size_field)),
2402                     "__entry_size") == 0);
2403   tree key_offset_field = DECL_CHAIN(entry_size_field);
2404   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(key_offset_field)),
2405                     "__key_offset") == 0);
2406   tree val_offset_field = DECL_CHAIN(key_offset_field);
2407   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(val_offset_field)),
2408                     "__val_offset") == 0);
2409
2410   VEC(constructor_elt, gc)* descriptor = VEC_alloc(constructor_elt, gc, 6);
2411
2412   constructor_elt* elt = VEC_quick_push(constructor_elt, descriptor, NULL);
2413   elt->index = map_descriptor_field;
2414   elt->value = maptype->type_descriptor_pointer(this);
2415
2416   elt = VEC_quick_push(constructor_elt, descriptor, NULL);
2417   elt->index = entry_size_field;
2418   elt->value = TYPE_SIZE_UNIT(map_entry_type);
2419
2420   elt = VEC_quick_push(constructor_elt, descriptor, NULL);
2421   elt->index = key_offset_field;
2422   elt->value = byte_position(map_entry_key_field);
2423
2424   elt = VEC_quick_push(constructor_elt, descriptor, NULL);
2425   elt->index = val_offset_field;
2426   elt->value = byte_position(map_entry_val_field);
2427
2428   tree constructor = build_constructor(struct_type, descriptor);
2429
2430   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, struct_type);
2431   TREE_STATIC(decl) = 1;
2432   TREE_USED(decl) = 1;
2433   TREE_READONLY(decl) = 1;
2434   TREE_CONSTANT(decl) = 1;
2435   DECL_INITIAL(decl) = constructor;
2436   make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2437   resolve_unique_section(decl, 1, 0);
2438
2439   rest_of_decl_compilation(decl, 1, 0);
2440
2441   go_preserve_from_gc(decl);
2442   p->second = decl;
2443
2444   return build_fold_addr_expr(decl);
2445 }
2446
2447 // Return a tree for the type of a map descriptor.  This is struct
2448 // __go_map_descriptor in libgo/runtime/map.h.  This is the same for
2449 // all map types.
2450
2451 tree
2452 Gogo::map_descriptor_type()
2453 {
2454   static tree struct_type;
2455   tree dtype = Type::make_type_descriptor_type()->get_tree(this);
2456   dtype = build_qualified_type(dtype, TYPE_QUAL_CONST);
2457   return Gogo::builtin_struct(&struct_type, "__go_map_descriptor", NULL_TREE,
2458                               4,
2459                               "__map_descriptor",
2460                               build_pointer_type(dtype),
2461                               "__entry_size",
2462                               sizetype,
2463                               "__key_offset",
2464                               sizetype,
2465                               "__val_offset",
2466                               sizetype);
2467 }
2468
2469 // Return the name to use for a type descriptor decl for TYPE.  This
2470 // is used when TYPE does not have a name.
2471
2472 std::string
2473 Gogo::unnamed_type_descriptor_decl_name(const Type* type)
2474 {
2475   return "__go_td_" + type->mangled_name(this);
2476 }
2477
2478 // Return the name to use for a type descriptor decl for a type named
2479 // NAME, defined in the function IN_FUNCTION.  IN_FUNCTION will
2480 // normally be NULL.
2481
2482 std::string
2483 Gogo::type_descriptor_decl_name(const Named_object* no,
2484                                 const Named_object* in_function)
2485 {
2486   std::string ret = "__go_tdn_";
2487   if (no->type_value()->is_builtin())
2488     gcc_assert(in_function == NULL);
2489   else
2490     {
2491       const std::string& unique_prefix(no->package() == NULL
2492                                        ? this->unique_prefix()
2493                                        : no->package()->unique_prefix());
2494       const std::string& package_name(no->package() == NULL
2495                                       ? this->package_name()
2496                                       : no->package()->name());
2497       ret.append(unique_prefix);
2498       ret.append(1, '.');
2499       ret.append(package_name);
2500       ret.append(1, '.');
2501       if (in_function != NULL)
2502         {
2503           ret.append(Gogo::unpack_hidden_name(in_function->name()));
2504           ret.append(1, '.');
2505         }
2506     }
2507   ret.append(no->name());
2508   return ret;
2509 }
2510
2511 // Where a type descriptor decl should be defined.
2512
2513 Gogo::Type_descriptor_location
2514 Gogo::type_descriptor_location(const Type* type)
2515 {
2516   const Named_type* name = type->named_type();
2517   if (name != NULL)
2518     {
2519       if (name->named_object()->package() != NULL)
2520         {
2521           // This is a named type defined in a different package.  The
2522           // descriptor should be defined in that package.
2523           return TYPE_DESCRIPTOR_UNDEFINED;
2524         }
2525       else if (name->is_builtin())
2526         {
2527           // We create the descriptor for a builtin type whenever we
2528           // need it.
2529           return TYPE_DESCRIPTOR_COMMON;
2530         }
2531       else
2532         {
2533           // This is a named type defined in this package.  The
2534           // descriptor should be defined here.
2535           return TYPE_DESCRIPTOR_DEFINED;
2536         }
2537     }
2538   else
2539     {
2540       if (type->points_to() != NULL
2541           && type->points_to()->named_type() != NULL
2542           && type->points_to()->named_type()->named_object()->package() != NULL)
2543         {
2544           // This is an unnamed pointer to a named type defined in a
2545           // different package.  The descriptor should be defined in
2546           // that package.
2547           return TYPE_DESCRIPTOR_UNDEFINED;
2548         }
2549       else
2550         {
2551           // This is an unnamed type.  The descriptor could be defined
2552           // in any package where it is needed, and the linker will
2553           // pick one descriptor to keep.
2554           return TYPE_DESCRIPTOR_COMMON;
2555         }
2556     }
2557 }
2558
2559 // Build a type descriptor decl for TYPE.  INITIALIZER is a struct
2560 // composite literal which initializers the type descriptor.
2561
2562 void
2563 Gogo::build_type_descriptor_decl(const Type* type, Expression* initializer,
2564                                  tree* pdecl)
2565 {
2566   const Named_type* name = type->named_type();
2567
2568   // We can have multiple instances of unnamed types, but we only want
2569   // to emit the type descriptor once.  We use a hash table to handle
2570   // this.  This is not necessary for named types, as they are unique,
2571   // and we store the type descriptor decl in the type itself.
2572   tree* phash = NULL;
2573   if (name == NULL)
2574     {
2575       if (this->type_descriptor_decls_ == NULL)
2576         this->type_descriptor_decls_ = new Type_descriptor_decls(10);
2577
2578       std::pair<Type_descriptor_decls::iterator, bool> ins =
2579         this->type_descriptor_decls_->insert(std::make_pair(type, NULL_TREE));
2580       if (!ins.second)
2581         {
2582           // We've already built a type descriptor for this type.
2583           *pdecl = ins.first->second;
2584           return;
2585         }
2586       phash = &ins.first->second;
2587     }
2588
2589   std::string decl_name;
2590   if (name == NULL)
2591     decl_name = this->unnamed_type_descriptor_decl_name(type);
2592   else
2593     decl_name = this->type_descriptor_decl_name(name->named_object(),
2594                                                 name->in_function());
2595   tree id = get_identifier_from_string(decl_name);
2596   tree descriptor_type_tree = initializer->type()->get_tree(this);
2597   if (descriptor_type_tree == error_mark_node)
2598     {
2599       *pdecl = error_mark_node;
2600       return;
2601     }
2602   tree decl = build_decl(name == NULL ? BUILTINS_LOCATION : name->location(),
2603                          VAR_DECL, id,
2604                          build_qualified_type(descriptor_type_tree,
2605                                               TYPE_QUAL_CONST));
2606   TREE_READONLY(decl) = 1;
2607   TREE_CONSTANT(decl) = 1;
2608   DECL_ARTIFICIAL(decl) = 1;
2609
2610   go_preserve_from_gc(decl);
2611   if (phash != NULL)
2612     *phash = decl;
2613
2614   // We store the new DECL now because we may need to refer to it when
2615   // expanding INITIALIZER.
2616   *pdecl = decl;
2617
2618   // If appropriate, just refer to the exported type identifier.
2619   Gogo::Type_descriptor_location type_descriptor_location =
2620     this->type_descriptor_location(type);
2621   if (type_descriptor_location == TYPE_DESCRIPTOR_UNDEFINED)
2622     {
2623       TREE_PUBLIC(decl) = 1;
2624       DECL_EXTERNAL(decl) = 1;
2625       return;
2626     }
2627
2628   TREE_STATIC(decl) = 1;
2629   TREE_USED(decl) = 1;
2630
2631   Translate_context context(this, NULL, NULL, NULL);
2632   context.set_is_const();
2633   tree constructor = initializer->get_tree(&context);
2634
2635   if (constructor == error_mark_node)
2636     gcc_assert(saw_errors());
2637
2638   DECL_INITIAL(decl) = constructor;
2639
2640   if (type_descriptor_location == TYPE_DESCRIPTOR_DEFINED)
2641     TREE_PUBLIC(decl) = 1;
2642   else
2643     {
2644       gcc_assert(type_descriptor_location == TYPE_DESCRIPTOR_COMMON);
2645       make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2646       resolve_unique_section(decl, 1, 0);
2647     }
2648
2649   rest_of_decl_compilation(decl, 1, 0);
2650 }
2651
2652 // Build an interface method table for a type: a list of function
2653 // pointers, one for each interface method.  This is used for
2654 // interfaces.
2655
2656 tree
2657 Gogo::interface_method_table_for_type(const Interface_type* interface,
2658                                       Named_type* type,
2659                                       bool is_pointer)
2660 {
2661   const Typed_identifier_list* interface_methods = interface->methods();
2662   gcc_assert(!interface_methods->empty());
2663
2664   std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_")
2665                               + interface->mangled_name(this)
2666                               + "__"
2667                               + type->mangled_name(this));
2668
2669   tree id = get_identifier_from_string(mangled_name);
2670
2671   // See whether this interface has any hidden methods.
2672   bool has_hidden_methods = false;
2673   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2674        p != interface_methods->end();
2675        ++p)
2676     {
2677       if (Gogo::is_hidden_name(p->name()))
2678         {
2679           has_hidden_methods = true;
2680           break;
2681         }
2682     }
2683
2684   // We already know that the named type is convertible to the
2685   // interface.  If the interface has hidden methods, and the named
2686   // type is defined in a different package, then the interface
2687   // conversion table will be defined by that other package.
2688   if (has_hidden_methods && type->named_object()->package() != NULL)
2689     {
2690       tree array_type = build_array_type(const_ptr_type_node, NULL);
2691       tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2692       TREE_READONLY(decl) = 1;
2693       TREE_CONSTANT(decl) = 1;
2694       TREE_PUBLIC(decl) = 1;
2695       DECL_EXTERNAL(decl) = 1;
2696       go_preserve_from_gc(decl);
2697       return decl;
2698     }
2699
2700   size_t count = interface_methods->size();
2701   VEC(constructor_elt, gc)* pointers = VEC_alloc(constructor_elt, gc,
2702                                                  count + 1);
2703
2704   // The first element is the type descriptor.
2705   constructor_elt* elt = VEC_quick_push(constructor_elt, pointers, NULL);
2706   elt->index = size_zero_node;
2707   Type* td_type;
2708   if (!is_pointer)
2709     td_type = type;
2710   else
2711     td_type = Type::make_pointer_type(type);
2712   elt->value = fold_convert(const_ptr_type_node,
2713                             td_type->type_descriptor_pointer(this));
2714
2715   size_t i = 1;
2716   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2717        p != interface_methods->end();
2718        ++p, ++i)
2719     {
2720       bool is_ambiguous;
2721       Method* m = type->method_function(p->name(), &is_ambiguous);
2722       gcc_assert(m != NULL);
2723
2724       Named_object* no = m->named_object();
2725
2726       tree fnid = no->get_id(this);
2727
2728       tree fndecl;
2729       if (no->is_function())
2730         fndecl = no->func_value()->get_or_make_decl(this, no, fnid);
2731       else if (no->is_function_declaration())
2732         fndecl = no->func_declaration_value()->get_or_make_decl(this, no,
2733                                                                 fnid);
2734       else
2735         gcc_unreachable();
2736       fndecl = build_fold_addr_expr(fndecl);
2737
2738       elt = VEC_quick_push(constructor_elt, pointers, NULL);
2739       elt->index = size_int(i);
2740       elt->value = fold_convert(const_ptr_type_node, fndecl);
2741     }
2742   gcc_assert(i == count + 1);
2743
2744   tree array_type = build_array_type(const_ptr_type_node,
2745                                      build_index_type(size_int(count)));
2746   tree constructor = build_constructor(array_type, pointers);
2747
2748   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2749   TREE_STATIC(decl) = 1;
2750   TREE_USED(decl) = 1;
2751   TREE_READONLY(decl) = 1;
2752   TREE_CONSTANT(decl) = 1;
2753   DECL_INITIAL(decl) = constructor;
2754
2755   // If the interface type has hidden methods, then this is the only
2756   // definition of the table.  Otherwise it is a comdat table which
2757   // may be defined in multiple packages.
2758   if (has_hidden_methods)
2759     TREE_PUBLIC(decl) = 1;
2760   else
2761     {
2762       make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2763       resolve_unique_section(decl, 1, 0);
2764     }
2765
2766   rest_of_decl_compilation(decl, 1, 0);
2767
2768   go_preserve_from_gc(decl);
2769
2770   return decl;
2771 }
2772
2773 // Mark a function as a builtin library function.
2774
2775 void
2776 Gogo::mark_fndecl_as_builtin_library(tree fndecl)
2777 {
2778   DECL_EXTERNAL(fndecl) = 1;
2779   TREE_PUBLIC(fndecl) = 1;
2780   DECL_ARTIFICIAL(fndecl) = 1;
2781   TREE_NOTHROW(fndecl) = 1;
2782   DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT;
2783   DECL_VISIBILITY_SPECIFIED(fndecl) = 1;
2784 }
2785
2786 // Build a call to a builtin function.
2787
2788 tree
2789 Gogo::call_builtin(tree* pdecl, source_location location, const char* name,
2790                    int nargs, tree rettype, ...)
2791 {
2792   if (rettype == error_mark_node)
2793     return error_mark_node;
2794
2795   tree* types = new tree[nargs];
2796   tree* args = new tree[nargs];
2797
2798   va_list ap;
2799   va_start(ap, rettype);
2800   for (int i = 0; i < nargs; ++i)
2801     {
2802       types[i] = va_arg(ap, tree);
2803       args[i] = va_arg(ap, tree);
2804       if (types[i] == error_mark_node || args[i] == error_mark_node)
2805         {
2806           delete[] types;
2807           delete[] args;
2808           return error_mark_node;
2809         }
2810     }
2811   va_end(ap);
2812
2813   if (*pdecl == NULL_TREE)
2814     {
2815       tree fnid = get_identifier(name);
2816
2817       tree argtypes = NULL_TREE;
2818       tree* pp = &argtypes;
2819       for (int i = 0; i < nargs; ++i)
2820         {
2821           *pp = tree_cons(NULL_TREE, types[i], NULL_TREE);
2822           pp = &TREE_CHAIN(*pp);
2823         }
2824       *pp = void_list_node;
2825
2826       tree fntype = build_function_type(rettype, argtypes);
2827
2828       *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype);
2829       Gogo::mark_fndecl_as_builtin_library(*pdecl);
2830       go_preserve_from_gc(*pdecl);
2831     }
2832
2833   tree fnptr = build_fold_addr_expr(*pdecl);
2834   if (CAN_HAVE_LOCATION_P(fnptr))
2835     SET_EXPR_LOCATION(fnptr, location);
2836
2837   tree ret = build_call_array(rettype, fnptr, nargs, args);
2838   SET_EXPR_LOCATION(ret, location);
2839
2840   delete[] types;
2841   delete[] args;
2842
2843   return ret;
2844 }
2845
2846 // Build a call to the runtime error function.
2847
2848 tree
2849 Gogo::runtime_error(int code, source_location location)
2850 {
2851   static tree runtime_error_fndecl;
2852   tree ret = Gogo::call_builtin(&runtime_error_fndecl,
2853                                 location,
2854                                 "__go_runtime_error",
2855                                 1,
2856                                 void_type_node,
2857                                 integer_type_node,
2858                                 build_int_cst(integer_type_node, code));
2859   if (ret == error_mark_node)
2860     return error_mark_node;
2861   // The runtime error function panics and does not return.
2862   TREE_NOTHROW(runtime_error_fndecl) = 0;
2863   TREE_THIS_VOLATILE(runtime_error_fndecl) = 1;
2864   return ret;
2865 }
2866
2867 // Send VAL on CHANNEL.  If BLOCKING is true, the resulting tree has a
2868 // void type.  If BLOCKING is false, the resulting tree has a boolean
2869 // type, and it will evaluate as true if the value was sent.  If
2870 // FOR_SELECT is true, this is being done because it was chosen in a
2871 // select statement.
2872
2873 tree
2874 Gogo::send_on_channel(tree channel, tree val, bool blocking, bool for_select,
2875                       source_location location)
2876 {
2877   if (channel == error_mark_node || val == error_mark_node)
2878     return error_mark_node;
2879
2880   if (int_size_in_bytes(TREE_TYPE(val)) <= 8
2881       && !AGGREGATE_TYPE_P(TREE_TYPE(val))
2882       && !FLOAT_TYPE_P(TREE_TYPE(val)))
2883     {
2884       val = convert_to_integer(uint64_type_node, val);
2885       if (blocking)
2886         {
2887           static tree send_small_fndecl;
2888           tree ret = Gogo::call_builtin(&send_small_fndecl,
2889                                         location,
2890                                         "__go_send_small",
2891                                         3,
2892                                         void_type_node,
2893                                         ptr_type_node,
2894                                         channel,
2895                                         uint64_type_node,
2896                                         val,
2897                                         boolean_type_node,
2898                                         (for_select
2899                                          ? boolean_true_node
2900                                          : boolean_false_node));
2901           if (ret == error_mark_node)
2902             return error_mark_node;
2903           // This can panic if there are too many operations on a
2904           // closed channel.
2905           TREE_NOTHROW(send_small_fndecl) = 0;
2906           return ret;
2907         }
2908       else
2909         {
2910           gcc_assert(!for_select);
2911           static tree send_nonblocking_small_fndecl;
2912           tree ret = Gogo::call_builtin(&send_nonblocking_small_fndecl,
2913                                         location,
2914                                         "__go_send_nonblocking_small",
2915                                         2,
2916                                         boolean_type_node,
2917                                         ptr_type_node,
2918                                         channel,
2919                                         uint64_type_node,
2920                                         val);
2921           if (ret == error_mark_node)
2922             return error_mark_node;
2923           // This can panic if there are too many operations on a
2924           // closed channel.
2925           TREE_NOTHROW(send_nonblocking_small_fndecl) = 0;
2926           return ret;
2927         }
2928     }
2929   else
2930     {
2931       tree make_tmp;
2932       if (TREE_ADDRESSABLE(TREE_TYPE(val)) || TREE_CODE(val) == VAR_DECL)
2933         {
2934           make_tmp = NULL_TREE;
2935           val = build_fold_addr_expr(val);
2936           if (DECL_P(val))
2937             TREE_ADDRESSABLE(val) = 1;
2938         }
2939       else
2940         {
2941           tree tmp = create_tmp_var(TREE_TYPE(val), get_name(val));
2942           DECL_IGNORED_P(tmp) = 0;
2943           DECL_INITIAL(tmp) = val;
2944           TREE_ADDRESSABLE(tmp) = 1;
2945           make_tmp = build1(DECL_EXPR, void_type_node, tmp);
2946           SET_EXPR_LOCATION(make_tmp, location);
2947           val = build_fold_addr_expr(tmp);
2948         }
2949       val = fold_convert(ptr_type_node, val);
2950
2951       tree call;
2952       if (blocking)
2953         {
2954           static tree send_big_fndecl;
2955           call = Gogo::call_builtin(&send_big_fndecl,
2956                                     location,
2957                                     "__go_send_big",
2958                                     3,
2959                                     void_type_node,
2960                                     ptr_type_node,
2961                                     channel,
2962                                     ptr_type_node,
2963                                     val,
2964                                     boolean_type_node,
2965                                     (for_select
2966                                      ? boolean_true_node
2967                                      : boolean_false_node));
2968           if (call == error_mark_node)
2969             return error_mark_node;
2970           // This can panic if there are too many operations on a
2971           // closed channel.
2972           TREE_NOTHROW(send_big_fndecl) = 0;
2973         }
2974       else
2975         {
2976           gcc_assert(!for_select);
2977           static tree send_nonblocking_big_fndecl;
2978           call = Gogo::call_builtin(&send_nonblocking_big_fndecl,
2979                                     location,
2980                                     "__go_send_nonblocking_big",
2981                                     2,
2982                                     boolean_type_node,
2983                                     ptr_type_node,
2984                                     channel,
2985                                     ptr_type_node,
2986                                     val);
2987           if (call == error_mark_node)
2988             return error_mark_node;
2989           // This can panic if there are too many operations on a
2990           // closed channel.
2991           TREE_NOTHROW(send_nonblocking_big_fndecl) = 0;
2992         }
2993
2994       if (make_tmp == NULL_TREE)
2995         return call;
2996       else
2997         {
2998           tree ret = build2(COMPOUND_EXPR, TREE_TYPE(call), make_tmp, call);
2999           SET_EXPR_LOCATION(ret, location);
3000           return ret;
3001         }
3002     }
3003 }
3004
3005 // Return a tree for receiving a value of type TYPE_TREE on CHANNEL.
3006 // This does a blocking receive and returns the value read from the
3007 // channel.  If FOR_SELECT is true, this is being done because it was
3008 // chosen in a select statement.
3009
3010 tree
3011 Gogo::receive_from_channel(tree type_tree, tree channel, bool for_select,
3012                            source_location location)
3013 {
3014   if (type_tree == error_mark_node || channel == error_mark_node)
3015     return error_mark_node;
3016
3017   if (int_size_in_bytes(type_tree) <= 8
3018       && !AGGREGATE_TYPE_P(type_tree)
3019       && !FLOAT_TYPE_P(type_tree))
3020     {
3021       static tree receive_small_fndecl;
3022       tree call = Gogo::call_builtin(&receive_small_fndecl,
3023                                      location,
3024                                      "__go_receive_small",
3025                                      2,
3026                                      uint64_type_node,
3027                                      ptr_type_node,
3028                                      channel,
3029                                      boolean_type_node,
3030                                      (for_select
3031                                       ? boolean_true_node
3032                                       : boolean_false_node));
3033       if (call == error_mark_node)
3034         return error_mark_node;
3035       // This can panic if there are too many operations on a closed
3036       // channel.
3037       TREE_NOTHROW(receive_small_fndecl) = 0;
3038       int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree));
3039       tree int_type_tree = go_type_for_size(bitsize, 1);
3040       return fold_convert_loc(location, type_tree,
3041                               fold_convert_loc(location, int_type_tree,
3042                                                call));
3043     }
3044   else
3045     {
3046       tree tmp = create_tmp_var(type_tree, get_name(type_tree));
3047       DECL_IGNORED_P(tmp) = 0;
3048       TREE_ADDRESSABLE(tmp) = 1;
3049       tree make_tmp = build1(DECL_EXPR, void_type_node, tmp);
3050       SET_EXPR_LOCATION(make_tmp, location);
3051       tree tmpaddr = build_fold_addr_expr(tmp);
3052       tmpaddr = fold_convert(ptr_type_node, tmpaddr);
3053       static tree receive_big_fndecl;
3054       tree call = Gogo::call_builtin(&receive_big_fndecl,
3055                                      location,
3056                                      "__go_receive_big",
3057                                      3,
3058                                      void_type_node,
3059                                      ptr_type_node,
3060                                      channel,
3061                                      ptr_type_node,
3062                                      tmpaddr,
3063                                      boolean_type_node,
3064                                      (for_select
3065                                       ? boolean_true_node
3066                                       : boolean_false_node));
3067       if (call == error_mark_node)
3068         return error_mark_node;
3069       // This can panic if there are too many operations on a closed
3070       // channel.
3071       TREE_NOTHROW(receive_big_fndecl) = 0;
3072       return build2(COMPOUND_EXPR, type_tree, make_tmp,
3073                     build2(COMPOUND_EXPR, type_tree, call, tmp));
3074     }
3075 }
3076
3077 // Return the type of a function trampoline.  This is like
3078 // get_trampoline_type in tree-nested.c.
3079
3080 tree
3081 Gogo::trampoline_type_tree()
3082 {
3083   static tree type_tree;
3084   if (type_tree == NULL_TREE)
3085     {
3086       unsigned int size;
3087       unsigned int align;
3088       go_trampoline_info(&size, &align);
3089       tree t = build_index_type(build_int_cst(integer_type_node, size - 1));
3090       t = build_array_type(char_type_node, t);
3091
3092       type_tree = Gogo::builtin_struct(NULL, "__go_trampoline", NULL_TREE, 1,
3093                                        "__data", t);
3094       t = TYPE_FIELDS(type_tree);
3095       DECL_ALIGN(t) = align;
3096       DECL_USER_ALIGN(t) = 1;
3097
3098       go_preserve_from_gc(type_tree);
3099     }
3100   return type_tree;
3101 }
3102
3103 // Make a trampoline which calls FNADDR passing CLOSURE.
3104
3105 tree
3106 Gogo::make_trampoline(tree fnaddr, tree closure, source_location location)
3107 {
3108   tree trampoline_type = Gogo::trampoline_type_tree();
3109   tree trampoline_size = TYPE_SIZE_UNIT(trampoline_type);
3110
3111   closure = save_expr(closure);
3112
3113   // We allocate the trampoline using a special function which will
3114   // mark it as executable.
3115   static tree trampoline_fndecl;
3116   tree x = Gogo::call_builtin(&trampoline_fndecl,
3117                               location,
3118                               "__go_allocate_trampoline",
3119                               2,
3120                               ptr_type_node,
3121                               size_type_node,
3122                               trampoline_size,
3123                               ptr_type_node,
3124                               fold_convert_loc(location, ptr_type_node,
3125                                                closure));
3126   if (x == error_mark_node)
3127     return error_mark_node;
3128
3129   x = save_expr(x);
3130
3131   // Initialize the trampoline.
3132   tree ini = build_call_expr(implicit_built_in_decls[BUILT_IN_INIT_TRAMPOLINE],
3133                              3, x, fnaddr, closure);
3134
3135   // On some targets the trampoline address needs to be adjusted.  For
3136   // example, when compiling in Thumb mode on the ARM, the address
3137   // needs to have the low bit set.
3138   x = build_call_expr(implicit_built_in_decls[BUILT_IN_ADJUST_TRAMPOLINE],
3139                       1, x);
3140   x = fold_convert(TREE_TYPE(fnaddr), x);
3141
3142   return build2(COMPOUND_EXPR, TREE_TYPE(x), ini, x);
3143 }