OSDN Git Service

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