OSDN Git Service

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