OSDN Git Service

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