OSDN Git Service

Check for errors from Gogo::call_builtin.
[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)
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   gcc_assert(TREE_CODE(block_tree) == BIND_EXPR);
1213   tree statements = BIND_EXPR_BODY(block_tree);
1214   while (TREE_CODE(statements) == TRY_FINALLY_EXPR
1215          || TREE_CODE(statements) == TRY_CATCH_EXPR)
1216     statements = TREE_OPERAND(statements, 0);
1217
1218   // It's possible to have pre-init statements without an initializer
1219   // if the pre-init statements set the variable.
1220   if (this->init_ != NULL)
1221     {
1222       tree rhs_tree = this->init_->get_tree(&context);
1223       if (var_decl == NULL_TREE)
1224         append_to_statement_list(rhs_tree, &statements);
1225       else
1226         {
1227           tree val = Expression::convert_for_assignment(&context, this->type(),
1228                                                         this->init_->type(),
1229                                                         rhs_tree,
1230                                                         this->location());
1231           tree set = fold_build2_loc(this->location(), MODIFY_EXPR,
1232                                      void_type_node, var_decl, val);
1233           append_to_statement_list(set, &statements);
1234         }
1235     }
1236
1237   return block_tree;
1238 }
1239
1240 // Get a tree for a function decl.
1241
1242 tree
1243 Function::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1244 {
1245   if (this->fndecl_ == NULL_TREE)
1246     {
1247       tree functype = this->type_->get_tree(gogo);
1248       if (functype == error_mark_node)
1249         this->fndecl_ = error_mark_node;
1250       else
1251         {
1252           // The type of a function comes back as a pointer, but we
1253           // want the real function type for a function declaration.
1254           gcc_assert(POINTER_TYPE_P(functype));
1255           functype = TREE_TYPE(functype);
1256           tree decl = build_decl(this->location(), FUNCTION_DECL, id, functype);
1257
1258           this->fndecl_ = decl;
1259
1260           gcc_assert(no->package() == NULL);
1261           if (this->enclosing_ != NULL || Gogo::is_thunk(no))
1262             ;
1263           else if (Gogo::unpack_hidden_name(no->name()) == "init"
1264                    && !this->type_->is_method())
1265             ;
1266           else if (Gogo::unpack_hidden_name(no->name()) == "main"
1267                    && gogo->package_name() == "main")
1268             TREE_PUBLIC(decl) = 1;
1269           // Methods have to be public even if they are hidden because
1270           // they can be pulled into type descriptors when using
1271           // anonymous fields.
1272           else if (!Gogo::is_hidden_name(no->name())
1273                    || this->type_->is_method())
1274             {
1275               TREE_PUBLIC(decl) = 1;
1276               std::string asm_name = gogo->unique_prefix();
1277               asm_name.append(1, '.');
1278               asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id));
1279               SET_DECL_ASSEMBLER_NAME(decl,
1280                                       get_identifier_from_string(asm_name));
1281             }
1282
1283           // Why do we have to do this in the frontend?
1284           tree restype = TREE_TYPE(functype);
1285           tree resdecl = build_decl(this->location(), RESULT_DECL, NULL_TREE,
1286                                     restype);
1287           DECL_ARTIFICIAL(resdecl) = 1;
1288           DECL_IGNORED_P(resdecl) = 1;
1289           DECL_CONTEXT(resdecl) = decl;
1290           DECL_RESULT(decl) = resdecl;
1291
1292           if (this->enclosing_ != NULL)
1293             DECL_STATIC_CHAIN(decl) = 1;
1294
1295           // If a function calls the predeclared recover function, we
1296           // can't inline it, because recover behaves differently in a
1297           // function passed directly to defer.
1298           if (this->calls_recover_ && !this->is_recover_thunk_)
1299             DECL_UNINLINABLE(decl) = 1;
1300
1301           // If this is a thunk created to call a function which calls
1302           // the predeclared recover function, we need to disable
1303           // stack splitting for the thunk.
1304           if (this->is_recover_thunk_)
1305             {
1306               tree attr = get_identifier("__no_split_stack__");
1307               DECL_ATTRIBUTES(decl) = tree_cons(attr, NULL_TREE, NULL_TREE);
1308             }
1309
1310           go_preserve_from_gc(decl);
1311
1312           if (this->closure_var_ != NULL)
1313             {
1314               push_struct_function(decl);
1315
1316               tree closure_decl = this->closure_var_->get_tree(gogo, no);
1317               if (closure_decl == error_mark_node)
1318                 this->fndecl_ = error_mark_node;
1319               else
1320                 {
1321                   DECL_ARTIFICIAL(closure_decl) = 1;
1322                   DECL_IGNORED_P(closure_decl) = 1;
1323                   TREE_USED(closure_decl) = 1;
1324                   DECL_ARG_TYPE(closure_decl) = TREE_TYPE(closure_decl);
1325                   TREE_READONLY(closure_decl) = 1;
1326
1327                   DECL_STRUCT_FUNCTION(decl)->static_chain_decl = closure_decl;
1328                 }
1329
1330               pop_cfun();
1331             }
1332         }
1333     }
1334   return this->fndecl_;
1335 }
1336
1337 // Get a tree for a function declaration.
1338
1339 tree
1340 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1341 {
1342   if (this->fndecl_ == NULL_TREE)
1343     {
1344       // Let Go code use an asm declaration to pick up a builtin
1345       // function.
1346       if (!this->asm_name_.empty())
1347         {
1348           std::map<std::string, tree>::const_iterator p =
1349             builtin_functions.find(this->asm_name_);
1350           if (p != builtin_functions.end())
1351             {
1352               this->fndecl_ = p->second;
1353               return this->fndecl_;
1354             }
1355         }
1356
1357       tree functype = this->fntype_->get_tree(gogo);
1358       tree decl;
1359       if (functype == error_mark_node)
1360         decl = error_mark_node;
1361       else
1362         {
1363           // The type of a function comes back as a pointer, but we
1364           // want the real function type for a function declaration.
1365           gcc_assert(POINTER_TYPE_P(functype));
1366           functype = TREE_TYPE(functype);
1367           decl = build_decl(this->location(), FUNCTION_DECL, id, functype);
1368           TREE_PUBLIC(decl) = 1;
1369           DECL_EXTERNAL(decl) = 1;
1370
1371           if (this->asm_name_.empty())
1372             {
1373               std::string asm_name = (no->package() == NULL
1374                                       ? gogo->unique_prefix()
1375                                       : no->package()->unique_prefix());
1376               asm_name.append(1, '.');
1377               asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id));
1378               SET_DECL_ASSEMBLER_NAME(decl,
1379                                       get_identifier_from_string(asm_name));
1380             }
1381         }
1382       this->fndecl_ = decl;
1383       go_preserve_from_gc(decl);
1384     }
1385   return this->fndecl_;
1386 }
1387
1388 // We always pass the receiver to a method as a pointer.  If the
1389 // receiver is actually declared as a non-pointer type, then we copy
1390 // the value into a local variable, so that it has the right type.  In
1391 // this function we create the real PARM_DECL to use, and set
1392 // DEC_INITIAL of the var_decl to be the value passed in.
1393
1394 tree
1395 Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl)
1396 {
1397   if (var_decl == error_mark_node)
1398     return error_mark_node;
1399   // If the function takes the address of a receiver which is passed
1400   // by value, then we will have an INDIRECT_REF here.  We need to get
1401   // the real variable.
1402   bool is_in_heap = no->var_value()->is_in_heap();
1403   tree val_type;
1404   if (TREE_CODE(var_decl) != INDIRECT_REF)
1405     {
1406       gcc_assert(!is_in_heap);
1407       val_type = TREE_TYPE(var_decl);
1408     }
1409   else
1410     {
1411       gcc_assert(is_in_heap);
1412       var_decl = TREE_OPERAND(var_decl, 0);
1413       if (var_decl == error_mark_node)
1414         return error_mark_node;
1415       gcc_assert(POINTER_TYPE_P(TREE_TYPE(var_decl)));
1416       val_type = TREE_TYPE(TREE_TYPE(var_decl));
1417     }
1418   gcc_assert(TREE_CODE(var_decl) == VAR_DECL);
1419   source_location loc = DECL_SOURCE_LOCATION(var_decl);
1420   std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1421   name += ".pointer";
1422   tree id = get_identifier_from_string(name);
1423   tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type));
1424   DECL_CONTEXT(parm_decl) = current_function_decl;
1425   DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl);
1426
1427   gcc_assert(DECL_INITIAL(var_decl) == NULL_TREE);
1428   // The receiver might be passed as a null pointer.
1429   tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node, parm_decl,
1430                                fold_convert_loc(loc, TREE_TYPE(parm_decl),
1431                                                 null_pointer_node));
1432   tree ind = build_fold_indirect_ref_loc(loc, parm_decl);
1433   TREE_THIS_NOTRAP(ind) = 1;
1434   tree zero_init = no->var_value()->type()->get_init_tree(gogo, false);
1435   tree init = fold_build3_loc(loc, COND_EXPR, TREE_TYPE(ind),
1436                               check, ind, zero_init);
1437
1438   if (is_in_heap)
1439     {
1440       tree size = TYPE_SIZE_UNIT(val_type);
1441       tree space = gogo->allocate_memory(no->var_value()->type(), size,
1442                                          no->location());
1443       space = save_expr(space);
1444       space = fold_convert(build_pointer_type(val_type), space);
1445       tree spaceref = build_fold_indirect_ref_loc(no->location(), space);
1446       TREE_THIS_NOTRAP(spaceref) = 1;
1447       tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node,
1448                                    parm_decl,
1449                                    fold_convert_loc(loc, TREE_TYPE(parm_decl),
1450                                                     null_pointer_node));
1451       tree parmref = build_fold_indirect_ref_loc(no->location(), parm_decl);
1452       TREE_THIS_NOTRAP(parmref) = 1;
1453       tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node,
1454                                  spaceref, parmref);
1455       init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space),
1456                              build3(COND_EXPR, void_type_node,
1457                                     check, set, NULL_TREE),
1458                              space);
1459     }
1460
1461   DECL_INITIAL(var_decl) = init;
1462
1463   return parm_decl;
1464 }
1465
1466 // If we take the address of a parameter, then we need to copy it into
1467 // the heap.  We will access it as a local variable via an
1468 // indirection.
1469
1470 tree
1471 Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree ref)
1472 {
1473   if (ref == error_mark_node)
1474     return error_mark_node;
1475
1476   gcc_assert(TREE_CODE(ref) == INDIRECT_REF);
1477
1478   tree var_decl = TREE_OPERAND(ref, 0);
1479   if (var_decl == error_mark_node)
1480     return error_mark_node;
1481   gcc_assert(TREE_CODE(var_decl) == VAR_DECL);
1482   source_location loc = DECL_SOURCE_LOCATION(var_decl);
1483
1484   std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1485   name += ".param";
1486   tree id = get_identifier_from_string(name);
1487
1488   tree type = TREE_TYPE(var_decl);
1489   gcc_assert(POINTER_TYPE_P(type));
1490   type = TREE_TYPE(type);
1491
1492   tree parm_decl = build_decl(loc, PARM_DECL, id, type);
1493   DECL_CONTEXT(parm_decl) = current_function_decl;
1494   DECL_ARG_TYPE(parm_decl) = type;
1495
1496   tree size = TYPE_SIZE_UNIT(type);
1497   tree space = gogo->allocate_memory(no->var_value()->type(), size, loc);
1498   space = save_expr(space);
1499   space = fold_convert(TREE_TYPE(var_decl), space);
1500   tree spaceref = build_fold_indirect_ref_loc(loc, space);
1501   TREE_THIS_NOTRAP(spaceref) = 1;
1502   tree init = build2(COMPOUND_EXPR, TREE_TYPE(space),
1503                      build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl),
1504                      space);
1505   DECL_INITIAL(var_decl) = init;
1506
1507   return parm_decl;
1508 }
1509
1510 // Get a tree for function code.
1511
1512 void
1513 Function::build_tree(Gogo* gogo, Named_object* named_function)
1514 {
1515   tree fndecl = this->fndecl_;
1516   gcc_assert(fndecl != NULL_TREE);
1517
1518   tree params = NULL_TREE;
1519   tree* pp = &params;
1520
1521   tree declare_vars = NULL_TREE;
1522   for (Bindings::const_definitions_iterator p =
1523          this->block_->bindings()->begin_definitions();
1524        p != this->block_->bindings()->end_definitions();
1525        ++p)
1526     {
1527       if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
1528         {
1529           *pp = (*p)->get_tree(gogo, named_function);
1530
1531           // We always pass the receiver to a method as a pointer.  If
1532           // the receiver is declared as a non-pointer type, then we
1533           // copy the value into a local variable.
1534           if ((*p)->var_value()->is_receiver()
1535               && (*p)->var_value()->type()->points_to() == NULL)
1536             {
1537               tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp);
1538               tree var = *pp;
1539               if (TREE_CODE(var) == INDIRECT_REF)
1540                 var = TREE_OPERAND(var, 0);
1541               if (var != error_mark_node)
1542                 {
1543                   gcc_assert(TREE_CODE(var) == VAR_DECL);
1544                   DECL_CHAIN(var) = declare_vars;
1545                   declare_vars = var;
1546                 }
1547               *pp = parm_decl;
1548             }
1549           else if ((*p)->var_value()->is_in_heap())
1550             {
1551               // If we take the address of a parameter, then we need
1552               // to copy it into the heap.
1553               tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp);
1554               if (*pp != error_mark_node)
1555                 {
1556                   gcc_assert(TREE_CODE(*pp) == INDIRECT_REF);
1557                   tree var_decl = TREE_OPERAND(*pp, 0);
1558                   if (var_decl != error_mark_node)
1559                     {
1560                       gcc_assert(TREE_CODE(var_decl) == VAR_DECL);
1561                       DECL_CHAIN(var_decl) = declare_vars;
1562                       declare_vars = var_decl;
1563                     }
1564                 }
1565               *pp = parm_decl;
1566             }
1567
1568           if (*pp != error_mark_node)
1569             {
1570               gcc_assert(TREE_CODE(*pp) == PARM_DECL);
1571               pp = &DECL_CHAIN(*pp);
1572             }
1573         }
1574       else if ((*p)->is_result_variable())
1575         {
1576           tree var_decl = (*p)->get_tree(gogo, named_function);
1577           if (var_decl != error_mark_node
1578               && (*p)->result_var_value()->is_in_heap())
1579             {
1580               gcc_assert(TREE_CODE(var_decl) == INDIRECT_REF);
1581               var_decl = TREE_OPERAND(var_decl, 0);
1582             }
1583           if (var_decl != error_mark_node)
1584             {
1585               gcc_assert(TREE_CODE(var_decl) == VAR_DECL);
1586               DECL_CHAIN(var_decl) = declare_vars;
1587               declare_vars = var_decl;
1588             }
1589         }
1590     }
1591   *pp = NULL_TREE;
1592
1593   DECL_ARGUMENTS(fndecl) = params;
1594
1595   if (this->block_ != NULL)
1596     {
1597       gcc_assert(DECL_INITIAL(fndecl) == NULL_TREE);
1598
1599       // Declare variables if necessary.
1600       tree bind = NULL_TREE;
1601       if (declare_vars != NULL_TREE)
1602         {
1603           tree block = make_node(BLOCK);
1604           BLOCK_SUPERCONTEXT(block) = fndecl;
1605           DECL_INITIAL(fndecl) = block;
1606           BLOCK_VARS(block) = declare_vars;
1607           TREE_USED(block) = 1;
1608           bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block),
1609                         NULL_TREE, block);
1610           TREE_SIDE_EFFECTS(bind) = 1;
1611         }
1612
1613       // Build the trees for all the statements in the function.
1614       Translate_context context(gogo, named_function, NULL, NULL_TREE);
1615       tree code = this->block_->get_tree(&context);
1616
1617       tree init = NULL_TREE;
1618       tree except = NULL_TREE;
1619       tree fini = NULL_TREE;
1620
1621       // Initialize variables if necessary.
1622       for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v))
1623         {
1624           tree dv = build1(DECL_EXPR, void_type_node, v);
1625           SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v));
1626           append_to_statement_list(dv, &init);
1627         }
1628
1629       // If we have a defer stack, initialize it at the start of a
1630       // function.
1631       if (this->defer_stack_ != NULL_TREE)
1632         {
1633           tree defer_init = build1(DECL_EXPR, void_type_node,
1634                                    this->defer_stack_);
1635           SET_EXPR_LOCATION(defer_init, this->block_->start_location());
1636           append_to_statement_list(defer_init, &init);
1637
1638           // Clean up the defer stack when we leave the function.
1639           this->build_defer_wrapper(gogo, named_function, &except, &fini);
1640         }
1641
1642       if (code != NULL_TREE && code != error_mark_node)
1643         {
1644           if (init != NULL_TREE)
1645             code = build2(COMPOUND_EXPR, void_type_node, init, code);
1646           if (except != NULL_TREE)
1647             code = build2(TRY_CATCH_EXPR, void_type_node, code,
1648                           build2(CATCH_EXPR, void_type_node, NULL, except));
1649           if (fini != NULL_TREE)
1650             code = build2(TRY_FINALLY_EXPR, void_type_node, code, fini);
1651         }
1652
1653       // Stick the code into the block we built for the receiver, if
1654       // we built on.
1655       if (bind != NULL_TREE && code != NULL_TREE && code != error_mark_node)
1656         {
1657           BIND_EXPR_BODY(bind) = code;
1658           code = bind;
1659         }
1660
1661       DECL_SAVED_TREE(fndecl) = code;
1662     }
1663 }
1664
1665 // Build the wrappers around function code needed if the function has
1666 // any defer statements.  This sets *EXCEPT to an exception handler
1667 // and *FINI to a finally handler.
1668
1669 void
1670 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
1671                               tree *except, tree *fini)
1672 {
1673   source_location end_loc = this->block_->end_location();
1674
1675   // Add an exception handler.  This is used if a panic occurs.  Its
1676   // purpose is to stop the stack unwinding if a deferred function
1677   // calls recover.  There are more details in
1678   // libgo/runtime/go-unwind.c.
1679   tree stmt_list = NULL_TREE;
1680   static tree check_fndecl;
1681   tree call = Gogo::call_builtin(&check_fndecl,
1682                                  end_loc,
1683                                  "__go_check_defer",
1684                                  1,
1685                                  void_type_node,
1686                                  ptr_type_node,
1687                                  this->defer_stack(end_loc));
1688   if (call != error_mark_node)
1689     append_to_statement_list(call, &stmt_list);
1690
1691   tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list);
1692   tree set;
1693   if (retval == NULL_TREE)
1694     set = NULL_TREE;
1695   else
1696     set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node,
1697                           DECL_RESULT(this->fndecl_), retval);
1698   tree ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set);
1699   append_to_statement_list(ret_stmt, &stmt_list);
1700
1701   gcc_assert(*except == NULL_TREE);
1702   *except = stmt_list;
1703
1704   // Add some finally code to run the defer functions.  This is used
1705   // both in the normal case, when no panic occurs, and also if a
1706   // panic occurs to run any further defer functions.  Of course, it
1707   // is possible for a defer function to call panic which should be
1708   // caught by another defer function.  To handle that we use a loop.
1709   //  finish:
1710   //   try { __go_undefer(); } catch { __go_check_defer(); goto finish; }
1711   //   if (return values are named) return named_vals;
1712
1713   stmt_list = NULL;
1714
1715   tree label = create_artificial_label(end_loc);
1716   tree define_label = fold_build1_loc(end_loc, LABEL_EXPR, void_type_node,
1717                                       label);
1718   append_to_statement_list(define_label, &stmt_list);
1719
1720   static tree undefer_fndecl;
1721   tree undefer = Gogo::call_builtin(&undefer_fndecl,
1722                                     end_loc,
1723                                     "__go_undefer",
1724                                     1,
1725                                     void_type_node,
1726                                     ptr_type_node,
1727                                     this->defer_stack(end_loc));
1728   if (undefer_fndecl != NULL_TREE)
1729     TREE_NOTHROW(undefer_fndecl) = 0;
1730
1731   tree defer = Gogo::call_builtin(&check_fndecl,
1732                                   end_loc,
1733                                   "__go_check_defer",
1734                                   1,
1735                                   void_type_node,
1736                                   ptr_type_node,
1737                                   this->defer_stack(end_loc));
1738   tree jump = fold_build1_loc(end_loc, GOTO_EXPR, void_type_node, label);
1739   tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump);
1740   catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body);
1741   tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body);
1742
1743   append_to_statement_list(try_catch, &stmt_list);
1744
1745   if (this->type_->results() != NULL
1746       && !this->type_->results()->empty()
1747       && !this->type_->results()->front().name().empty())
1748     {
1749       // If the result variables are named, we need to return them
1750       // again, because they might have been changed by a defer
1751       // function.
1752       retval = this->return_value(gogo, named_function, end_loc,
1753                                   &stmt_list);
1754       set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node,
1755                             DECL_RESULT(this->fndecl_), retval);
1756       ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set);
1757       append_to_statement_list(ret_stmt, &stmt_list);
1758     }
1759   
1760   gcc_assert(*fini == NULL_TREE);
1761   *fini = stmt_list;
1762 }
1763
1764 // Return the value to assign to DECL_RESULT(this->fndecl_).  This may
1765 // also add statements to STMT_LIST, which need to be executed before
1766 // the assignment.  This is used for a return statement with no
1767 // explicit values.
1768
1769 tree
1770 Function::return_value(Gogo* gogo, Named_object* named_function,
1771                        source_location location, tree* stmt_list) const
1772 {
1773   const Typed_identifier_list* results = this->type_->results();
1774   if (results == NULL || results->empty())
1775     return NULL_TREE;
1776
1777   // In the case of an exception handler created for functions with
1778   // defer statements, the result variables may be unnamed.
1779   bool is_named = !results->front().name().empty();
1780   if (is_named)
1781     gcc_assert(this->named_results_ != NULL
1782                && this->named_results_->size() == results->size());
1783
1784   tree retval;
1785   if (results->size() == 1)
1786     {
1787       if (is_named)
1788         return this->named_results_->front()->get_tree(gogo, named_function);
1789       else
1790         return results->front().type()->get_init_tree(gogo, false);
1791     }
1792   else
1793     {
1794       tree rettype = TREE_TYPE(DECL_RESULT(this->fndecl_));
1795       retval = create_tmp_var(rettype, "RESULT");
1796       tree field = TYPE_FIELDS(rettype);
1797       int index = 0;
1798       for (Typed_identifier_list::const_iterator pr = results->begin();
1799            pr != results->end();
1800            ++pr, ++index, field = DECL_CHAIN(field))
1801         {
1802           gcc_assert(field != NULL);
1803           tree val;
1804           if (is_named)
1805             val = (*this->named_results_)[index]->get_tree(gogo,
1806                                                            named_function);
1807           else
1808             val = pr->type()->get_init_tree(gogo, false);
1809           tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node,
1810                                      build3(COMPONENT_REF, TREE_TYPE(field),
1811                                             retval, field, NULL_TREE),
1812                                      val);
1813           append_to_statement_list(set, stmt_list);
1814         }
1815       return retval;
1816     }
1817 }
1818
1819 // Get the tree for the variable holding the defer stack for this
1820 // function.  At least at present, the value of this variable is not
1821 // used.  However, a pointer to this variable is used as a marker for
1822 // the functions on the defer stack associated with this function.
1823 // Doing things this way permits inlining a function which uses defer.
1824
1825 tree
1826 Function::defer_stack(source_location location)
1827 {
1828   if (this->defer_stack_ == NULL_TREE)
1829     {
1830       tree var = create_tmp_var(ptr_type_node, "DEFER");
1831       DECL_INITIAL(var) = null_pointer_node;
1832       DECL_SOURCE_LOCATION(var) = location;
1833       TREE_ADDRESSABLE(var) = 1;
1834       this->defer_stack_ = var;
1835     }
1836   return fold_convert_loc(location, ptr_type_node,
1837                           build_fold_addr_expr_loc(location,
1838                                                    this->defer_stack_));
1839 }
1840
1841 // Get a tree for the statements in a block.
1842
1843 tree
1844 Block::get_tree(Translate_context* context)
1845 {
1846   Gogo* gogo = context->gogo();
1847
1848   tree block = make_node(BLOCK);
1849
1850   // Put the new block into the block tree.
1851
1852   if (context->block() == NULL)
1853     {
1854       tree fndecl;
1855       if (context->function() != NULL)
1856         fndecl = context->function()->func_value()->get_decl();
1857       else
1858         fndecl = current_function_decl;
1859       gcc_assert(fndecl != NULL_TREE);
1860
1861       // We may have already created a block for the receiver.
1862       if (DECL_INITIAL(fndecl) == NULL_TREE)
1863         {
1864           BLOCK_SUPERCONTEXT(block) = fndecl;
1865           DECL_INITIAL(fndecl) = block;
1866         }
1867       else
1868         {
1869           tree superblock_tree = DECL_INITIAL(fndecl);
1870           BLOCK_SUPERCONTEXT(block) = superblock_tree;
1871           gcc_assert(BLOCK_CHAIN(block) == NULL_TREE);
1872           BLOCK_CHAIN(block) = block;
1873         }
1874     }
1875   else
1876     {
1877       tree superblock_tree = context->block_tree();
1878       BLOCK_SUPERCONTEXT(block) = superblock_tree;
1879       tree* pp;
1880       for (pp = &BLOCK_SUBBLOCKS(superblock_tree);
1881            *pp != NULL_TREE;
1882            pp = &BLOCK_CHAIN(*pp))
1883         ;
1884       *pp = block;
1885     }
1886
1887   // Expand local variables in the block.
1888
1889   tree* pp = &BLOCK_VARS(block);
1890   for (Bindings::const_definitions_iterator pv =
1891          this->bindings_->begin_definitions();
1892        pv != this->bindings_->end_definitions();
1893        ++pv)
1894     {
1895       if ((!(*pv)->is_variable() || !(*pv)->var_value()->is_parameter())
1896           && !(*pv)->is_result_variable()
1897           && !(*pv)->is_const())
1898         {
1899           tree var = (*pv)->get_tree(gogo, context->function());
1900           if (var != error_mark_node && TREE_TYPE(var) != error_mark_node)
1901             {
1902               if ((*pv)->is_variable() && (*pv)->var_value()->is_in_heap())
1903                 {
1904                   gcc_assert(TREE_CODE(var) == INDIRECT_REF);
1905                   var = TREE_OPERAND(var, 0);
1906                   gcc_assert(TREE_CODE(var) == VAR_DECL);
1907                 }
1908               *pp = var;
1909               pp = &DECL_CHAIN(*pp);
1910             }
1911         }
1912     }
1913   *pp = NULL_TREE;
1914
1915   Translate_context subcontext(context->gogo(), context->function(),
1916                                this, block);
1917
1918   tree statements = NULL_TREE;
1919
1920   // Expand the statements.
1921
1922   for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
1923        p != this->statements_.end();
1924        ++p)
1925     {
1926       tree statement = (*p)->get_tree(&subcontext);
1927       if (statement != error_mark_node)
1928         append_to_statement_list(statement, &statements);
1929     }
1930
1931   TREE_USED(block) = 1;
1932
1933   tree bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block), statements,
1934                      block);
1935   TREE_SIDE_EFFECTS(bind) = 1;
1936
1937   return bind;
1938 }
1939
1940 // Get the LABEL_DECL for a label.
1941
1942 tree
1943 Label::get_decl()
1944 {
1945   if (this->decl_ == NULL)
1946     {
1947       tree id = get_identifier_from_string(this->name_);
1948       this->decl_ = build_decl(this->location_, LABEL_DECL, id, void_type_node);
1949       DECL_CONTEXT(this->decl_) = current_function_decl;
1950     }
1951   return this->decl_;
1952 }
1953
1954 // Return an expression for the address of this label.
1955
1956 tree
1957 Label::get_addr(source_location location)
1958 {
1959   tree decl = this->get_decl();
1960   TREE_USED(decl) = 1;
1961   TREE_ADDRESSABLE(decl) = 1;
1962   return fold_convert_loc(location, ptr_type_node,
1963                           build_fold_addr_expr_loc(location, decl));
1964 }
1965
1966 // Get the LABEL_DECL for an unnamed label.
1967
1968 tree
1969 Unnamed_label::get_decl()
1970 {
1971   if (this->decl_ == NULL)
1972     this->decl_ = create_artificial_label(this->location_);
1973   return this->decl_;
1974 }
1975
1976 // Get the LABEL_EXPR for an unnamed label.
1977
1978 tree
1979 Unnamed_label::get_definition()
1980 {
1981   tree t = build1(LABEL_EXPR, void_type_node, this->get_decl());
1982   SET_EXPR_LOCATION(t, this->location_);
1983   return t;
1984 }
1985
1986 // Return a goto to this label.
1987
1988 tree
1989 Unnamed_label::get_goto(source_location location)
1990 {
1991   tree t = build1(GOTO_EXPR, void_type_node, this->get_decl());
1992   SET_EXPR_LOCATION(t, location);
1993   return t;
1994 }
1995
1996 // Return the integer type to use for a size.
1997
1998 GO_EXTERN_C
1999 tree
2000 go_type_for_size(unsigned int bits, int unsignedp)
2001 {
2002   const char* name;
2003   switch (bits)
2004     {
2005     case 8:
2006       name = unsignedp ? "uint8" : "int8";
2007       break;
2008     case 16:
2009       name = unsignedp ? "uint16" : "int16";
2010       break;
2011     case 32:
2012       name = unsignedp ? "uint32" : "int32";
2013       break;
2014     case 64:
2015       name = unsignedp ? "uint64" : "int64";
2016       break;
2017     default:
2018       if (bits == POINTER_SIZE && unsignedp)
2019         name = "uintptr";
2020       else
2021         return NULL_TREE;
2022     }
2023   Type* type = Type::lookup_integer_type(name);
2024   return type->get_tree(go_get_gogo());
2025 }
2026
2027 // Return the type to use for a mode.
2028
2029 GO_EXTERN_C
2030 tree
2031 go_type_for_mode(enum machine_mode mode, int unsignedp)
2032 {
2033   // FIXME: This static_cast should be in machmode.h.
2034   enum mode_class mc = static_cast<enum mode_class>(GET_MODE_CLASS(mode));
2035   if (mc == MODE_INT)
2036     return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp);
2037   else if (mc == MODE_FLOAT)
2038     {
2039       Type* type;
2040       switch (GET_MODE_BITSIZE (mode))
2041         {
2042         case 32:
2043           type = Type::lookup_float_type("float32");
2044           break;
2045         case 64:
2046           type = Type::lookup_float_type("float64");
2047           break;
2048         default:
2049           // We have to check for long double in order to support
2050           // i386 excess precision.
2051           if (mode == TYPE_MODE(long_double_type_node))
2052             return long_double_type_node;
2053           return NULL_TREE;
2054         }
2055       return type->float_type()->type_tree();
2056     }
2057   else if (mc == MODE_COMPLEX_FLOAT)
2058     {
2059       Type *type;
2060       switch (GET_MODE_BITSIZE (mode))
2061         {
2062         case 64:
2063           type = Type::lookup_complex_type("complex64");
2064           break;
2065         case 128:
2066           type = Type::lookup_complex_type("complex128");
2067           break;
2068         default:
2069           // We have to check for long double in order to support
2070           // i386 excess precision.
2071           if (mode == TYPE_MODE(complex_long_double_type_node))
2072             return complex_long_double_type_node;
2073           return NULL_TREE;
2074         }
2075       return type->complex_type()->type_tree();
2076     }
2077   else
2078     return NULL_TREE;
2079 }
2080
2081 // Return a tree which allocates SIZE bytes which will holds value of
2082 // type TYPE.
2083
2084 tree
2085 Gogo::allocate_memory(Type* type, tree size, source_location location)
2086 {
2087   // If the package imports unsafe, then it may play games with
2088   // pointers that look like integers.
2089   if (this->imported_unsafe_ || type->has_pointer())
2090     {
2091       static tree new_fndecl;
2092       return Gogo::call_builtin(&new_fndecl,
2093                                 location,
2094                                 "__go_new",
2095                                 1,
2096                                 ptr_type_node,
2097                                 sizetype,
2098                                 size);
2099     }
2100   else
2101     {
2102       static tree new_nopointers_fndecl;
2103       return Gogo::call_builtin(&new_nopointers_fndecl,
2104                                 location,
2105                                 "__go_new_nopointers",
2106                                 1,
2107                                 ptr_type_node,
2108                                 sizetype,
2109                                 size);
2110     }
2111 }
2112
2113 // Build a builtin struct with a list of fields.  The name is
2114 // STRUCT_NAME.  STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE
2115 // node; this exists so that the struct can have fields which point to
2116 // itself.  If PTYPE is not NULL, store the result in *PTYPE.  There
2117 // are NFIELDS fields.  Each field is a name (a const char*) followed
2118 // by a type (a tree).
2119
2120 tree
2121 Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type,
2122                      int nfields, ...)
2123 {
2124   if (ptype != NULL && *ptype != NULL_TREE)
2125     return *ptype;
2126
2127   va_list ap;
2128   va_start(ap, nfields);
2129
2130   tree fields = NULL_TREE;
2131   for (int i = 0; i < nfields; ++i)
2132     {
2133       const char* field_name = va_arg(ap, const char*);
2134       tree type = va_arg(ap, tree);
2135       if (type == error_mark_node)
2136         {
2137           if (ptype != NULL)
2138             *ptype = error_mark_node;
2139           return error_mark_node;
2140         }
2141       tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL,
2142                               get_identifier(field_name), type);
2143       DECL_CHAIN(field) = fields;
2144       fields = field;
2145     }
2146
2147   va_end(ap);
2148
2149   if (struct_type == NULL_TREE)
2150     struct_type = make_node(RECORD_TYPE);
2151   finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE);
2152
2153   if (ptype != NULL)
2154     {
2155       go_preserve_from_gc(struct_type);
2156       *ptype = struct_type;
2157     }
2158
2159   return struct_type;
2160 }
2161
2162 // Return a type to use for pointer to const char for a string.
2163
2164 tree
2165 Gogo::const_char_pointer_type_tree()
2166 {
2167   static tree type;
2168   if (type == NULL_TREE)
2169     {
2170       tree const_char_type = build_qualified_type(unsigned_char_type_node,
2171                                                   TYPE_QUAL_CONST);
2172       type = build_pointer_type(const_char_type);
2173       go_preserve_from_gc(type);
2174     }
2175   return type;
2176 }
2177
2178 // Return a tree for a string constant.
2179
2180 tree
2181 Gogo::string_constant_tree(const std::string& val)
2182 {
2183   tree index_type = build_index_type(size_int(val.length()));
2184   tree const_char_type = build_qualified_type(unsigned_char_type_node,
2185                                               TYPE_QUAL_CONST);
2186   tree string_type = build_array_type(const_char_type, index_type);
2187   string_type = build_variant_type_copy(string_type);
2188   TYPE_STRING_FLAG(string_type) = 1;
2189   tree string_val = build_string(val.length(), val.data());
2190   TREE_TYPE(string_val) = string_type;
2191   return string_val;
2192 }
2193
2194 // Return a tree for a Go string constant.
2195
2196 tree
2197 Gogo::go_string_constant_tree(const std::string& val)
2198 {
2199   tree string_type = Type::make_string_type()->get_tree(this);
2200
2201   VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2);
2202
2203   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
2204   tree field = TYPE_FIELDS(string_type);
2205   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0);
2206   elt->index = field;
2207   tree str = Gogo::string_constant_tree(val);
2208   elt->value = fold_convert(TREE_TYPE(field),
2209                             build_fold_addr_expr(str));
2210
2211   elt = VEC_quick_push(constructor_elt, init, NULL);
2212   field = DECL_CHAIN(field);
2213   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0);
2214   elt->index = field;
2215   elt->value = build_int_cst_type(TREE_TYPE(field), val.length());
2216
2217   tree constructor = build_constructor(string_type, init);
2218   TREE_READONLY(constructor) = 1;
2219   TREE_CONSTANT(constructor) = 1;
2220
2221   return constructor;
2222 }
2223
2224 // Return a tree for a pointer to a Go string constant.  This is only
2225 // used for type descriptors, so we return a pointer to a constant
2226 // decl.
2227
2228 tree
2229 Gogo::ptr_go_string_constant_tree(const std::string& val)
2230 {
2231   tree pval = this->go_string_constant_tree(val);
2232
2233   tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL,
2234                          create_tmp_var_name("SP"), TREE_TYPE(pval));
2235   DECL_EXTERNAL(decl) = 0;
2236   TREE_PUBLIC(decl) = 0;
2237   TREE_USED(decl) = 1;
2238   TREE_READONLY(decl) = 1;
2239   TREE_CONSTANT(decl) = 1;
2240   TREE_STATIC(decl) = 1;
2241   DECL_ARTIFICIAL(decl) = 1;
2242   DECL_INITIAL(decl) = pval;
2243   rest_of_decl_compilation(decl, 1, 0);
2244
2245   return build_fold_addr_expr(decl);
2246 }
2247
2248 // Build the type of the struct that holds a slice for the given
2249 // element type.
2250
2251 tree
2252 Gogo::slice_type_tree(tree element_type_tree)
2253 {
2254   // We use int for the count and capacity fields in a slice header.
2255   // This matches 6g.  The language definition guarantees that we
2256   // can't allocate space of a size which does not fit in int
2257   // anyhow. FIXME: integer_type_node is the the C type "int" but is
2258   // not necessarily the Go type "int".  They will differ when the C
2259   // type "int" has fewer than 32 bits.
2260   return Gogo::builtin_struct(NULL, "__go_slice", NULL_TREE, 3,
2261                               "__values",
2262                               build_pointer_type(element_type_tree),
2263                               "__count",
2264                               integer_type_node,
2265                               "__capacity",
2266                               integer_type_node);
2267 }
2268
2269 // Given the tree for a slice type, return the tree for the type of
2270 // the elements of the slice.
2271
2272 tree
2273 Gogo::slice_element_type_tree(tree slice_type_tree)
2274 {
2275   gcc_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE
2276              && POINTER_TYPE_P(TREE_TYPE(TYPE_FIELDS(slice_type_tree))));
2277   return TREE_TYPE(TREE_TYPE(TYPE_FIELDS(slice_type_tree)));
2278 }
2279
2280 // Build a constructor for a slice.  SLICE_TYPE_TREE is the type of
2281 // the slice.  VALUES is the value pointer and COUNT is the number of
2282 // entries.  If CAPACITY is not NULL, it is the capacity; otherwise
2283 // the capacity and the count are the same.
2284
2285 tree
2286 Gogo::slice_constructor(tree slice_type_tree, tree values, tree count,
2287                         tree capacity)
2288 {
2289   gcc_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE);
2290
2291   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
2292
2293   tree field = TYPE_FIELDS(slice_type_tree);
2294   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
2295   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
2296   elt->index = field;
2297   gcc_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field))
2298              == TYPE_MAIN_VARIANT(TREE_TYPE(values)));
2299   elt->value = values;
2300
2301   count = fold_convert(sizetype, count);
2302   if (capacity == NULL_TREE)
2303     {
2304       count = save_expr(count);
2305       capacity = count;
2306     }
2307
2308   field = DECL_CHAIN(field);
2309   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
2310   elt = VEC_quick_push(constructor_elt, init, NULL);
2311   elt->index = field;
2312   elt->value = fold_convert(TREE_TYPE(field), count);
2313
2314   field = DECL_CHAIN(field);
2315   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
2316   elt = VEC_quick_push(constructor_elt, init, NULL);
2317   elt->index = field;
2318   elt->value = fold_convert(TREE_TYPE(field), capacity);
2319
2320   return build_constructor(slice_type_tree, init);
2321 }
2322
2323 // Build a constructor for an empty slice.
2324
2325 tree
2326 Gogo::empty_slice_constructor(tree slice_type_tree)
2327 {
2328   tree element_field = TYPE_FIELDS(slice_type_tree);
2329   tree ret = Gogo::slice_constructor(slice_type_tree,
2330                                      fold_convert(TREE_TYPE(element_field),
2331                                                   null_pointer_node),
2332                                      size_zero_node,
2333                                      size_zero_node);
2334   TREE_CONSTANT(ret) = 1;
2335   return ret;
2336 }
2337
2338 // Build a map descriptor for a map of type MAPTYPE.
2339
2340 tree
2341 Gogo::map_descriptor(Map_type* maptype)
2342 {
2343   if (this->map_descriptors_ == NULL)
2344     this->map_descriptors_ = new Map_descriptors(10);
2345
2346   std::pair<const Map_type*, tree> val(maptype, NULL);
2347   std::pair<Map_descriptors::iterator, bool> ins =
2348     this->map_descriptors_->insert(val);
2349   Map_descriptors::iterator p = ins.first;
2350   if (!ins.second)
2351     {
2352       gcc_assert(p->second != NULL_TREE && DECL_P(p->second));
2353       return build_fold_addr_expr(p->second);
2354     }
2355
2356   Type* keytype = maptype->key_type();
2357   Type* valtype = maptype->val_type();
2358
2359   std::string mangled_name = ("__go_map_" + maptype->mangled_name(this));
2360
2361   tree id = get_identifier_from_string(mangled_name);
2362
2363   // Get the type of the map descriptor.  This is __go_map_descriptor
2364   // in libgo/map.h.
2365
2366   tree struct_type = this->map_descriptor_type();
2367
2368   // The map entry type is a struct with three fields.  This struct is
2369   // specific to MAPTYPE.  Build it.
2370
2371   tree map_entry_type = make_node(RECORD_TYPE);
2372
2373   map_entry_type = Gogo::builtin_struct(NULL, "__map", map_entry_type, 3,
2374                                         "__next",
2375                                         build_pointer_type(map_entry_type),
2376                                         "__key",
2377                                         keytype->get_tree(this),
2378                                         "__val",
2379                                         valtype->get_tree(this));
2380   if (map_entry_type == error_mark_node)
2381     return error_mark_node;
2382
2383   tree map_entry_key_field = DECL_CHAIN(TYPE_FIELDS(map_entry_type));
2384   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_key_field)),
2385                     "__key") == 0);
2386
2387   tree map_entry_val_field = DECL_CHAIN(map_entry_key_field);
2388   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_val_field)),
2389                     "__val") == 0);
2390
2391   // Initialize the entries.
2392
2393   tree map_descriptor_field = TYPE_FIELDS(struct_type);
2394   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_descriptor_field)),
2395                     "__map_descriptor") == 0);
2396   tree entry_size_field = DECL_CHAIN(map_descriptor_field);
2397   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(entry_size_field)),
2398                     "__entry_size") == 0);
2399   tree key_offset_field = DECL_CHAIN(entry_size_field);
2400   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(key_offset_field)),
2401                     "__key_offset") == 0);
2402   tree val_offset_field = DECL_CHAIN(key_offset_field);
2403   gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(val_offset_field)),
2404                     "__val_offset") == 0);
2405
2406   VEC(constructor_elt, gc)* descriptor = VEC_alloc(constructor_elt, gc, 6);
2407
2408   constructor_elt* elt = VEC_quick_push(constructor_elt, descriptor, NULL);
2409   elt->index = map_descriptor_field;
2410   elt->value = maptype->type_descriptor_pointer(this);
2411
2412   elt = VEC_quick_push(constructor_elt, descriptor, NULL);
2413   elt->index = entry_size_field;
2414   elt->value = TYPE_SIZE_UNIT(map_entry_type);
2415
2416   elt = VEC_quick_push(constructor_elt, descriptor, NULL);
2417   elt->index = key_offset_field;
2418   elt->value = byte_position(map_entry_key_field);
2419
2420   elt = VEC_quick_push(constructor_elt, descriptor, NULL);
2421   elt->index = val_offset_field;
2422   elt->value = byte_position(map_entry_val_field);
2423
2424   tree constructor = build_constructor(struct_type, descriptor);
2425
2426   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, struct_type);
2427   TREE_STATIC(decl) = 1;
2428   TREE_USED(decl) = 1;
2429   TREE_READONLY(decl) = 1;
2430   TREE_CONSTANT(decl) = 1;
2431   DECL_INITIAL(decl) = constructor;
2432   make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2433   resolve_unique_section(decl, 1, 0);
2434
2435   rest_of_decl_compilation(decl, 1, 0);
2436
2437   go_preserve_from_gc(decl);
2438   p->second = decl;
2439
2440   return build_fold_addr_expr(decl);
2441 }
2442
2443 // Return a tree for the type of a map descriptor.  This is struct
2444 // __go_map_descriptor in libgo/runtime/map.h.  This is the same for
2445 // all map types.
2446
2447 tree
2448 Gogo::map_descriptor_type()
2449 {
2450   static tree struct_type;
2451   tree dtype = Type::make_type_descriptor_type()->get_tree(this);
2452   dtype = build_qualified_type(dtype, TYPE_QUAL_CONST);
2453   return Gogo::builtin_struct(&struct_type, "__go_map_descriptor", NULL_TREE,
2454                               4,
2455                               "__map_descriptor",
2456                               build_pointer_type(dtype),
2457                               "__entry_size",
2458                               sizetype,
2459                               "__key_offset",
2460                               sizetype,
2461                               "__val_offset",
2462                               sizetype);
2463 }
2464
2465 // Return the name to use for a type descriptor decl for TYPE.  This
2466 // is used when TYPE does not have a name.
2467
2468 std::string
2469 Gogo::unnamed_type_descriptor_decl_name(const Type* type)
2470 {
2471   return "__go_td_" + type->mangled_name(this);
2472 }
2473
2474 // Return the name to use for a type descriptor decl for a type named
2475 // NAME, defined in the function IN_FUNCTION.  IN_FUNCTION will
2476 // normally be NULL.
2477
2478 std::string
2479 Gogo::type_descriptor_decl_name(const Named_object* no,
2480                                 const Named_object* in_function)
2481 {
2482   std::string ret = "__go_tdn_";
2483   if (no->type_value()->is_builtin())
2484     gcc_assert(in_function == NULL);
2485   else
2486     {
2487       const std::string& unique_prefix(no->package() == NULL
2488                                        ? this->unique_prefix()
2489                                        : no->package()->unique_prefix());
2490       const std::string& package_name(no->package() == NULL
2491                                       ? this->package_name()
2492                                       : no->package()->name());
2493       ret.append(unique_prefix);
2494       ret.append(1, '.');
2495       ret.append(package_name);
2496       ret.append(1, '.');
2497       if (in_function != NULL)
2498         {
2499           ret.append(Gogo::unpack_hidden_name(in_function->name()));
2500           ret.append(1, '.');
2501         }
2502     }
2503   ret.append(no->name());
2504   return ret;
2505 }
2506
2507 // Where a type descriptor decl should be defined.
2508
2509 Gogo::Type_descriptor_location
2510 Gogo::type_descriptor_location(const Type* type)
2511 {
2512   const Named_type* name = type->named_type();
2513   if (name != NULL)
2514     {
2515       if (name->named_object()->package() != NULL)
2516         {
2517           // This is a named type defined in a different package.  The
2518           // descriptor should be defined in that package.
2519           return TYPE_DESCRIPTOR_UNDEFINED;
2520         }
2521       else if (name->is_builtin())
2522         {
2523           // We create the descriptor for a builtin type whenever we
2524           // need it.
2525           return TYPE_DESCRIPTOR_COMMON;
2526         }
2527       else
2528         {
2529           // This is a named type defined in this package.  The
2530           // descriptor should be defined here.
2531           return TYPE_DESCRIPTOR_DEFINED;
2532         }
2533     }
2534   else
2535     {
2536       if (type->points_to() != NULL
2537           && type->points_to()->named_type() != NULL
2538           && type->points_to()->named_type()->named_object()->package() != NULL)
2539         {
2540           // This is an unnamed pointer to a named type defined in a
2541           // different package.  The descriptor should be defined in
2542           // that package.
2543           return TYPE_DESCRIPTOR_UNDEFINED;
2544         }
2545       else
2546         {
2547           // This is an unnamed type.  The descriptor could be defined
2548           // in any package where it is needed, and the linker will
2549           // pick one descriptor to keep.
2550           return TYPE_DESCRIPTOR_COMMON;
2551         }
2552     }
2553 }
2554
2555 // Build a type descriptor decl for TYPE.  INITIALIZER is a struct
2556 // composite literal which initializers the type descriptor.
2557
2558 void
2559 Gogo::build_type_descriptor_decl(const Type* type, Expression* initializer,
2560                                  tree* pdecl)
2561 {
2562   const Named_type* name = type->named_type();
2563
2564   // We can have multiple instances of unnamed types, but we only want
2565   // to emit the type descriptor once.  We use a hash table to handle
2566   // this.  This is not necessary for named types, as they are unique,
2567   // and we store the type descriptor decl in the type itself.
2568   tree* phash = NULL;
2569   if (name == NULL)
2570     {
2571       if (this->type_descriptor_decls_ == NULL)
2572         this->type_descriptor_decls_ = new Type_descriptor_decls(10);
2573
2574       std::pair<Type_descriptor_decls::iterator, bool> ins =
2575         this->type_descriptor_decls_->insert(std::make_pair(type, NULL_TREE));
2576       if (!ins.second)
2577         {
2578           // We've already built a type descriptor for this type.
2579           *pdecl = ins.first->second;
2580           return;
2581         }
2582       phash = &ins.first->second;
2583     }
2584
2585   std::string decl_name;
2586   if (name == NULL)
2587     decl_name = this->unnamed_type_descriptor_decl_name(type);
2588   else
2589     decl_name = this->type_descriptor_decl_name(name->named_object(),
2590                                                 name->in_function());
2591   tree id = get_identifier_from_string(decl_name);
2592   tree descriptor_type_tree = initializer->type()->get_tree(this);
2593   if (descriptor_type_tree == error_mark_node)
2594     {
2595       *pdecl = error_mark_node;
2596       return;
2597     }
2598   tree decl = build_decl(name == NULL ? BUILTINS_LOCATION : name->location(),
2599                          VAR_DECL, id,
2600                          build_qualified_type(descriptor_type_tree,
2601                                               TYPE_QUAL_CONST));
2602   TREE_READONLY(decl) = 1;
2603   TREE_CONSTANT(decl) = 1;
2604   DECL_ARTIFICIAL(decl) = 1;
2605
2606   go_preserve_from_gc(decl);
2607   if (phash != NULL)
2608     *phash = decl;
2609
2610   // We store the new DECL now because we may need to refer to it when
2611   // expanding INITIALIZER.
2612   *pdecl = decl;
2613
2614   // If appropriate, just refer to the exported type identifier.
2615   Gogo::Type_descriptor_location type_descriptor_location =
2616     this->type_descriptor_location(type);
2617   if (type_descriptor_location == TYPE_DESCRIPTOR_UNDEFINED)
2618     {
2619       TREE_PUBLIC(decl) = 1;
2620       DECL_EXTERNAL(decl) = 1;
2621       return;
2622     }
2623
2624   TREE_STATIC(decl) = 1;
2625   TREE_USED(decl) = 1;
2626
2627   Translate_context context(this, NULL, NULL, NULL);
2628   context.set_is_const();
2629   tree constructor = initializer->get_tree(&context);
2630
2631   if (constructor == error_mark_node)
2632     gcc_assert(saw_errors());
2633
2634   DECL_INITIAL(decl) = constructor;
2635
2636   if (type_descriptor_location == TYPE_DESCRIPTOR_COMMON)
2637     {
2638       make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2639       resolve_unique_section(decl, 1, 0);
2640     }
2641   else
2642     {
2643 #ifdef OBJECT_FORMAT_ELF
2644       // Give the decl protected visibility.  This avoids out-of-range
2645       // references with shared libraries with the x86_64 small model
2646       // when the type descriptor gets a COPY reloc into the main
2647       // executable.  There is no need to have unique pointers to type
2648       // descriptors, as the runtime code compares reflection strings
2649       // if necessary.
2650       DECL_VISIBILITY(decl) = VISIBILITY_PROTECTED;
2651       DECL_VISIBILITY_SPECIFIED(decl) = 1;
2652 #endif
2653
2654       TREE_PUBLIC(decl) = 1;
2655     }
2656
2657   rest_of_decl_compilation(decl, 1, 0);
2658 }
2659
2660 // Build an interface method table for a type: a list of function
2661 // pointers, one for each interface method.  This is used for
2662 // interfaces.
2663
2664 tree
2665 Gogo::interface_method_table_for_type(const Interface_type* interface,
2666                                       Named_type* type,
2667                                       bool is_pointer)
2668 {
2669   const Typed_identifier_list* interface_methods = interface->methods();
2670   gcc_assert(!interface_methods->empty());
2671
2672   std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_")
2673                               + interface->mangled_name(this)
2674                               + "__"
2675                               + type->mangled_name(this));
2676
2677   tree id = get_identifier_from_string(mangled_name);
2678
2679   // See whether this interface has any hidden methods.
2680   bool has_hidden_methods = false;
2681   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2682        p != interface_methods->end();
2683        ++p)
2684     {
2685       if (Gogo::is_hidden_name(p->name()))
2686         {
2687           has_hidden_methods = true;
2688           break;
2689         }
2690     }
2691
2692   // We already know that the named type is convertible to the
2693   // interface.  If the interface has hidden methods, and the named
2694   // type is defined in a different package, then the interface
2695   // conversion table will be defined by that other package.
2696   if (has_hidden_methods && type->named_object()->package() != NULL)
2697     {
2698       tree array_type = build_array_type(const_ptr_type_node, NULL);
2699       tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2700       TREE_READONLY(decl) = 1;
2701       TREE_CONSTANT(decl) = 1;
2702       TREE_PUBLIC(decl) = 1;
2703       DECL_EXTERNAL(decl) = 1;
2704       go_preserve_from_gc(decl);
2705       return decl;
2706     }
2707
2708   size_t count = interface_methods->size();
2709   VEC(constructor_elt, gc)* pointers = VEC_alloc(constructor_elt, gc,
2710                                                  count + 1);
2711
2712   // The first element is the type descriptor.
2713   constructor_elt* elt = VEC_quick_push(constructor_elt, pointers, NULL);
2714   elt->index = size_zero_node;
2715   Type* td_type;
2716   if (!is_pointer)
2717     td_type = type;
2718   else
2719     td_type = Type::make_pointer_type(type);
2720   elt->value = fold_convert(const_ptr_type_node,
2721                             td_type->type_descriptor_pointer(this));
2722
2723   size_t i = 1;
2724   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2725        p != interface_methods->end();
2726        ++p, ++i)
2727     {
2728       bool is_ambiguous;
2729       Method* m = type->method_function(p->name(), &is_ambiguous);
2730       gcc_assert(m != NULL);
2731
2732       Named_object* no = m->named_object();
2733
2734       tree fnid = no->get_id(this);
2735
2736       tree fndecl;
2737       if (no->is_function())
2738         fndecl = no->func_value()->get_or_make_decl(this, no, fnid);
2739       else if (no->is_function_declaration())
2740         fndecl = no->func_declaration_value()->get_or_make_decl(this, no,
2741                                                                 fnid);
2742       else
2743         gcc_unreachable();
2744       fndecl = build_fold_addr_expr(fndecl);
2745
2746       elt = VEC_quick_push(constructor_elt, pointers, NULL);
2747       elt->index = size_int(i);
2748       elt->value = fold_convert(const_ptr_type_node, fndecl);
2749     }
2750   gcc_assert(i == count + 1);
2751
2752   tree array_type = build_array_type(const_ptr_type_node,
2753                                      build_index_type(size_int(count)));
2754   tree constructor = build_constructor(array_type, pointers);
2755
2756   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2757   TREE_STATIC(decl) = 1;
2758   TREE_USED(decl) = 1;
2759   TREE_READONLY(decl) = 1;
2760   TREE_CONSTANT(decl) = 1;
2761   DECL_INITIAL(decl) = constructor;
2762
2763   // If the interface type has hidden methods, then this is the only
2764   // definition of the table.  Otherwise it is a comdat table which
2765   // may be defined in multiple packages.
2766   if (has_hidden_methods)
2767     {
2768 #ifdef OBJECT_FORMAT_ELF
2769       // Give the decl protected visibility.  This avoids out-of-range
2770       // references with shared libraries with the x86_64 small model
2771       // when the table gets a COPY reloc into the main executable.
2772       DECL_VISIBILITY(decl) = VISIBILITY_PROTECTED;
2773       DECL_VISIBILITY_SPECIFIED(decl) = 1;
2774 #endif
2775
2776       TREE_PUBLIC(decl) = 1;
2777     }
2778   else
2779     {
2780       make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2781       resolve_unique_section(decl, 1, 0);
2782     }
2783
2784   rest_of_decl_compilation(decl, 1, 0);
2785
2786   go_preserve_from_gc(decl);
2787
2788   return decl;
2789 }
2790
2791 // Mark a function as a builtin library function.
2792
2793 void
2794 Gogo::mark_fndecl_as_builtin_library(tree fndecl)
2795 {
2796   DECL_EXTERNAL(fndecl) = 1;
2797   TREE_PUBLIC(fndecl) = 1;
2798   DECL_ARTIFICIAL(fndecl) = 1;
2799   TREE_NOTHROW(fndecl) = 1;
2800   DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT;
2801   DECL_VISIBILITY_SPECIFIED(fndecl) = 1;
2802 }
2803
2804 // Build a call to a builtin function.
2805
2806 tree
2807 Gogo::call_builtin(tree* pdecl, source_location location, const char* name,
2808                    int nargs, tree rettype, ...)
2809 {
2810   if (rettype == error_mark_node)
2811     return error_mark_node;
2812
2813   tree* types = new tree[nargs];
2814   tree* args = new tree[nargs];
2815
2816   va_list ap;
2817   va_start(ap, rettype);
2818   for (int i = 0; i < nargs; ++i)
2819     {
2820       types[i] = va_arg(ap, tree);
2821       args[i] = va_arg(ap, tree);
2822       if (types[i] == error_mark_node || args[i] == error_mark_node)
2823         return error_mark_node;
2824     }
2825   va_end(ap);
2826
2827   if (*pdecl == NULL_TREE)
2828     {
2829       tree fnid = get_identifier(name);
2830
2831       tree argtypes = NULL_TREE;
2832       tree* pp = &argtypes;
2833       for (int i = 0; i < nargs; ++i)
2834         {
2835           *pp = tree_cons(NULL_TREE, types[i], NULL_TREE);
2836           pp = &TREE_CHAIN(*pp);
2837         }
2838       *pp = void_list_node;
2839
2840       tree fntype = build_function_type(rettype, argtypes);
2841
2842       *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype);
2843       Gogo::mark_fndecl_as_builtin_library(*pdecl);
2844       go_preserve_from_gc(*pdecl);
2845     }
2846
2847   tree fnptr = build_fold_addr_expr(*pdecl);
2848   if (CAN_HAVE_LOCATION_P(fnptr))
2849     SET_EXPR_LOCATION(fnptr, location);
2850
2851   tree ret = build_call_array(rettype, fnptr, nargs, args);
2852   SET_EXPR_LOCATION(ret, location);
2853
2854   delete[] types;
2855   delete[] args;
2856
2857   return ret;
2858 }
2859
2860 // Build a call to the runtime error function.
2861
2862 tree
2863 Gogo::runtime_error(int code, source_location location)
2864 {
2865   static tree runtime_error_fndecl;
2866   tree ret = Gogo::call_builtin(&runtime_error_fndecl,
2867                                 location,
2868                                 "__go_runtime_error",
2869                                 1,
2870                                 void_type_node,
2871                                 integer_type_node,
2872                                 build_int_cst(integer_type_node, code));
2873   if (ret == error_mark_node)
2874     return error_mark_node;
2875   // The runtime error function panics and does not return.
2876   TREE_NOTHROW(runtime_error_fndecl) = 0;
2877   TREE_THIS_VOLATILE(runtime_error_fndecl) = 1;
2878   return ret;
2879 }
2880
2881 // Send VAL on CHANNEL.  If BLOCKING is true, the resulting tree has a
2882 // void type.  If BLOCKING is false, the resulting tree has a boolean
2883 // type, and it will evaluate as true if the value was sent.  If
2884 // FOR_SELECT is true, this is being done because it was chosen in a
2885 // select statement.
2886
2887 tree
2888 Gogo::send_on_channel(tree channel, tree val, bool blocking, bool for_select,
2889                       source_location location)
2890 {
2891   if (int_size_in_bytes(TREE_TYPE(val)) <= 8
2892       && !AGGREGATE_TYPE_P(TREE_TYPE(val))
2893       && !FLOAT_TYPE_P(TREE_TYPE(val)))
2894     {
2895       val = convert_to_integer(uint64_type_node, val);
2896       if (blocking)
2897         {
2898           static tree send_small_fndecl;
2899           tree ret = Gogo::call_builtin(&send_small_fndecl,
2900                                         location,
2901                                         "__go_send_small",
2902                                         3,
2903                                         void_type_node,
2904                                         ptr_type_node,
2905                                         channel,
2906                                         uint64_type_node,
2907                                         val,
2908                                         boolean_type_node,
2909                                         (for_select
2910                                          ? boolean_true_node
2911                                          : boolean_false_node));
2912           if (ret == error_mark_node)
2913             return error_mark_node;
2914           // This can panic if there are too many operations on a
2915           // closed channel.
2916           TREE_NOTHROW(send_small_fndecl) = 0;
2917           return ret;
2918         }
2919       else
2920         {
2921           gcc_assert(!for_select);
2922           static tree send_nonblocking_small_fndecl;
2923           tree ret = Gogo::call_builtin(&send_nonblocking_small_fndecl,
2924                                         location,
2925                                         "__go_send_nonblocking_small",
2926                                         2,
2927                                         boolean_type_node,
2928                                         ptr_type_node,
2929                                         channel,
2930                                         uint64_type_node,
2931                                         val);
2932           if (ret == error_mark_node)
2933             return error_mark_node;
2934           // This can panic if there are too many operations on a
2935           // closed channel.
2936           TREE_NOTHROW(send_nonblocking_small_fndecl) = 0;
2937           return ret;
2938         }
2939     }
2940   else
2941     {
2942       tree make_tmp;
2943       if (TREE_ADDRESSABLE(TREE_TYPE(val)) || TREE_CODE(val) == VAR_DECL)
2944         {
2945           make_tmp = NULL_TREE;
2946           val = build_fold_addr_expr(val);
2947           if (DECL_P(val))
2948             TREE_ADDRESSABLE(val) = 1;
2949         }
2950       else
2951         {
2952           tree tmp = create_tmp_var(TREE_TYPE(val), get_name(val));
2953           DECL_IGNORED_P(tmp) = 0;
2954           DECL_INITIAL(tmp) = val;
2955           TREE_ADDRESSABLE(tmp) = 1;
2956           make_tmp = build1(DECL_EXPR, void_type_node, tmp);
2957           SET_EXPR_LOCATION(make_tmp, location);
2958           val = build_fold_addr_expr(tmp);
2959         }
2960       val = fold_convert(ptr_type_node, val);
2961
2962       tree call;
2963       if (blocking)
2964         {
2965           static tree send_big_fndecl;
2966           call = Gogo::call_builtin(&send_big_fndecl,
2967                                     location,
2968                                     "__go_send_big",
2969                                     3,
2970                                     void_type_node,
2971                                     ptr_type_node,
2972                                     channel,
2973                                     ptr_type_node,
2974                                     val,
2975                                     boolean_type_node,
2976                                     (for_select
2977                                      ? boolean_true_node
2978                                      : boolean_false_node));
2979           if (call == error_mark_node)
2980             return error_mark_node;
2981           // This can panic if there are too many operations on a
2982           // closed channel.
2983           TREE_NOTHROW(send_big_fndecl) = 0;
2984         }
2985       else
2986         {
2987           gcc_assert(!for_select);
2988           static tree send_nonblocking_big_fndecl;
2989           call = Gogo::call_builtin(&send_nonblocking_big_fndecl,
2990                                     location,
2991                                     "__go_send_nonblocking_big",
2992                                     2,
2993                                     boolean_type_node,
2994                                     ptr_type_node,
2995                                     channel,
2996                                     ptr_type_node,
2997                                     val);
2998           if (call == error_mark_node)
2999             return error_mark_node;
3000           // This can panic if there are too many operations on a
3001           // closed channel.
3002           TREE_NOTHROW(send_nonblocking_big_fndecl) = 0;
3003         }
3004
3005       if (make_tmp == NULL_TREE)
3006         return call;
3007       else
3008         {
3009           tree ret = build2(COMPOUND_EXPR, TREE_TYPE(call), make_tmp, call);
3010           SET_EXPR_LOCATION(ret, location);
3011           return ret;
3012         }
3013     }
3014 }
3015
3016 // Return a tree for receiving a value of type TYPE_TREE on CHANNEL.
3017 // This does a blocking receive and returns the value read from the
3018 // channel.  If FOR_SELECT is true, this is being done because it was
3019 // chosen in a select statement.
3020
3021 tree
3022 Gogo::receive_from_channel(tree type_tree, tree channel, bool for_select,
3023                            source_location location)
3024 {
3025   if (int_size_in_bytes(type_tree) <= 8
3026       && !AGGREGATE_TYPE_P(type_tree)
3027       && !FLOAT_TYPE_P(type_tree))
3028     {
3029       static tree receive_small_fndecl;
3030       tree call = Gogo::call_builtin(&receive_small_fndecl,
3031                                      location,
3032                                      "__go_receive_small",
3033                                      2,
3034                                      uint64_type_node,
3035                                      ptr_type_node,
3036                                      channel,
3037                                      boolean_type_node,
3038                                      (for_select
3039                                       ? boolean_true_node
3040                                       : boolean_false_node));
3041       if (call == error_mark_node)
3042         return error_mark_node;
3043       // This can panic if there are too many operations on a closed
3044       // channel.
3045       TREE_NOTHROW(receive_small_fndecl) = 0;
3046       int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree));
3047       tree int_type_tree = go_type_for_size(bitsize, 1);
3048       return fold_convert_loc(location, type_tree,
3049                               fold_convert_loc(location, int_type_tree,
3050                                                call));
3051     }
3052   else
3053     {
3054       tree tmp = create_tmp_var(type_tree, get_name(type_tree));
3055       DECL_IGNORED_P(tmp) = 0;
3056       TREE_ADDRESSABLE(tmp) = 1;
3057       tree make_tmp = build1(DECL_EXPR, void_type_node, tmp);
3058       SET_EXPR_LOCATION(make_tmp, location);
3059       tree tmpaddr = build_fold_addr_expr(tmp);
3060       tmpaddr = fold_convert(ptr_type_node, tmpaddr);
3061       static tree receive_big_fndecl;
3062       tree call = Gogo::call_builtin(&receive_big_fndecl,
3063                                      location,
3064                                      "__go_receive_big",
3065                                      3,
3066                                      void_type_node,
3067                                      ptr_type_node,
3068                                      channel,
3069                                      ptr_type_node,
3070                                      tmpaddr,
3071                                      boolean_type_node,
3072                                      (for_select
3073                                       ? boolean_true_node
3074                                       : boolean_false_node));
3075       if (call == error_mark_node)
3076         return error_mark_node;
3077       // This can panic if there are too many operations on a closed
3078       // channel.
3079       TREE_NOTHROW(receive_big_fndecl) = 0;
3080       return build2(COMPOUND_EXPR, type_tree, make_tmp,
3081                     build2(COMPOUND_EXPR, type_tree, call, tmp));
3082     }
3083 }
3084
3085 // Return the type of a function trampoline.  This is like
3086 // get_trampoline_type in tree-nested.c.
3087
3088 tree
3089 Gogo::trampoline_type_tree()
3090 {
3091   static tree type_tree;
3092   if (type_tree == NULL_TREE)
3093     {
3094       unsigned int size;
3095       unsigned int align;
3096       go_trampoline_info(&size, &align);
3097       tree t = build_index_type(build_int_cst(integer_type_node, size - 1));
3098       t = build_array_type(char_type_node, t);
3099
3100       type_tree = Gogo::builtin_struct(NULL, "__go_trampoline", NULL_TREE, 1,
3101                                        "__data", t);
3102       t = TYPE_FIELDS(type_tree);
3103       DECL_ALIGN(t) = align;
3104       DECL_USER_ALIGN(t) = 1;
3105
3106       go_preserve_from_gc(type_tree);
3107     }
3108   return type_tree;
3109 }
3110
3111 // Make a trampoline which calls FNADDR passing CLOSURE.
3112
3113 tree
3114 Gogo::make_trampoline(tree fnaddr, tree closure, source_location location)
3115 {
3116   tree trampoline_type = Gogo::trampoline_type_tree();
3117   tree trampoline_size = TYPE_SIZE_UNIT(trampoline_type);
3118
3119   closure = save_expr(closure);
3120
3121   // We allocate the trampoline using a special function which will
3122   // mark it as executable.
3123   static tree trampoline_fndecl;
3124   tree x = Gogo::call_builtin(&trampoline_fndecl,
3125                               location,
3126                               "__go_allocate_trampoline",
3127                               2,
3128                               ptr_type_node,
3129                               size_type_node,
3130                               trampoline_size,
3131                               ptr_type_node,
3132                               fold_convert_loc(location, ptr_type_node,
3133                                                closure));
3134   if (x == error_mark_node)
3135     return error_mark_node;
3136
3137   x = save_expr(x);
3138
3139   // Initialize the trampoline.
3140   tree ini = build_call_expr(implicit_built_in_decls[BUILT_IN_INIT_TRAMPOLINE],
3141                              3, x, fnaddr, closure);
3142
3143   // On some targets the trampoline address needs to be adjusted.  For
3144   // example, when compiling in Thumb mode on the ARM, the address
3145   // needs to have the low bit set.
3146   x = build_call_expr(implicit_built_in_decls[BUILT_IN_ADJUST_TRAMPOLINE],
3147                       1, x);
3148   x = fold_convert(TREE_TYPE(fnaddr), x);
3149
3150   return build2(COMPOUND_EXPR, TREE_TYPE(x), ini, x);
3151 }