OSDN Git Service

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