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 "toplev.h"
10 #include "tree.h"
11 #include "stringpool.h"
12 #include "stor-layout.h"
13 #include "varasm.h"
14 #include "gimple-expr.h"
15 #include "gimplify.h"
16 #include "tree-iterator.h"
17 #include "cgraph.h"
18 #include "langhooks.h"
19 #include "convert.h"
20 #include "output.h"
21 #include "diagnostic.h"
22 #include "go-c.h"
23 
24 #include "types.h"
25 #include "expressions.h"
26 #include "statements.h"
27 #include "runtime.h"
28 #include "backend.h"
29 #include "gogo.h"
30 
31 // Whether we have seen any errors.
32 
33 bool
saw_errors()34 saw_errors()
35 {
36   return errorcount != 0 || sorrycount != 0;
37 }
38 
39 // A helper function.
40 
41 static inline tree
get_identifier_from_string(const std::string & str)42 get_identifier_from_string(const std::string& str)
43 {
44   return get_identifier_with_length(str.data(), str.length());
45 }
46 
47 // Builtin functions.
48 
49 static std::map<std::string, tree> builtin_functions;
50 
51 // Define a builtin function.  BCODE is the builtin function code
52 // defined by builtins.def.  NAME is the name of the builtin function.
53 // LIBNAME is the name of the corresponding library function, and is
54 // NULL if there isn't one.  FNTYPE is the type of the function.
55 // CONST_P is true if the function has the const attribute.
56 
57 static void
define_builtin(built_in_function bcode,const char * name,const char * libname,tree fntype,bool const_p)58 define_builtin(built_in_function bcode, const char* name, const char* libname,
59 	       tree fntype, bool const_p)
60 {
61   tree decl = add_builtin_function(name, fntype, bcode, BUILT_IN_NORMAL,
62 				   libname, NULL_TREE);
63   if (const_p)
64     TREE_READONLY(decl) = 1;
65   set_builtin_decl(bcode, decl, true);
66   builtin_functions[name] = decl;
67   if (libname != NULL)
68     {
69       decl = add_builtin_function(libname, fntype, bcode, BUILT_IN_NORMAL,
70 				  NULL, NULL_TREE);
71       if (const_p)
72 	TREE_READONLY(decl) = 1;
73       builtin_functions[libname] = decl;
74     }
75 }
76 
77 // Create trees for implicit builtin functions.
78 
79 void
define_builtin_function_trees()80 Gogo::define_builtin_function_trees()
81 {
82   /* We need to define the fetch_and_add functions, since we use them
83      for ++ and --.  */
84   tree t = go_type_for_size(BITS_PER_UNIT, 1);
85   tree p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
86   define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_1, "__sync_fetch_and_add_1", NULL,
87 		 build_function_type_list(t, p, t, NULL_TREE), false);
88 
89   t = go_type_for_size(BITS_PER_UNIT * 2, 1);
90   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
91   define_builtin (BUILT_IN_SYNC_ADD_AND_FETCH_2, "__sync_fetch_and_add_2", NULL,
92 		  build_function_type_list(t, p, t, NULL_TREE), false);
93 
94   t = go_type_for_size(BITS_PER_UNIT * 4, 1);
95   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
96   define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_4, "__sync_fetch_and_add_4", NULL,
97 		 build_function_type_list(t, p, t, NULL_TREE), false);
98 
99   t = go_type_for_size(BITS_PER_UNIT * 8, 1);
100   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
101   define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_8, "__sync_fetch_and_add_8", NULL,
102 		 build_function_type_list(t, p, t, NULL_TREE), false);
103 
104   // We use __builtin_expect for magic import functions.
105   define_builtin(BUILT_IN_EXPECT, "__builtin_expect", NULL,
106 		 build_function_type_list(long_integer_type_node,
107 					  long_integer_type_node,
108 					  long_integer_type_node,
109 					  NULL_TREE),
110 		 true);
111 
112   // We use __builtin_memcmp for struct comparisons.
113   define_builtin(BUILT_IN_MEMCMP, "__builtin_memcmp", "memcmp",
114 		 build_function_type_list(integer_type_node,
115 					  const_ptr_type_node,
116 					  const_ptr_type_node,
117 					  size_type_node,
118 					  NULL_TREE),
119 		 false);
120 
121   // We provide some functions for the math library.
122   tree math_function_type = build_function_type_list(double_type_node,
123 						     double_type_node,
124 						     NULL_TREE);
125   tree math_function_type_long =
126     build_function_type_list(long_double_type_node, long_double_type_node,
127 			     long_double_type_node, NULL_TREE);
128   tree math_function_type_two = build_function_type_list(double_type_node,
129 							 double_type_node,
130 							 double_type_node,
131 							 NULL_TREE);
132   tree math_function_type_long_two =
133     build_function_type_list(long_double_type_node, long_double_type_node,
134 			     long_double_type_node, NULL_TREE);
135   define_builtin(BUILT_IN_ACOS, "__builtin_acos", "acos",
136 		 math_function_type, true);
137   define_builtin(BUILT_IN_ACOSL, "__builtin_acosl", "acosl",
138 		 math_function_type_long, true);
139   define_builtin(BUILT_IN_ASIN, "__builtin_asin", "asin",
140 		 math_function_type, true);
141   define_builtin(BUILT_IN_ASINL, "__builtin_asinl", "asinl",
142 		 math_function_type_long, true);
143   define_builtin(BUILT_IN_ATAN, "__builtin_atan", "atan",
144 		 math_function_type, true);
145   define_builtin(BUILT_IN_ATANL, "__builtin_atanl", "atanl",
146 		 math_function_type_long, true);
147   define_builtin(BUILT_IN_ATAN2, "__builtin_atan2", "atan2",
148 		 math_function_type_two, true);
149   define_builtin(BUILT_IN_ATAN2L, "__builtin_atan2l", "atan2l",
150 		 math_function_type_long_two, true);
151   define_builtin(BUILT_IN_CEIL, "__builtin_ceil", "ceil",
152 		 math_function_type, true);
153   define_builtin(BUILT_IN_CEILL, "__builtin_ceill", "ceill",
154 		 math_function_type_long, true);
155   define_builtin(BUILT_IN_COS, "__builtin_cos", "cos",
156 		 math_function_type, true);
157   define_builtin(BUILT_IN_COSL, "__builtin_cosl", "cosl",
158 		 math_function_type_long, true);
159   define_builtin(BUILT_IN_EXP, "__builtin_exp", "exp",
160 		 math_function_type, true);
161   define_builtin(BUILT_IN_EXPL, "__builtin_expl", "expl",
162 		 math_function_type_long, true);
163   define_builtin(BUILT_IN_EXPM1, "__builtin_expm1", "expm1",
164 		 math_function_type, true);
165   define_builtin(BUILT_IN_EXPM1L, "__builtin_expm1l", "expm1l",
166 		 math_function_type_long, true);
167   define_builtin(BUILT_IN_FABS, "__builtin_fabs", "fabs",
168 		 math_function_type, true);
169   define_builtin(BUILT_IN_FABSL, "__builtin_fabsl", "fabsl",
170 		 math_function_type_long, true);
171   define_builtin(BUILT_IN_FLOOR, "__builtin_floor", "floor",
172 		 math_function_type, true);
173   define_builtin(BUILT_IN_FLOORL, "__builtin_floorl", "floorl",
174 		 math_function_type_long, true);
175   define_builtin(BUILT_IN_FMOD, "__builtin_fmod", "fmod",
176 		 math_function_type_two, true);
177   define_builtin(BUILT_IN_FMODL, "__builtin_fmodl", "fmodl",
178 		 math_function_type_long_two, true);
179   define_builtin(BUILT_IN_LDEXP, "__builtin_ldexp", "ldexp",
180 		 build_function_type_list(double_type_node,
181 					  double_type_node,
182 					  integer_type_node,
183 					  NULL_TREE),
184 		 true);
185   define_builtin(BUILT_IN_LDEXPL, "__builtin_ldexpl", "ldexpl",
186 		 build_function_type_list(long_double_type_node,
187 					  long_double_type_node,
188 					  integer_type_node,
189 					  NULL_TREE),
190 		 true);
191   define_builtin(BUILT_IN_LOG, "__builtin_log", "log",
192 		 math_function_type, true);
193   define_builtin(BUILT_IN_LOGL, "__builtin_logl", "logl",
194 		 math_function_type_long, true);
195   define_builtin(BUILT_IN_LOG1P, "__builtin_log1p", "log1p",
196 		 math_function_type, true);
197   define_builtin(BUILT_IN_LOG1PL, "__builtin_log1pl", "log1pl",
198 		 math_function_type_long, true);
199   define_builtin(BUILT_IN_LOG10, "__builtin_log10", "log10",
200 		 math_function_type, true);
201   define_builtin(BUILT_IN_LOG10L, "__builtin_log10l", "log10l",
202 		 math_function_type_long, true);
203   define_builtin(BUILT_IN_LOG2, "__builtin_log2", "log2",
204 		 math_function_type, true);
205   define_builtin(BUILT_IN_LOG2L, "__builtin_log2l", "log2l",
206 		 math_function_type_long, true);
207   define_builtin(BUILT_IN_SIN, "__builtin_sin", "sin",
208 		 math_function_type, true);
209   define_builtin(BUILT_IN_SINL, "__builtin_sinl", "sinl",
210 		 math_function_type_long, true);
211   define_builtin(BUILT_IN_SQRT, "__builtin_sqrt", "sqrt",
212 		 math_function_type, true);
213   define_builtin(BUILT_IN_SQRTL, "__builtin_sqrtl", "sqrtl",
214 		 math_function_type_long, true);
215   define_builtin(BUILT_IN_TAN, "__builtin_tan", "tan",
216 		 math_function_type, true);
217   define_builtin(BUILT_IN_TANL, "__builtin_tanl", "tanl",
218 		 math_function_type_long, true);
219   define_builtin(BUILT_IN_TRUNC, "__builtin_trunc", "trunc",
220 		 math_function_type, true);
221   define_builtin(BUILT_IN_TRUNCL, "__builtin_truncl", "truncl",
222 		 math_function_type_long, true);
223 
224   // We use __builtin_return_address in the thunk we build for
225   // functions which call recover.
226   define_builtin(BUILT_IN_RETURN_ADDRESS, "__builtin_return_address", NULL,
227 		 build_function_type_list(ptr_type_node,
228 					  unsigned_type_node,
229 					  NULL_TREE),
230 		 false);
231 
232   // The compiler uses __builtin_trap for some exception handling
233   // cases.
234   define_builtin(BUILT_IN_TRAP, "__builtin_trap", NULL,
235 		 build_function_type(void_type_node, void_list_node),
236 		 false);
237 }
238 
239 // Get the name to use for the import control function.  If there is a
240 // global function or variable, then we know that that name must be
241 // unique in the link, and we use it as the basis for our name.
242 
243 const std::string&
get_init_fn_name()244 Gogo::get_init_fn_name()
245 {
246   if (this->init_fn_name_.empty())
247     {
248       go_assert(this->package_ != NULL);
249       if (this->is_main_package())
250 	{
251 	  // Use a name which the runtime knows.
252 	  this->init_fn_name_ = "__go_init_main";
253 	}
254       else
255 	{
256 	  std::string s = this->pkgpath_symbol();
257 	  s.append("..import");
258 	  this->init_fn_name_ = s;
259 	}
260     }
261 
262   return this->init_fn_name_;
263 }
264 
265 // Add statements to INIT_STMT_LIST which run the initialization
266 // functions for imported packages.  This is only used for the "main"
267 // package.
268 
269 void
init_imports(tree * init_stmt_list)270 Gogo::init_imports(tree* init_stmt_list)
271 {
272   go_assert(this->is_main_package());
273 
274   if (this->imported_init_fns_.empty())
275     return;
276 
277   tree fntype = build_function_type(void_type_node, void_list_node);
278 
279   // We must call them in increasing priority order.
280   std::vector<Import_init> v;
281   for (std::set<Import_init>::const_iterator p =
282 	 this->imported_init_fns_.begin();
283        p != this->imported_init_fns_.end();
284        ++p)
285     v.push_back(*p);
286   std::sort(v.begin(), v.end());
287 
288   for (std::vector<Import_init>::const_iterator p = v.begin();
289        p != v.end();
290        ++p)
291     {
292       std::string user_name = p->package_name() + ".init";
293       tree decl = build_decl(UNKNOWN_LOCATION, FUNCTION_DECL,
294 			     get_identifier_from_string(user_name),
295 			     fntype);
296       const std::string& init_name(p->init_name());
297       SET_DECL_ASSEMBLER_NAME(decl, get_identifier_from_string(init_name));
298       TREE_PUBLIC(decl) = 1;
299       DECL_EXTERNAL(decl) = 1;
300       append_to_statement_list(build_call_expr(decl, 0), init_stmt_list);
301     }
302 }
303 
304 // Register global variables with the garbage collector.  We need to
305 // register all variables which can hold a pointer value.  They become
306 // roots during the mark phase.  We build a struct that is easy to
307 // hook into a list of roots.
308 
309 // struct __go_gc_root_list
310 // {
311 //   struct __go_gc_root_list* __next;
312 //   struct __go_gc_root
313 //   {
314 //     void* __decl;
315 //     size_t __size;
316 //   } __roots[];
317 // };
318 
319 // The last entry in the roots array has a NULL decl field.
320 
321 void
register_gc_vars(const std::vector<Named_object * > & var_gc,tree * init_stmt_list)322 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
323 		       tree* init_stmt_list)
324 {
325   if (var_gc.empty())
326     return;
327 
328   size_t count = var_gc.size();
329 
330   tree root_type = Gogo::builtin_struct(NULL, "__go_gc_root", NULL_TREE, 2,
331 					"__next",
332 					ptr_type_node,
333 					"__size",
334 					sizetype);
335 
336   tree index_type = build_index_type(size_int(count));
337   tree array_type = build_array_type(root_type, index_type);
338 
339   tree root_list_type = make_node(RECORD_TYPE);
340   root_list_type = Gogo::builtin_struct(NULL, "__go_gc_root_list",
341 					root_list_type, 2,
342 					"__next",
343 					build_pointer_type(root_list_type),
344 					"__roots",
345 					array_type);
346 
347   // Build an initialier for the __roots array.
348 
349   vec<constructor_elt, va_gc> *roots_init;
350   vec_alloc(roots_init, count + 1);
351 
352   size_t i = 0;
353   for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
354        p != var_gc.end();
355        ++p, ++i)
356     {
357       vec<constructor_elt, va_gc> *init;
358       vec_alloc(init, 2);
359 
360       constructor_elt empty = {NULL, NULL};
361       constructor_elt* elt = init->quick_push(empty);
362       tree field = TYPE_FIELDS(root_type);
363       elt->index = field;
364       Bvariable* bvar = (*p)->get_backend_variable(this, NULL);
365       tree decl = var_to_tree(bvar);
366       go_assert(TREE_CODE(decl) == VAR_DECL);
367       elt->value = build_fold_addr_expr(decl);
368 
369       elt = init->quick_push(empty);
370       field = DECL_CHAIN(field);
371       elt->index = field;
372       elt->value = DECL_SIZE_UNIT(decl);
373 
374       elt = roots_init->quick_push(empty);
375       elt->index = size_int(i);
376       elt->value = build_constructor(root_type, init);
377     }
378 
379   // The list ends with a NULL entry.
380 
381   vec<constructor_elt, va_gc> *init;
382   vec_alloc(init, 2);
383 
384   constructor_elt empty = {NULL, NULL};
385   constructor_elt* elt = init->quick_push(empty);
386   tree field = TYPE_FIELDS(root_type);
387   elt->index = field;
388   elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
389 
390   elt = init->quick_push(empty);
391   field = DECL_CHAIN(field);
392   elt->index = field;
393   elt->value = size_zero_node;
394 
395   elt = roots_init->quick_push(empty);
396   elt->index = size_int(i);
397   elt->value = build_constructor(root_type, init);
398 
399   // Build a constructor for the struct.
400 
401   vec<constructor_elt, va_gc> *root_list_init;
402   vec_alloc(root_list_init, 2);
403 
404   elt = root_list_init->quick_push(empty);
405   field = TYPE_FIELDS(root_list_type);
406   elt->index = field;
407   elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
408 
409   elt = root_list_init->quick_push(empty);
410   field = DECL_CHAIN(field);
411   elt->index = field;
412   elt->value = build_constructor(array_type, roots_init);
413 
414   // Build a decl to register.
415 
416   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL,
417 			 create_tmp_var_name("gc"), root_list_type);
418   DECL_EXTERNAL(decl) = 0;
419   TREE_PUBLIC(decl) = 0;
420   TREE_STATIC(decl) = 1;
421   DECL_ARTIFICIAL(decl) = 1;
422   DECL_INITIAL(decl) = build_constructor(root_list_type, root_list_init);
423   rest_of_decl_compilation(decl, 1, 0);
424 
425   static tree register_gc_fndecl;
426   tree call = Gogo::call_builtin(&register_gc_fndecl,
427                                  Linemap::predeclared_location(),
428                                  "__go_register_gc_roots",
429 				 1,
430 				 void_type_node,
431 				 build_pointer_type(root_list_type),
432 				 build_fold_addr_expr(decl));
433   if (call != error_mark_node)
434     append_to_statement_list(call, init_stmt_list);
435 }
436 
437 // Build the decl for the initialization function.
438 
439 tree
initialization_function_decl()440 Gogo::initialization_function_decl()
441 {
442   // The tedious details of building your own function.  There doesn't
443   // seem to be a helper function for this.
444   std::string name = this->package_name() + ".init";
445   tree fndecl = build_decl(this->package_->location().gcc_location(),
446 			   FUNCTION_DECL, get_identifier_from_string(name),
447 			   build_function_type(void_type_node,
448 					       void_list_node));
449   const std::string& asm_name(this->get_init_fn_name());
450   SET_DECL_ASSEMBLER_NAME(fndecl, get_identifier_from_string(asm_name));
451 
452   tree resdecl = build_decl(this->package_->location().gcc_location(),
453 			    RESULT_DECL, NULL_TREE, void_type_node);
454   DECL_ARTIFICIAL(resdecl) = 1;
455   DECL_CONTEXT(resdecl) = fndecl;
456   DECL_RESULT(fndecl) = resdecl;
457 
458   TREE_STATIC(fndecl) = 1;
459   TREE_USED(fndecl) = 1;
460   DECL_ARTIFICIAL(fndecl) = 1;
461   TREE_PUBLIC(fndecl) = 1;
462 
463   DECL_INITIAL(fndecl) = make_node(BLOCK);
464   TREE_USED(DECL_INITIAL(fndecl)) = 1;
465 
466   return fndecl;
467 }
468 
469 // Create the magic initialization function.  INIT_STMT_LIST is the
470 // code that it needs to run.
471 
472 void
write_initialization_function(tree fndecl,tree init_stmt_list)473 Gogo::write_initialization_function(tree fndecl, tree init_stmt_list)
474 {
475   // Make sure that we thought we needed an initialization function,
476   // as otherwise we will not have reported it in the export data.
477   go_assert(this->is_main_package() || this->need_init_fn_);
478 
479   if (fndecl == NULL_TREE)
480     fndecl = this->initialization_function_decl();
481 
482   DECL_SAVED_TREE(fndecl) = init_stmt_list;
483 
484   if (DECL_STRUCT_FUNCTION(fndecl) == NULL)
485     push_struct_function(fndecl);
486   else
487     push_cfun(DECL_STRUCT_FUNCTION(fndecl));
488   cfun->function_start_locus = this->package_->location().gcc_location();
489   cfun->function_end_locus = cfun->function_start_locus;
490 
491   gimplify_function_tree(fndecl);
492 
493   cgraph_add_new_function(fndecl, false);
494 
495   pop_cfun();
496 }
497 
498 // Search for references to VAR in any statements or called functions.
499 
500 class Find_var : public Traverse
501 {
502  public:
503   // A hash table we use to avoid looping.  The index is the name of a
504   // named object.  We only look through objects defined in this
505   // package.
506   typedef Unordered_set(const void*) Seen_objects;
507 
Find_var(Named_object * var,Seen_objects * seen_objects)508   Find_var(Named_object* var, Seen_objects* seen_objects)
509     : Traverse(traverse_expressions),
510       var_(var), seen_objects_(seen_objects), found_(false)
511   { }
512 
513   // Whether the variable was found.
514   bool
found() const515   found() const
516   { return this->found_; }
517 
518   int
519   expression(Expression**);
520 
521  private:
522   // The variable we are looking for.
523   Named_object* var_;
524   // Names of objects we have already seen.
525   Seen_objects* seen_objects_;
526   // True if the variable was found.
527   bool found_;
528 };
529 
530 // See if EXPR refers to VAR, looking through function calls and
531 // variable initializations.
532 
533 int
expression(Expression ** pexpr)534 Find_var::expression(Expression** pexpr)
535 {
536   Expression* e = *pexpr;
537 
538   Var_expression* ve = e->var_expression();
539   if (ve != NULL)
540     {
541       Named_object* v = ve->named_object();
542       if (v == this->var_)
543 	{
544 	  this->found_ = true;
545 	  return TRAVERSE_EXIT;
546 	}
547 
548       if (v->is_variable() && v->package() == NULL)
549 	{
550 	  Expression* init = v->var_value()->init();
551 	  if (init != NULL)
552 	    {
553 	      std::pair<Seen_objects::iterator, bool> ins =
554 		this->seen_objects_->insert(v);
555 	      if (ins.second)
556 		{
557 		  // This is the first time we have seen this name.
558 		  if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
559 		    return TRAVERSE_EXIT;
560 		}
561 	    }
562 	}
563     }
564 
565   // We traverse the code of any function we see.  Note that this
566   // means that we will traverse the code of a function whose address
567   // is taken even if it is not called.
568   Func_expression* fe = e->func_expression();
569   if (fe != NULL)
570     {
571       const Named_object* f = fe->named_object();
572       if (f->is_function() && f->package() == NULL)
573 	{
574 	  std::pair<Seen_objects::iterator, bool> ins =
575 	    this->seen_objects_->insert(f);
576 	  if (ins.second)
577 	    {
578 	      // This is the first time we have seen this name.
579 	      if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
580 		return TRAVERSE_EXIT;
581 	    }
582 	}
583     }
584 
585   Temporary_reference_expression* tre = e->temporary_reference_expression();
586   if (tre != NULL)
587     {
588       Temporary_statement* ts = tre->statement();
589       Expression* init = ts->init();
590       if (init != NULL)
591 	{
592 	  std::pair<Seen_objects::iterator, bool> ins =
593 	    this->seen_objects_->insert(ts);
594 	  if (ins.second)
595 	    {
596 	      // This is the first time we have seen this temporary
597 	      // statement.
598 	      if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
599 		return TRAVERSE_EXIT;
600 	    }
601 	}
602     }
603 
604   return TRAVERSE_CONTINUE;
605 }
606 
607 // Return true if EXPR, PREINIT, or DEP refers to VAR.
608 
609 static bool
expression_requires(Expression * expr,Block * preinit,Named_object * dep,Named_object * var)610 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
611 		    Named_object* var)
612 {
613   Find_var::Seen_objects seen_objects;
614   Find_var find_var(var, &seen_objects);
615   if (expr != NULL)
616     Expression::traverse(&expr, &find_var);
617   if (preinit != NULL)
618     preinit->traverse(&find_var);
619   if (dep != NULL)
620     {
621       Expression* init = dep->var_value()->init();
622       if (init != NULL)
623 	Expression::traverse(&init, &find_var);
624       if (dep->var_value()->has_pre_init())
625 	dep->var_value()->preinit()->traverse(&find_var);
626     }
627 
628   return find_var.found();
629 }
630 
631 // Sort variable initializations.  If the initialization expression
632 // for variable A refers directly or indirectly to the initialization
633 // expression for variable B, then we must initialize B before A.
634 
635 class Var_init
636 {
637  public:
Var_init()638   Var_init()
639     : var_(NULL), init_(NULL_TREE)
640   { }
641 
Var_init(Named_object * var,tree init)642   Var_init(Named_object* var, tree init)
643     : var_(var), init_(init)
644   { }
645 
646   // Return the variable.
647   Named_object*
var() const648   var() const
649   { return this->var_; }
650 
651   // Return the initialization expression.
652   tree
init() const653   init() const
654   { return this->init_; }
655 
656  private:
657   // The variable being initialized.
658   Named_object* var_;
659   // The initialization expression to run.
660   tree init_;
661 };
662 
663 typedef std::list<Var_init> Var_inits;
664 
665 // Sort the variable initializations.  The rule we follow is that we
666 // emit them in the order they appear in the array, except that if the
667 // initialization expression for a variable V1 depends upon another
668 // variable V2 then we initialize V1 after V2.
669 
670 static void
sort_var_inits(Gogo * gogo,Var_inits * var_inits)671 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
672 {
673   typedef std::pair<Named_object*, Named_object*> No_no;
674   typedef std::map<No_no, bool> Cache;
675   Cache cache;
676 
677   Var_inits ready;
678   while (!var_inits->empty())
679     {
680       Var_inits::iterator p1 = var_inits->begin();
681       Named_object* var = p1->var();
682       Expression* init = var->var_value()->init();
683       Block* preinit = var->var_value()->preinit();
684       Named_object* dep = gogo->var_depends_on(var->var_value());
685 
686       // Start walking through the list to see which variables VAR
687       // needs to wait for.
688       Var_inits::iterator p2 = p1;
689       ++p2;
690 
691       for (; p2 != var_inits->end(); ++p2)
692 	{
693 	  Named_object* p2var = p2->var();
694 	  No_no key(var, p2var);
695 	  std::pair<Cache::iterator, bool> ins =
696 	    cache.insert(std::make_pair(key, false));
697 	  if (ins.second)
698 	    ins.first->second = expression_requires(init, preinit, dep, p2var);
699 	  if (ins.first->second)
700 	    {
701 	      // Check for cycles.
702 	      key = std::make_pair(p2var, var);
703 	      ins = cache.insert(std::make_pair(key, false));
704 	      if (ins.second)
705 		ins.first->second =
706 		  expression_requires(p2var->var_value()->init(),
707 				      p2var->var_value()->preinit(),
708 				      gogo->var_depends_on(p2var->var_value()),
709 				      var);
710 	      if (ins.first->second)
711 		{
712 		  error_at(var->location(),
713 			   ("initialization expressions for %qs and "
714 			    "%qs depend upon each other"),
715 			   var->message_name().c_str(),
716 			   p2var->message_name().c_str());
717 		  inform(p2->var()->location(), "%qs defined here",
718 			 p2var->message_name().c_str());
719 		  p2 = var_inits->end();
720 		}
721 	      else
722 		{
723 		  // We can't emit P1 until P2 is emitted.  Move P1.
724 		  Var_inits::iterator p3 = p2;
725 		  ++p3;
726 		  var_inits->splice(p3, *var_inits, p1);
727 		}
728 	      break;
729 	    }
730 	}
731 
732       if (p2 == var_inits->end())
733 	{
734 	  // VAR does not depends upon any other initialization expressions.
735 
736 	  // Check for a loop of VAR on itself.  We only do this if
737 	  // INIT is not NULL and there is no dependency; when INIT is
738 	  // NULL, it means that PREINIT sets VAR, which we will
739 	  // interpret as a loop.
740 	  if (init != NULL && dep == NULL
741 	      && expression_requires(init, preinit, NULL, var))
742 	    error_at(var->location(),
743 		     "initialization expression for %qs depends upon itself",
744 		     var->message_name().c_str());
745 	  ready.splice(ready.end(), *var_inits, p1);
746 	}
747     }
748 
749   // Now READY is the list in the desired initialization order.
750   var_inits->swap(ready);
751 }
752 
753 // Write out the global definitions.
754 
755 void
write_globals()756 Gogo::write_globals()
757 {
758   this->build_interface_method_tables();
759 
760   Bindings* bindings = this->current_bindings();
761 
762   for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
763        p != bindings->end_declarations();
764        ++p)
765     {
766       // If any function declarations needed a descriptor, make sure
767       // we build it.
768       Named_object* no = p->second;
769       if (no->is_function_declaration())
770 	no->func_declaration_value()->build_backend_descriptor(this);
771     }
772 
773   size_t count_definitions = bindings->size_definitions();
774   size_t count = count_definitions;
775 
776   tree* vec = new tree[count];
777 
778   tree init_fndecl = NULL_TREE;
779   tree init_stmt_list = NULL_TREE;
780 
781   if (this->is_main_package())
782     this->init_imports(&init_stmt_list);
783 
784   // A list of variable initializations.
785   Var_inits var_inits;
786 
787   // A list of variables which need to be registered with the garbage
788   // collector.
789   std::vector<Named_object*> var_gc;
790   var_gc.reserve(count);
791 
792   tree var_init_stmt_list = NULL_TREE;
793   size_t i = 0;
794   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
795        p != bindings->end_definitions();
796        ++p, ++i)
797     {
798       Named_object* no = *p;
799 
800       go_assert(i < count);
801 
802       go_assert(!no->is_type_declaration() && !no->is_function_declaration());
803       // There is nothing to do for a package.
804       if (no->is_package())
805 	{
806 	  --i;
807 	  --count;
808 	  continue;
809 	}
810 
811       // There is nothing to do for an object which was imported from
812       // a different package into the global scope.
813       if (no->package() != NULL)
814 	{
815 	  --i;
816 	  --count;
817 	  continue;
818 	}
819 
820       // Skip blank named functions and constants.
821       if ((no->is_function() && no->func_value()->is_sink())
822 	  || (no->is_const() && no->const_value()->is_sink()))
823         {
824           --i;
825           --count;
826           continue;
827         }
828 
829       // There is nothing useful we can output for constants which
830       // have ideal or non-integral type.
831       if (no->is_const())
832 	{
833 	  Type* type = no->const_value()->type();
834 	  if (type == NULL)
835 	    type = no->const_value()->expr()->type();
836 	  if (type->is_abstract() || type->integer_type() == NULL)
837 	    {
838 	      --i;
839 	      --count;
840 	      continue;
841 	    }
842 	}
843 
844       if (!no->is_variable())
845 	{
846 	  vec[i] = no->get_tree(this, NULL);
847 	  if (vec[i] == error_mark_node)
848 	    {
849 	      go_assert(saw_errors());
850 	      --i;
851 	      --count;
852 	      continue;
853 	    }
854 	}
855       else
856 	{
857 	  Bvariable* var = no->get_backend_variable(this, NULL);
858 	  vec[i] = var_to_tree(var);
859 	  if (vec[i] == error_mark_node)
860 	    {
861 	      go_assert(saw_errors());
862 	      --i;
863 	      --count;
864 	      continue;
865 	    }
866 
867 	  // Check for a sink variable, which may be used to run an
868 	  // initializer purely for its side effects.
869 	  bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
870 
871 	  tree var_init_tree = NULL_TREE;
872 	  if (!no->var_value()->has_pre_init())
873 	    {
874 	      tree init = no->var_value()->get_init_tree(this, NULL);
875 	      if (init == error_mark_node)
876 		go_assert(saw_errors());
877 	      else if (init == NULL_TREE)
878 		;
879 	      else if (TREE_CONSTANT(init))
880 		{
881 		  if (expression_requires(no->var_value()->init(), NULL,
882 					  this->var_depends_on(no->var_value()),
883 					  no))
884 		    error_at(no->location(),
885 			     "initialization expression for %qs depends "
886 			     "upon itself",
887 			     no->message_name().c_str());
888 		  this->backend()->global_variable_set_init(var,
889 							    tree_to_expr(init));
890 		}
891 	      else if (is_sink
892 		       || int_size_in_bytes(TREE_TYPE(init)) == 0
893 		       || int_size_in_bytes(TREE_TYPE(vec[i])) == 0)
894 		var_init_tree = init;
895 	      else
896 		var_init_tree = fold_build2_loc(no->location().gcc_location(),
897                                                 MODIFY_EXPR, void_type_node,
898                                                 vec[i], init);
899 	    }
900 	  else
901 	    {
902 	      // We are going to create temporary variables which
903 	      // means that we need an fndecl.
904 	      if (init_fndecl == NULL_TREE)
905 		init_fndecl = this->initialization_function_decl();
906 	      if (DECL_STRUCT_FUNCTION(init_fndecl) == NULL)
907 		push_struct_function(init_fndecl);
908 	      else
909 		push_cfun(DECL_STRUCT_FUNCTION(init_fndecl));
910 	      tree var_decl = is_sink ? NULL_TREE : vec[i];
911 	      var_init_tree = no->var_value()->get_init_block(this, NULL,
912 							      var_decl);
913 	      pop_cfun();
914 	    }
915 
916 	  if (var_init_tree != NULL_TREE && var_init_tree != error_mark_node)
917 	    {
918 	      if (no->var_value()->init() == NULL
919 		  && !no->var_value()->has_pre_init())
920 		append_to_statement_list(var_init_tree, &var_init_stmt_list);
921 	      else
922 		var_inits.push_back(Var_init(no, var_init_tree));
923 	    }
924 	  else if (this->var_depends_on(no->var_value()) != NULL)
925 	    {
926 	      // This variable is initialized from something that is
927 	      // not in its init or preinit.  This variable needs to
928 	      // participate in dependency analysis sorting, in case
929 	      // some other variable depends on this one.
930 	      var_inits.push_back(Var_init(no, integer_zero_node));
931 	    }
932 
933 	  if (!is_sink && no->var_value()->type()->has_pointer())
934 	    var_gc.push_back(no);
935 	}
936     }
937 
938   // Register global variables with the garbage collector.
939   this->register_gc_vars(var_gc, &init_stmt_list);
940 
941   // Simple variable initializations, after all variables are
942   // registered.
943   append_to_statement_list(var_init_stmt_list, &init_stmt_list);
944 
945   // Complex variable initializations, first sorting them into a
946   // workable order.
947   if (!var_inits.empty())
948     {
949       sort_var_inits(this, &var_inits);
950       for (Var_inits::const_iterator p = var_inits.begin();
951 	   p != var_inits.end();
952 	   ++p)
953 	append_to_statement_list(p->init(), &init_stmt_list);
954     }
955 
956   // After all the variables are initialized, call the "init"
957   // functions if there are any.
958   for (std::vector<Named_object*>::const_iterator p =
959 	 this->init_functions_.begin();
960        p != this->init_functions_.end();
961        ++p)
962     {
963       tree decl = (*p)->get_tree(this, NULL);
964       tree call = build_call_expr(decl, 0);
965       append_to_statement_list(call, &init_stmt_list);
966     }
967 
968   // Set up a magic function to do all the initialization actions.
969   // This will be called if this package is imported.
970   if (init_stmt_list != NULL_TREE
971       || this->need_init_fn_
972       || this->is_main_package())
973     this->write_initialization_function(init_fndecl, init_stmt_list);
974 
975   // We should not have seen any new bindings created during the
976   // conversion.
977   go_assert(count_definitions == this->current_bindings()->size_definitions());
978 
979   // Pass everything back to the middle-end.
980 
981   wrapup_global_declarations(vec, count);
982 
983   finalize_compilation_unit();
984 
985   check_global_declarations(vec, count);
986   emit_debug_global_declarations(vec, count);
987 
988   delete[] vec;
989 }
990 
991 // Get a tree for a named object.
992 
993 tree
get_tree(Gogo * gogo,Named_object * function)994 Named_object::get_tree(Gogo* gogo, Named_object* function)
995 {
996   if (this->tree_ != NULL_TREE)
997     return this->tree_;
998 
999   if (Gogo::is_erroneous_name(this->name_))
1000     {
1001       this->tree_ = error_mark_node;
1002       return error_mark_node;
1003     }
1004 
1005   tree decl;
1006   switch (this->classification_)
1007     {
1008     case NAMED_OBJECT_CONST:
1009       {
1010 	Named_constant* named_constant = this->u_.const_value;
1011 	Translate_context subcontext(gogo, function, NULL, NULL);
1012 	tree expr_tree = named_constant->expr()->get_tree(&subcontext);
1013 	if (expr_tree == error_mark_node)
1014 	  decl = error_mark_node;
1015 	else
1016 	  {
1017 	    Type* type = named_constant->type();
1018 	    if (type != NULL && !type->is_abstract())
1019 	      {
1020 		if (type->is_error())
1021 		  expr_tree = error_mark_node;
1022 		else
1023 		  {
1024 		    Btype* btype = type->get_backend(gogo);
1025 		    expr_tree = fold_convert(type_to_tree(btype), expr_tree);
1026 		  }
1027 	      }
1028 	    if (expr_tree == error_mark_node)
1029 	      decl = error_mark_node;
1030 	    else if (INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
1031 	      {
1032                 tree name = get_identifier_from_string(this->get_id(gogo));
1033 		decl = build_decl(named_constant->location().gcc_location(),
1034                                   CONST_DECL, name, TREE_TYPE(expr_tree));
1035 		DECL_INITIAL(decl) = expr_tree;
1036 		TREE_CONSTANT(decl) = 1;
1037 		TREE_READONLY(decl) = 1;
1038 	      }
1039 	    else
1040 	      {
1041 		// A CONST_DECL is only for an enum constant, so we
1042 		// shouldn't use for non-integral types.  Instead we
1043 		// just return the constant itself, rather than a
1044 		// decl.
1045 		decl = expr_tree;
1046 	      }
1047 	  }
1048       }
1049       break;
1050 
1051     case NAMED_OBJECT_TYPE:
1052       {
1053 	Named_type* named_type = this->u_.type_value;
1054 	tree type_tree = type_to_tree(named_type->get_backend(gogo));
1055 	if (type_tree == error_mark_node)
1056 	  decl = error_mark_node;
1057 	else
1058 	  {
1059 	    decl = TYPE_NAME(type_tree);
1060 	    go_assert(decl != NULL_TREE);
1061 
1062 	    // We need to produce a type descriptor for every named
1063 	    // type, and for a pointer to every named type, since
1064 	    // other files or packages might refer to them.  We need
1065 	    // to do this even for hidden types, because they might
1066 	    // still be returned by some function.  Simply calling the
1067 	    // type_descriptor method is enough to create the type
1068 	    // descriptor, even though we don't do anything with it.
1069 	    if (this->package_ == NULL)
1070 	      {
1071 		named_type->
1072                   type_descriptor_pointer(gogo,
1073 					  Linemap::predeclared_location());
1074 		Type* pn = Type::make_pointer_type(named_type);
1075 		pn->type_descriptor_pointer(gogo,
1076 					    Linemap::predeclared_location());
1077 	      }
1078 	  }
1079       }
1080       break;
1081 
1082     case NAMED_OBJECT_TYPE_DECLARATION:
1083       error("reference to undefined type %qs",
1084 	    this->message_name().c_str());
1085       return error_mark_node;
1086 
1087     case NAMED_OBJECT_VAR:
1088     case NAMED_OBJECT_RESULT_VAR:
1089     case NAMED_OBJECT_SINK:
1090       go_unreachable();
1091 
1092     case NAMED_OBJECT_FUNC:
1093       {
1094 	Function* func = this->u_.func_value;
1095 	decl = function_to_tree(func->get_or_make_decl(gogo, this));
1096 	if (decl != error_mark_node)
1097 	  {
1098 	    if (func->block() != NULL)
1099 	      {
1100 		if (DECL_STRUCT_FUNCTION(decl) == NULL)
1101 		  push_struct_function(decl);
1102 		else
1103 		  push_cfun(DECL_STRUCT_FUNCTION(decl));
1104 
1105 		cfun->function_start_locus = func->location().gcc_location();
1106 		cfun->function_end_locus =
1107                   func->block()->end_location().gcc_location();
1108 
1109 		func->build_tree(gogo, this);
1110 
1111 		gimplify_function_tree(decl);
1112 
1113 		cgraph_finalize_function(decl, true);
1114 
1115 		pop_cfun();
1116 	      }
1117 	  }
1118       }
1119       break;
1120 
1121     case NAMED_OBJECT_ERRONEOUS:
1122       decl = error_mark_node;
1123       break;
1124 
1125     default:
1126       go_unreachable();
1127     }
1128 
1129   if (TREE_TYPE(decl) == error_mark_node)
1130     decl = error_mark_node;
1131 
1132   tree ret = decl;
1133 
1134   this->tree_ = ret;
1135 
1136   if (ret != error_mark_node)
1137     go_preserve_from_gc(ret);
1138 
1139   return ret;
1140 }
1141 
1142 // Get the initial value of a variable as a tree.  This does not
1143 // consider whether the variable is in the heap--it returns the
1144 // initial value as though it were always stored in the stack.
1145 
1146 tree
get_init_tree(Gogo * gogo,Named_object * function)1147 Variable::get_init_tree(Gogo* gogo, Named_object* function)
1148 {
1149   go_assert(this->preinit_ == NULL);
1150   if (this->init_ == NULL)
1151     {
1152       go_assert(!this->is_parameter_);
1153       if (this->is_global_ || this->is_in_heap())
1154 	return NULL;
1155       Btype* btype = this->type_->get_backend(gogo);
1156       return expr_to_tree(gogo->backend()->zero_expression(btype));
1157     }
1158   else
1159     {
1160       Translate_context context(gogo, function, NULL, NULL);
1161       tree rhs_tree = this->init_->get_tree(&context);
1162       return Expression::convert_for_assignment(&context, this->type(),
1163 						this->init_->type(),
1164 						rhs_tree, this->location());
1165     }
1166 }
1167 
1168 // Get the initial value of a variable when a block is required.
1169 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
1170 
1171 tree
get_init_block(Gogo * gogo,Named_object * function,tree var_decl)1172 Variable::get_init_block(Gogo* gogo, Named_object* function, tree var_decl)
1173 {
1174   go_assert(this->preinit_ != NULL);
1175 
1176   // We want to add the variable assignment to the end of the preinit
1177   // block.  The preinit block may have a TRY_FINALLY_EXPR and a
1178   // TRY_CATCH_EXPR; if it does, we want to add to the end of the
1179   // regular statements.
1180 
1181   Translate_context context(gogo, function, NULL, NULL);
1182   Bblock* bblock = this->preinit_->get_backend(&context);
1183   tree block_tree = block_to_tree(bblock);
1184   if (block_tree == error_mark_node)
1185     return error_mark_node;
1186   go_assert(TREE_CODE(block_tree) == BIND_EXPR);
1187   tree statements = BIND_EXPR_BODY(block_tree);
1188   while (statements != NULL_TREE
1189 	 && (TREE_CODE(statements) == TRY_FINALLY_EXPR
1190 	     || TREE_CODE(statements) == TRY_CATCH_EXPR))
1191     statements = TREE_OPERAND(statements, 0);
1192 
1193   // It's possible to have pre-init statements without an initializer
1194   // if the pre-init statements set the variable.
1195   if (this->init_ != NULL)
1196     {
1197       tree rhs_tree = this->init_->get_tree(&context);
1198       if (rhs_tree == error_mark_node)
1199 	return error_mark_node;
1200       if (var_decl == NULL_TREE)
1201 	append_to_statement_list(rhs_tree, &statements);
1202       else
1203 	{
1204 	  tree val = Expression::convert_for_assignment(&context, this->type(),
1205 							this->init_->type(),
1206 							rhs_tree,
1207 							this->location());
1208 	  if (val == error_mark_node)
1209 	    return error_mark_node;
1210 	  tree set = fold_build2_loc(this->location().gcc_location(),
1211                                      MODIFY_EXPR, void_type_node, var_decl,
1212                                      val);
1213 	  append_to_statement_list(set, &statements);
1214 	}
1215     }
1216 
1217   return block_tree;
1218 }
1219 
1220 // Get the backend representation.
1221 
1222 Bfunction*
get_or_make_decl(Gogo * gogo,Named_object * no)1223 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
1224 {
1225   if (this->fndecl_ == NULL)
1226     {
1227       // Let Go code use an asm declaration to pick up a builtin
1228       // function.
1229       if (!this->asm_name_.empty())
1230 	{
1231 	  std::map<std::string, tree>::const_iterator p =
1232 	    builtin_functions.find(this->asm_name_);
1233 	  if (p != builtin_functions.end())
1234 	    {
1235 	      this->fndecl_ = tree_to_function(p->second);
1236 	      return this->fndecl_;
1237 	    }
1238 	}
1239 
1240       std::string asm_name;
1241       if (this->asm_name_.empty())
1242         {
1243           asm_name = (no->package() == NULL
1244                                   ? gogo->pkgpath_symbol()
1245                                   : no->package()->pkgpath_symbol());
1246           asm_name.append(1, '.');
1247           asm_name.append(Gogo::unpack_hidden_name(no->name()));
1248           if (this->fntype_->is_method())
1249             {
1250               asm_name.append(1, '.');
1251               Type* rtype = this->fntype_->receiver()->type();
1252               asm_name.append(rtype->mangled_name(gogo));
1253             }
1254         }
1255 
1256       Btype* functype = this->fntype_->get_backend_fntype(gogo);
1257       this->fndecl_ =
1258           gogo->backend()->function(functype, no->get_id(gogo), asm_name,
1259                                     true, true, true, false, false,
1260                                     this->location());
1261     }
1262 
1263   return this->fndecl_;
1264 }
1265 
1266 // Return the function's decl after it has been built.
1267 
1268 tree
get_decl() const1269 Function::get_decl() const
1270 {
1271   go_assert(this->fndecl_ != NULL);
1272   return function_to_tree(this->fndecl_);
1273 }
1274 
1275 // We always pass the receiver to a method as a pointer.  If the
1276 // receiver is actually declared as a non-pointer type, then we copy
1277 // the value into a local variable, so that it has the right type.  In
1278 // this function we create the real PARM_DECL to use, and set
1279 // DEC_INITIAL of the var_decl to be the value passed in.
1280 
1281 tree
make_receiver_parm_decl(Gogo * gogo,Named_object * no,tree var_decl)1282 Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl)
1283 {
1284   if (var_decl == error_mark_node)
1285     return error_mark_node;
1286   go_assert(TREE_CODE(var_decl) == VAR_DECL);
1287   tree val_type = TREE_TYPE(var_decl);
1288   bool is_in_heap = no->var_value()->is_in_heap();
1289   if (is_in_heap)
1290     {
1291       go_assert(POINTER_TYPE_P(val_type));
1292       val_type = TREE_TYPE(val_type);
1293     }
1294 
1295   source_location loc = DECL_SOURCE_LOCATION(var_decl);
1296   std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1297   name += ".pointer";
1298   tree id = get_identifier_from_string(name);
1299   tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type));
1300   DECL_CONTEXT(parm_decl) = current_function_decl;
1301   DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl);
1302 
1303   go_assert(DECL_INITIAL(var_decl) == NULL_TREE);
1304   tree init = build_fold_indirect_ref_loc(loc, parm_decl);
1305 
1306   if (is_in_heap)
1307     {
1308       tree size = TYPE_SIZE_UNIT(val_type);
1309       tree space = gogo->allocate_memory(no->var_value()->type(), size,
1310 					 no->location());
1311       space = save_expr(space);
1312       space = fold_convert(build_pointer_type(val_type), space);
1313       tree spaceref = build_fold_indirect_ref_loc(no->location().gcc_location(),
1314                                                   space);
1315       TREE_THIS_NOTRAP(spaceref) = 1;
1316       tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node,
1317 				 spaceref, init);
1318       init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), set, space);
1319     }
1320 
1321   DECL_INITIAL(var_decl) = init;
1322 
1323   return parm_decl;
1324 }
1325 
1326 // If we take the address of a parameter, then we need to copy it into
1327 // the heap.  We will access it as a local variable via an
1328 // indirection.
1329 
1330 tree
copy_parm_to_heap(Gogo * gogo,Named_object * no,tree var_decl)1331 Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree var_decl)
1332 {
1333   if (var_decl == error_mark_node)
1334     return error_mark_node;
1335   go_assert(TREE_CODE(var_decl) == VAR_DECL);
1336   Location loc(DECL_SOURCE_LOCATION(var_decl));
1337 
1338   std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1339   name += ".param";
1340   tree id = get_identifier_from_string(name);
1341 
1342   tree type = TREE_TYPE(var_decl);
1343   go_assert(POINTER_TYPE_P(type));
1344   type = TREE_TYPE(type);
1345 
1346   tree parm_decl = build_decl(loc.gcc_location(), PARM_DECL, id, type);
1347   DECL_CONTEXT(parm_decl) = current_function_decl;
1348   DECL_ARG_TYPE(parm_decl) = type;
1349 
1350   tree size = TYPE_SIZE_UNIT(type);
1351   tree space = gogo->allocate_memory(no->var_value()->type(), size, loc);
1352   space = save_expr(space);
1353   space = fold_convert(TREE_TYPE(var_decl), space);
1354   tree spaceref = build_fold_indirect_ref_loc(loc.gcc_location(), space);
1355   TREE_THIS_NOTRAP(spaceref) = 1;
1356   tree init = build2(COMPOUND_EXPR, TREE_TYPE(space),
1357 		     build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl),
1358 		     space);
1359   DECL_INITIAL(var_decl) = init;
1360 
1361   return parm_decl;
1362 }
1363 
1364 // Get a tree for function code.
1365 
1366 void
build_tree(Gogo * gogo,Named_object * named_function)1367 Function::build_tree(Gogo* gogo, Named_object* named_function)
1368 {
1369   tree fndecl = this->get_decl();
1370   go_assert(fndecl != NULL_TREE);
1371 
1372   tree params = NULL_TREE;
1373   tree* pp = &params;
1374 
1375   tree declare_vars = NULL_TREE;
1376   for (Bindings::const_definitions_iterator p =
1377 	 this->block_->bindings()->begin_definitions();
1378        p != this->block_->bindings()->end_definitions();
1379        ++p)
1380     {
1381       if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
1382 	{
1383 	  Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
1384 	  *pp = var_to_tree(bvar);
1385 
1386 	  // We always pass the receiver to a method as a pointer.  If
1387 	  // the receiver is declared as a non-pointer type, then we
1388 	  // copy the value into a local variable.
1389 	  if ((*p)->var_value()->is_receiver()
1390 	      && (*p)->var_value()->type()->points_to() == NULL)
1391 	    {
1392 	      tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp);
1393 	      tree var = *pp;
1394 	      if (var != error_mark_node)
1395 		{
1396 		  go_assert(TREE_CODE(var) == VAR_DECL);
1397 		  DECL_CHAIN(var) = declare_vars;
1398 		  declare_vars = var;
1399 		}
1400 	      *pp = parm_decl;
1401 	    }
1402 	  else if ((*p)->var_value()->is_in_heap())
1403 	    {
1404 	      // If we take the address of a parameter, then we need
1405 	      // to copy it into the heap.
1406 	      tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp);
1407 	      tree var = *pp;
1408 	      if (var != error_mark_node)
1409 		{
1410 		  go_assert(TREE_CODE(var) == VAR_DECL);
1411 		  DECL_CHAIN(var) = declare_vars;
1412 		  declare_vars = var;
1413 		}
1414 	      *pp = parm_decl;
1415 	    }
1416 
1417 	  if (*pp != error_mark_node)
1418 	    {
1419 	      go_assert(TREE_CODE(*pp) == PARM_DECL);
1420 	      pp = &DECL_CHAIN(*pp);
1421 	    }
1422 	}
1423       else if ((*p)->is_result_variable())
1424 	{
1425 	  Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
1426 	  tree var_decl = var_to_tree(bvar);
1427 
1428 	  Type* type = (*p)->result_var_value()->type();
1429 	  tree init;
1430 	  if (!(*p)->result_var_value()->is_in_heap())
1431 	    {
1432 	      Btype* btype = type->get_backend(gogo);
1433 	      init = expr_to_tree(gogo->backend()->zero_expression(btype));
1434 	    }
1435 	  else
1436 	    {
1437 	      Location loc = (*p)->location();
1438 	      tree type_tree = type_to_tree(type->get_backend(gogo));
1439 	      tree space = gogo->allocate_memory(type,
1440 						 TYPE_SIZE_UNIT(type_tree),
1441 						 loc);
1442 	      tree ptr_type_tree = build_pointer_type(type_tree);
1443 	      init = fold_convert_loc(loc.gcc_location(), ptr_type_tree, space);
1444 	    }
1445 
1446 	  if (var_decl != error_mark_node)
1447 	    {
1448 	      go_assert(TREE_CODE(var_decl) == VAR_DECL);
1449 	      DECL_INITIAL(var_decl) = init;
1450 	      DECL_CHAIN(var_decl) = declare_vars;
1451 	      declare_vars = var_decl;
1452 	    }
1453 	}
1454     }
1455 
1456   *pp = NULL_TREE;
1457 
1458   DECL_ARGUMENTS(fndecl) = params;
1459 
1460   // If we need a closure variable, fetch it by calling a runtime
1461   // function.  The caller will have called __go_set_closure before
1462   // the function call.
1463   if (this->closure_var_ != NULL)
1464     {
1465       Bvariable* bvar =
1466 	this->closure_var_->get_backend_variable(gogo, named_function);
1467       tree var_decl = var_to_tree(bvar);
1468       if (var_decl != error_mark_node)
1469 	{
1470 	  go_assert(TREE_CODE(var_decl) == VAR_DECL);
1471 	  static tree get_closure_fndecl;
1472 	  tree get_closure = Gogo::call_builtin(&get_closure_fndecl,
1473 						this->location_,
1474 						"__go_get_closure",
1475 						0,
1476 						ptr_type_node);
1477 
1478 	  // Mark the __go_get_closure function as pure, since it
1479 	  // depends only on the global variable g.
1480 	  DECL_PURE_P(get_closure_fndecl) = 1;
1481 
1482 	  get_closure = fold_convert_loc(this->location_.gcc_location(),
1483 					 TREE_TYPE(var_decl), get_closure);
1484 	  DECL_INITIAL(var_decl) = get_closure;
1485 	  DECL_CHAIN(var_decl) = declare_vars;
1486 	  declare_vars = var_decl;
1487 	}
1488     }
1489 
1490   if (this->block_ != NULL)
1491     {
1492       go_assert(DECL_INITIAL(fndecl) == NULL_TREE);
1493 
1494       // Declare variables if necessary.
1495       tree bind = NULL_TREE;
1496       tree defer_init = NULL_TREE;
1497       if (declare_vars != NULL_TREE || this->defer_stack_ != NULL)
1498 	{
1499 	  tree block = make_node(BLOCK);
1500 	  BLOCK_SUPERCONTEXT(block) = fndecl;
1501 	  DECL_INITIAL(fndecl) = block;
1502 	  BLOCK_VARS(block) = declare_vars;
1503 	  TREE_USED(block) = 1;
1504 
1505 	  bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block),
1506 			NULL_TREE, block);
1507 	  TREE_SIDE_EFFECTS(bind) = 1;
1508 
1509 	  if (this->defer_stack_ != NULL)
1510 	    {
1511 	      Translate_context dcontext(gogo, named_function, this->block_,
1512 					 tree_to_block(bind));
1513 	      Bstatement* bdi = this->defer_stack_->get_backend(&dcontext);
1514 	      defer_init = stat_to_tree(bdi);
1515 	    }
1516 	}
1517 
1518       // Build the trees for all the statements in the function.
1519       Translate_context context(gogo, named_function, NULL, NULL);
1520       Bblock* bblock = this->block_->get_backend(&context);
1521       tree code = block_to_tree(bblock);
1522 
1523       tree init = NULL_TREE;
1524       tree except = NULL_TREE;
1525       tree fini = NULL_TREE;
1526 
1527       // Initialize variables if necessary.
1528       for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v))
1529 	{
1530 	  tree dv = build1(DECL_EXPR, void_type_node, v);
1531 	  SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v));
1532 	  append_to_statement_list(dv, &init);
1533 	}
1534 
1535       // If we have a defer stack, initialize it at the start of a
1536       // function.
1537       if (defer_init != NULL_TREE && defer_init != error_mark_node)
1538 	{
1539 	  SET_EXPR_LOCATION(defer_init,
1540                             this->block_->start_location().gcc_location());
1541 	  append_to_statement_list(defer_init, &init);
1542 
1543 	  // Clean up the defer stack when we leave the function.
1544 	  this->build_defer_wrapper(gogo, named_function, &except, &fini);
1545 	}
1546 
1547       if (code != NULL_TREE && code != error_mark_node)
1548 	{
1549 	  if (init != NULL_TREE)
1550 	    code = build2(COMPOUND_EXPR, void_type_node, init, code);
1551 	  if (except != NULL_TREE)
1552 	    code = build2(TRY_CATCH_EXPR, void_type_node, code,
1553 			  build2(CATCH_EXPR, void_type_node, NULL, except));
1554 	  if (fini != NULL_TREE)
1555 	    code = build2(TRY_FINALLY_EXPR, void_type_node, code, fini);
1556 	}
1557 
1558       // Stick the code into the block we built for the receiver, if
1559       // we built on.
1560       if (bind != NULL_TREE && code != NULL_TREE && code != error_mark_node)
1561 	{
1562 	  BIND_EXPR_BODY(bind) = code;
1563 	  code = bind;
1564 	}
1565 
1566       DECL_SAVED_TREE(fndecl) = code;
1567     }
1568 
1569   // If we created a descriptor for the function, make sure we emit it.
1570   if (this->descriptor_ != NULL)
1571     {
1572       Translate_context context(gogo, NULL, NULL, NULL);
1573       this->descriptor_->get_tree(&context);
1574     }
1575 }
1576 
1577 // Build the wrappers around function code needed if the function has
1578 // any defer statements.  This sets *EXCEPT to an exception handler
1579 // and *FINI to a finally handler.
1580 
1581 void
build_defer_wrapper(Gogo * gogo,Named_object * named_function,tree * except,tree * fini)1582 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
1583 			      tree *except, tree *fini)
1584 {
1585   Location end_loc = this->block_->end_location();
1586 
1587   // Add an exception handler.  This is used if a panic occurs.  Its
1588   // purpose is to stop the stack unwinding if a deferred function
1589   // calls recover.  There are more details in
1590   // libgo/runtime/go-unwind.c.
1591 
1592   tree stmt_list = NULL_TREE;
1593 
1594   Expression* call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
1595 					this->defer_stack(end_loc));
1596   Translate_context context(gogo, named_function, NULL, NULL);
1597   tree call_tree = call->get_tree(&context);
1598   if (call_tree != error_mark_node)
1599     append_to_statement_list(call_tree, &stmt_list);
1600 
1601   tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list);
1602   tree set;
1603   if (retval == NULL_TREE)
1604     set = NULL_TREE;
1605   else
1606     set = fold_build2_loc(end_loc.gcc_location(), MODIFY_EXPR, void_type_node,
1607 			  DECL_RESULT(this->get_decl()), retval);
1608   tree ret_stmt = fold_build1_loc(end_loc.gcc_location(), RETURN_EXPR,
1609                                   void_type_node, set);
1610   append_to_statement_list(ret_stmt, &stmt_list);
1611 
1612   go_assert(*except == NULL_TREE);
1613   *except = stmt_list;
1614 
1615   // Add some finally code to run the defer functions.  This is used
1616   // both in the normal case, when no panic occurs, and also if a
1617   // panic occurs to run any further defer functions.  Of course, it
1618   // is possible for a defer function to call panic which should be
1619   // caught by another defer function.  To handle that we use a loop.
1620   //  finish:
1621   //   try { __go_undefer(); } catch { __go_check_defer(); goto finish; }
1622   //   if (return values are named) return named_vals;
1623 
1624   stmt_list = NULL;
1625 
1626   tree label = create_artificial_label(end_loc.gcc_location());
1627   tree define_label = fold_build1_loc(end_loc.gcc_location(), LABEL_EXPR,
1628                                       void_type_node, label);
1629   append_to_statement_list(define_label, &stmt_list);
1630 
1631   call = Runtime::make_call(Runtime::UNDEFER, end_loc, 1,
1632 			    this->defer_stack(end_loc));
1633   tree undefer = call->get_tree(&context);
1634 
1635   call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
1636 			    this->defer_stack(end_loc));
1637   tree defer = call->get_tree(&context);
1638 
1639   if (undefer == error_mark_node || defer == error_mark_node)
1640     return;
1641 
1642   tree jump = fold_build1_loc(end_loc.gcc_location(), GOTO_EXPR, void_type_node,
1643                               label);
1644   tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump);
1645   catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body);
1646   tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body);
1647 
1648   append_to_statement_list(try_catch, &stmt_list);
1649 
1650   if (this->type_->results() != NULL
1651       && !this->type_->results()->empty()
1652       && !this->type_->results()->front().name().empty())
1653     {
1654       // If the result variables are named, and we are returning from
1655       // this function rather than panicing through it, we need to
1656       // return them again, because they might have been changed by a
1657       // defer function.  The runtime routines set the defer_stack
1658       // variable to true if we are returning from this function.
1659       retval = this->return_value(gogo, named_function, end_loc,
1660 				  &stmt_list);
1661       set = fold_build2_loc(end_loc.gcc_location(), MODIFY_EXPR, void_type_node,
1662 			    DECL_RESULT(this->get_decl()), retval);
1663       ret_stmt = fold_build1_loc(end_loc.gcc_location(), RETURN_EXPR,
1664                                  void_type_node, set);
1665 
1666       Expression* ref =
1667 	Expression::make_temporary_reference(this->defer_stack_, end_loc);
1668       tree tref = ref->get_tree(&context);
1669       tree s = build3_loc(end_loc.gcc_location(), COND_EXPR, void_type_node,
1670                           tref, ret_stmt, NULL_TREE);
1671 
1672       append_to_statement_list(s, &stmt_list);
1673 
1674     }
1675 
1676   go_assert(*fini == NULL_TREE);
1677   *fini = stmt_list;
1678 }
1679 
1680 // Return the value to assign to DECL_RESULT(this->get_decl()).  This may
1681 // also add statements to STMT_LIST, which need to be executed before
1682 // the assignment.  This is used for a return statement with no
1683 // explicit values.
1684 
1685 tree
return_value(Gogo * gogo,Named_object * named_function,Location location,tree * stmt_list) const1686 Function::return_value(Gogo* gogo, Named_object* named_function,
1687 		       Location location, tree* stmt_list) const
1688 {
1689   const Typed_identifier_list* results = this->type_->results();
1690   if (results == NULL || results->empty())
1691     return NULL_TREE;
1692 
1693   go_assert(this->results_ != NULL);
1694   if (this->results_->size() != results->size())
1695     {
1696       go_assert(saw_errors());
1697       return error_mark_node;
1698     }
1699 
1700   tree retval;
1701   if (results->size() == 1)
1702     {
1703       Bvariable* bvar =
1704 	this->results_->front()->get_backend_variable(gogo,
1705 						      named_function);
1706       tree ret = var_to_tree(bvar);
1707       if (this->results_->front()->result_var_value()->is_in_heap())
1708 	ret = build_fold_indirect_ref_loc(location.gcc_location(), ret);
1709       return ret;
1710     }
1711   else
1712     {
1713       tree rettype = TREE_TYPE(DECL_RESULT(this->get_decl()));
1714       retval = create_tmp_var(rettype, "RESULT");
1715       tree field = TYPE_FIELDS(rettype);
1716       int index = 0;
1717       for (Typed_identifier_list::const_iterator pr = results->begin();
1718 	   pr != results->end();
1719 	   ++pr, ++index, field = DECL_CHAIN(field))
1720 	{
1721 	  go_assert(field != NULL);
1722 	  Named_object* no = (*this->results_)[index];
1723 	  Bvariable* bvar = no->get_backend_variable(gogo, named_function);
1724 	  tree val = var_to_tree(bvar);
1725 	  if (no->result_var_value()->is_in_heap())
1726 	    val = build_fold_indirect_ref_loc(location.gcc_location(), val);
1727 	  tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
1728                                      void_type_node,
1729 				     build3(COMPONENT_REF, TREE_TYPE(field),
1730 					    retval, field, NULL_TREE),
1731 				     val);
1732 	  append_to_statement_list(set, stmt_list);
1733 	}
1734       return retval;
1735     }
1736 }
1737 
1738 // Build the descriptor for a function declaration.  This won't
1739 // necessarily happen if the package has just a declaration for the
1740 // function and no other reference to it, but we may still need the
1741 // descriptor for references from other packages.
1742 void
build_backend_descriptor(Gogo * gogo)1743 Function_declaration::build_backend_descriptor(Gogo* gogo)
1744 {
1745   if (this->descriptor_ != NULL)
1746     {
1747       Translate_context context(gogo, NULL, NULL, NULL);
1748       this->descriptor_->get_tree(&context);
1749     }
1750 }
1751 
1752 // Return the integer type to use for a size.
1753 
1754 GO_EXTERN_C
1755 tree
go_type_for_size(unsigned int bits,int unsignedp)1756 go_type_for_size(unsigned int bits, int unsignedp)
1757 {
1758   const char* name;
1759   switch (bits)
1760     {
1761     case 8:
1762       name = unsignedp ? "uint8" : "int8";
1763       break;
1764     case 16:
1765       name = unsignedp ? "uint16" : "int16";
1766       break;
1767     case 32:
1768       name = unsignedp ? "uint32" : "int32";
1769       break;
1770     case 64:
1771       name = unsignedp ? "uint64" : "int64";
1772       break;
1773     default:
1774       if (bits == POINTER_SIZE && unsignedp)
1775 	name = "uintptr";
1776       else
1777 	return NULL_TREE;
1778     }
1779   Type* type = Type::lookup_integer_type(name);
1780   return type_to_tree(type->get_backend(go_get_gogo()));
1781 }
1782 
1783 // Return the type to use for a mode.
1784 
1785 GO_EXTERN_C
1786 tree
go_type_for_mode(enum machine_mode mode,int unsignedp)1787 go_type_for_mode(enum machine_mode mode, int unsignedp)
1788 {
1789   // FIXME: This static_cast should be in machmode.h.
1790   enum mode_class mc = static_cast<enum mode_class>(GET_MODE_CLASS(mode));
1791   if (mc == MODE_INT)
1792     return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp);
1793   else if (mc == MODE_FLOAT)
1794     {
1795       Type* type;
1796       switch (GET_MODE_BITSIZE (mode))
1797 	{
1798 	case 32:
1799 	  type = Type::lookup_float_type("float32");
1800 	  break;
1801 	case 64:
1802 	  type = Type::lookup_float_type("float64");
1803 	  break;
1804 	default:
1805 	  // We have to check for long double in order to support
1806 	  // i386 excess precision.
1807 	  if (mode == TYPE_MODE(long_double_type_node))
1808 	    return long_double_type_node;
1809 	  return NULL_TREE;
1810 	}
1811       return type_to_tree(type->get_backend(go_get_gogo()));
1812     }
1813   else if (mc == MODE_COMPLEX_FLOAT)
1814     {
1815       Type *type;
1816       switch (GET_MODE_BITSIZE (mode))
1817 	{
1818 	case 64:
1819 	  type = Type::lookup_complex_type("complex64");
1820 	  break;
1821 	case 128:
1822 	  type = Type::lookup_complex_type("complex128");
1823 	  break;
1824 	default:
1825 	  // We have to check for long double in order to support
1826 	  // i386 excess precision.
1827 	  if (mode == TYPE_MODE(complex_long_double_type_node))
1828 	    return complex_long_double_type_node;
1829 	  return NULL_TREE;
1830 	}
1831       return type_to_tree(type->get_backend(go_get_gogo()));
1832     }
1833   else
1834     return NULL_TREE;
1835 }
1836 
1837 // Return a tree which allocates SIZE bytes which will holds value of
1838 // type TYPE.
1839 
1840 tree
allocate_memory(Type * type,tree size,Location location)1841 Gogo::allocate_memory(Type* type, tree size, Location location)
1842 {
1843   // If the package imports unsafe, then it may play games with
1844   // pointers that look like integers.
1845   if (this->imported_unsafe_ || type->has_pointer())
1846     {
1847       static tree new_fndecl;
1848       return Gogo::call_builtin(&new_fndecl,
1849 				location,
1850 				"__go_new",
1851 				1,
1852 				ptr_type_node,
1853 				sizetype,
1854 				size);
1855     }
1856   else
1857     {
1858       static tree new_nopointers_fndecl;
1859       return Gogo::call_builtin(&new_nopointers_fndecl,
1860 				location,
1861 				"__go_new_nopointers",
1862 				1,
1863 				ptr_type_node,
1864 				sizetype,
1865 				size);
1866     }
1867 }
1868 
1869 // Build a builtin struct with a list of fields.  The name is
1870 // STRUCT_NAME.  STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE
1871 // node; this exists so that the struct can have fields which point to
1872 // itself.  If PTYPE is not NULL, store the result in *PTYPE.  There
1873 // are NFIELDS fields.  Each field is a name (a const char*) followed
1874 // by a type (a tree).
1875 
1876 tree
builtin_struct(tree * ptype,const char * struct_name,tree struct_type,int nfields,...)1877 Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type,
1878 		     int nfields, ...)
1879 {
1880   if (ptype != NULL && *ptype != NULL_TREE)
1881     return *ptype;
1882 
1883   va_list ap;
1884   va_start(ap, nfields);
1885 
1886   tree fields = NULL_TREE;
1887   for (int i = 0; i < nfields; ++i)
1888     {
1889       const char* field_name = va_arg(ap, const char*);
1890       tree type = va_arg(ap, tree);
1891       if (type == error_mark_node)
1892 	{
1893 	  if (ptype != NULL)
1894 	    *ptype = error_mark_node;
1895 	  return error_mark_node;
1896 	}
1897       tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL,
1898 			      get_identifier(field_name), type);
1899       DECL_CHAIN(field) = fields;
1900       fields = field;
1901     }
1902 
1903   va_end(ap);
1904 
1905   if (struct_type == NULL_TREE)
1906     struct_type = make_node(RECORD_TYPE);
1907   finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE);
1908 
1909   if (ptype != NULL)
1910     {
1911       go_preserve_from_gc(struct_type);
1912       *ptype = struct_type;
1913     }
1914 
1915   return struct_type;
1916 }
1917 
1918 // Return a type to use for pointer to const char for a string.
1919 
1920 tree
const_char_pointer_type_tree()1921 Gogo::const_char_pointer_type_tree()
1922 {
1923   static tree type;
1924   if (type == NULL_TREE)
1925     {
1926       tree const_char_type = build_qualified_type(unsigned_char_type_node,
1927 						  TYPE_QUAL_CONST);
1928       type = build_pointer_type(const_char_type);
1929       go_preserve_from_gc(type);
1930     }
1931   return type;
1932 }
1933 
1934 // Return a tree for a string constant.
1935 
1936 tree
string_constant_tree(const std::string & val)1937 Gogo::string_constant_tree(const std::string& val)
1938 {
1939   tree index_type = build_index_type(size_int(val.length()));
1940   tree const_char_type = build_qualified_type(unsigned_char_type_node,
1941 					      TYPE_QUAL_CONST);
1942   tree string_type = build_array_type(const_char_type, index_type);
1943   string_type = build_variant_type_copy(string_type);
1944   TYPE_STRING_FLAG(string_type) = 1;
1945   tree string_val = build_string(val.length(), val.data());
1946   TREE_TYPE(string_val) = string_type;
1947   return string_val;
1948 }
1949 
1950 // Return a tree for a Go string constant.
1951 
1952 tree
go_string_constant_tree(const std::string & val)1953 Gogo::go_string_constant_tree(const std::string& val)
1954 {
1955   tree string_type = type_to_tree(Type::make_string_type()->get_backend(this));
1956 
1957   vec<constructor_elt, va_gc> *init;
1958   vec_alloc(init, 2);
1959 
1960   constructor_elt empty = {NULL, NULL};
1961   constructor_elt* elt = init->quick_push(empty);
1962   tree field = TYPE_FIELDS(string_type);
1963   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0);
1964   elt->index = field;
1965   tree str = Gogo::string_constant_tree(val);
1966   elt->value = fold_convert(TREE_TYPE(field),
1967 			    build_fold_addr_expr(str));
1968 
1969   elt = init->quick_push(empty);
1970   field = DECL_CHAIN(field);
1971   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0);
1972   elt->index = field;
1973   elt->value = build_int_cst_type(TREE_TYPE(field), val.length());
1974 
1975   tree constructor = build_constructor(string_type, init);
1976   TREE_READONLY(constructor) = 1;
1977   TREE_CONSTANT(constructor) = 1;
1978 
1979   return constructor;
1980 }
1981 
1982 // Return a tree for a pointer to a Go string constant.  This is only
1983 // used for type descriptors, so we return a pointer to a constant
1984 // decl.
1985 
1986 tree
ptr_go_string_constant_tree(const std::string & val)1987 Gogo::ptr_go_string_constant_tree(const std::string& val)
1988 {
1989   tree pval = this->go_string_constant_tree(val);
1990 
1991   tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL,
1992 			 create_tmp_var_name("SP"), TREE_TYPE(pval));
1993   DECL_EXTERNAL(decl) = 0;
1994   TREE_PUBLIC(decl) = 0;
1995   TREE_USED(decl) = 1;
1996   TREE_READONLY(decl) = 1;
1997   TREE_CONSTANT(decl) = 1;
1998   TREE_STATIC(decl) = 1;
1999   DECL_ARTIFICIAL(decl) = 1;
2000   DECL_INITIAL(decl) = pval;
2001   rest_of_decl_compilation(decl, 1, 0);
2002 
2003   return build_fold_addr_expr(decl);
2004 }
2005 
2006 // Build a constructor for a slice.  SLICE_TYPE_TREE is the type of
2007 // the slice.  VALUES is the value pointer and COUNT is the number of
2008 // entries.  If CAPACITY is not NULL, it is the capacity; otherwise
2009 // the capacity and the count are the same.
2010 
2011 tree
slice_constructor(tree slice_type_tree,tree values,tree count,tree capacity)2012 Gogo::slice_constructor(tree slice_type_tree, tree values, tree count,
2013 			tree capacity)
2014 {
2015   go_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE);
2016 
2017   vec<constructor_elt, va_gc> *init;
2018   vec_alloc(init, 3);
2019 
2020   tree field = TYPE_FIELDS(slice_type_tree);
2021   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
2022   constructor_elt empty = {NULL, NULL};
2023   constructor_elt* elt = init->quick_push(empty);
2024   elt->index = field;
2025   go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field))
2026 	     == TYPE_MAIN_VARIANT(TREE_TYPE(values)));
2027   elt->value = values;
2028 
2029   count = fold_convert(sizetype, count);
2030   if (capacity == NULL_TREE)
2031     {
2032       count = save_expr(count);
2033       capacity = count;
2034     }
2035 
2036   field = DECL_CHAIN(field);
2037   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
2038   elt = init->quick_push(empty);
2039   elt->index = field;
2040   elt->value = fold_convert(TREE_TYPE(field), count);
2041 
2042   field = DECL_CHAIN(field);
2043   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
2044   elt = init->quick_push(empty);
2045   elt->index = field;
2046   elt->value = fold_convert(TREE_TYPE(field), capacity);
2047 
2048   return build_constructor(slice_type_tree, init);
2049 }
2050 
2051 // Build an interface method table for a type: a list of function
2052 // pointers, one for each interface method.  This is used for
2053 // interfaces.
2054 
2055 tree
interface_method_table_for_type(const Interface_type * interface,Type * type,bool is_pointer)2056 Gogo::interface_method_table_for_type(const Interface_type* interface,
2057 				      Type* type, bool is_pointer)
2058 {
2059   const Typed_identifier_list* interface_methods = interface->methods();
2060   go_assert(!interface_methods->empty());
2061 
2062   std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_")
2063 			      + interface->mangled_name(this)
2064 			      + "__"
2065 			      + type->mangled_name(this));
2066 
2067   tree id = get_identifier_from_string(mangled_name);
2068 
2069   // See whether this interface has any hidden methods.
2070   bool has_hidden_methods = false;
2071   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2072        p != interface_methods->end();
2073        ++p)
2074     {
2075       if (Gogo::is_hidden_name(p->name()))
2076 	{
2077 	  has_hidden_methods = true;
2078 	  break;
2079 	}
2080     }
2081 
2082   // We already know that the named type is convertible to the
2083   // interface.  If the interface has hidden methods, and the named
2084   // type is defined in a different package, then the interface
2085   // conversion table will be defined by that other package.
2086   if (has_hidden_methods
2087       && type->named_type() != NULL
2088       && type->named_type()->named_object()->package() != NULL)
2089     {
2090       tree array_type = build_array_type(const_ptr_type_node, NULL);
2091       tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2092       TREE_READONLY(decl) = 1;
2093       TREE_CONSTANT(decl) = 1;
2094       TREE_PUBLIC(decl) = 1;
2095       DECL_EXTERNAL(decl) = 1;
2096       go_preserve_from_gc(decl);
2097       return decl;
2098     }
2099 
2100   size_t count = interface_methods->size();
2101   vec<constructor_elt, va_gc> *pointers;
2102   vec_alloc(pointers, count + 1);
2103 
2104   // The first element is the type descriptor.
2105   constructor_elt empty = {NULL, NULL};
2106   constructor_elt* elt = pointers->quick_push(empty);
2107   elt->index = size_zero_node;
2108   Type* td_type;
2109   if (!is_pointer)
2110     td_type = type;
2111   else
2112     td_type = Type::make_pointer_type(type);
2113 
2114   Location loc = Linemap::predeclared_location();
2115   Bexpression* tdp_bexpr = td_type->type_descriptor_pointer(this, loc);
2116   tree tdp = expr_to_tree(tdp_bexpr);
2117   elt->value = fold_convert(const_ptr_type_node, tdp);
2118 
2119   Named_type* nt = type->named_type();
2120   Struct_type* st = type->struct_type();
2121   go_assert(nt != NULL || st != NULL);
2122   size_t i = 1;
2123   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2124        p != interface_methods->end();
2125        ++p, ++i)
2126     {
2127       bool is_ambiguous;
2128       Method* m;
2129       if (nt != NULL)
2130 	m = nt->method_function(p->name(), &is_ambiguous);
2131       else
2132 	m = st->method_function(p->name(), &is_ambiguous);
2133       go_assert(m != NULL);
2134 
2135       Named_object* no = m->named_object();
2136       Bfunction* bf;
2137       if (no->is_function())
2138 	bf = no->func_value()->get_or_make_decl(this, no);
2139       else if (no->is_function_declaration())
2140 	bf = no->func_declaration_value()->get_or_make_decl(this, no);
2141       else
2142 	go_unreachable();
2143       tree fndecl = build_fold_addr_expr(function_to_tree(bf));
2144 
2145       elt = pointers->quick_push(empty);
2146       elt->index = size_int(i);
2147       elt->value = fold_convert(const_ptr_type_node, fndecl);
2148     }
2149   go_assert(i == count + 1);
2150 
2151   tree array_type = build_array_type(const_ptr_type_node,
2152 				     build_index_type(size_int(count)));
2153   tree constructor = build_constructor(array_type, pointers);
2154 
2155   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2156   TREE_STATIC(decl) = 1;
2157   TREE_USED(decl) = 1;
2158   TREE_READONLY(decl) = 1;
2159   TREE_CONSTANT(decl) = 1;
2160   DECL_INITIAL(decl) = constructor;
2161 
2162   // If the interface type has hidden methods, and the table is for a
2163   // named type, then this is the only definition of the table.
2164   // Otherwise it is a comdat table which may be defined in multiple
2165   // packages.
2166   if (has_hidden_methods && type->named_type() != NULL)
2167     TREE_PUBLIC(decl) = 1;
2168   else
2169     {
2170       make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2171       resolve_unique_section(decl, 1, 0);
2172     }
2173 
2174   rest_of_decl_compilation(decl, 1, 0);
2175 
2176   go_preserve_from_gc(decl);
2177 
2178   return decl;
2179 }
2180 
2181 // Mark a function as a builtin library function.
2182 
2183 void
mark_fndecl_as_builtin_library(tree fndecl)2184 Gogo::mark_fndecl_as_builtin_library(tree fndecl)
2185 {
2186   DECL_EXTERNAL(fndecl) = 1;
2187   TREE_PUBLIC(fndecl) = 1;
2188   DECL_ARTIFICIAL(fndecl) = 1;
2189   TREE_NOTHROW(fndecl) = 1;
2190   DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT;
2191   DECL_VISIBILITY_SPECIFIED(fndecl) = 1;
2192 }
2193 
2194 // Build a call to a builtin function.
2195 
2196 tree
call_builtin(tree * pdecl,Location location,const char * name,int nargs,tree rettype,...)2197 Gogo::call_builtin(tree* pdecl, Location location, const char* name,
2198 		   int nargs, tree rettype, ...)
2199 {
2200   if (rettype == error_mark_node)
2201     return error_mark_node;
2202 
2203   tree* types = new tree[nargs];
2204   tree* args = new tree[nargs];
2205 
2206   va_list ap;
2207   va_start(ap, rettype);
2208   for (int i = 0; i < nargs; ++i)
2209     {
2210       types[i] = va_arg(ap, tree);
2211       args[i] = va_arg(ap, tree);
2212       if (types[i] == error_mark_node || args[i] == error_mark_node)
2213 	{
2214 	  delete[] types;
2215 	  delete[] args;
2216 	  return error_mark_node;
2217 	}
2218     }
2219   va_end(ap);
2220 
2221   if (*pdecl == NULL_TREE)
2222     {
2223       tree fnid = get_identifier(name);
2224 
2225       tree argtypes = NULL_TREE;
2226       tree* pp = &argtypes;
2227       for (int i = 0; i < nargs; ++i)
2228 	{
2229 	  *pp = tree_cons(NULL_TREE, types[i], NULL_TREE);
2230 	  pp = &TREE_CHAIN(*pp);
2231 	}
2232       *pp = void_list_node;
2233 
2234       tree fntype = build_function_type(rettype, argtypes);
2235 
2236       *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype);
2237       Gogo::mark_fndecl_as_builtin_library(*pdecl);
2238       go_preserve_from_gc(*pdecl);
2239     }
2240 
2241   tree fnptr = build_fold_addr_expr(*pdecl);
2242   if (CAN_HAVE_LOCATION_P(fnptr))
2243     SET_EXPR_LOCATION(fnptr, location.gcc_location());
2244 
2245   tree ret = build_call_array(rettype, fnptr, nargs, args);
2246   SET_EXPR_LOCATION(ret, location.gcc_location());
2247 
2248   delete[] types;
2249   delete[] args;
2250 
2251   return ret;
2252 }
2253 
2254 // Return a tree for receiving a value of type TYPE_TREE on CHANNEL.
2255 // TYPE_DESCRIPTOR_TREE is the channel's type descriptor.  This does a
2256 // blocking receive and returns the value read from the channel.
2257 
2258 tree
receive_from_channel(tree type_tree,tree type_descriptor_tree,tree channel,Location location)2259 Gogo::receive_from_channel(tree type_tree, tree type_descriptor_tree,
2260 			   tree channel, Location location)
2261 {
2262   if (type_tree == error_mark_node || channel == error_mark_node)
2263     return error_mark_node;
2264 
2265   if (int_size_in_bytes(type_tree) <= 8
2266       && !AGGREGATE_TYPE_P(type_tree)
2267       && !FLOAT_TYPE_P(type_tree))
2268     {
2269       static tree receive_small_fndecl;
2270       tree call = Gogo::call_builtin(&receive_small_fndecl,
2271 				     location,
2272 				     "__go_receive_small",
2273 				     2,
2274 				     uint64_type_node,
2275 				     TREE_TYPE(type_descriptor_tree),
2276 				     type_descriptor_tree,
2277 				     ptr_type_node,
2278 				     channel);
2279       if (call == error_mark_node)
2280 	return error_mark_node;
2281       // This can panic if there are too many operations on a closed
2282       // channel.
2283       TREE_NOTHROW(receive_small_fndecl) = 0;
2284       int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree));
2285       tree int_type_tree = go_type_for_size(bitsize, 1);
2286       return fold_convert_loc(location.gcc_location(), type_tree,
2287 			      fold_convert_loc(location.gcc_location(),
2288                                                int_type_tree, call));
2289     }
2290   else
2291     {
2292       tree tmp = create_tmp_var(type_tree, get_name(type_tree));
2293       DECL_IGNORED_P(tmp) = 0;
2294       TREE_ADDRESSABLE(tmp) = 1;
2295       tree make_tmp = build1(DECL_EXPR, void_type_node, tmp);
2296       SET_EXPR_LOCATION(make_tmp, location.gcc_location());
2297       tree tmpaddr = build_fold_addr_expr(tmp);
2298       tmpaddr = fold_convert(ptr_type_node, tmpaddr);
2299       static tree receive_big_fndecl;
2300       tree call = Gogo::call_builtin(&receive_big_fndecl,
2301 				     location,
2302 				     "__go_receive_big",
2303 				     3,
2304 				     void_type_node,
2305 				     TREE_TYPE(type_descriptor_tree),
2306 				     type_descriptor_tree,
2307 				     ptr_type_node,
2308 				     channel,
2309 				     ptr_type_node,
2310 				     tmpaddr);
2311       if (call == error_mark_node)
2312 	return error_mark_node;
2313       // This can panic if there are too many operations on a closed
2314       // channel.
2315       TREE_NOTHROW(receive_big_fndecl) = 0;
2316       return build2(COMPOUND_EXPR, type_tree, make_tmp,
2317 		    build2(COMPOUND_EXPR, type_tree, call, tmp));
2318     }
2319 }
2320