OSDN Git Service

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