OSDN Git Service

Don't crash on erroneous thunk call.
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / statements.cc
1 // statements.cc -- Go frontend statements.
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 "intl.h"
17 #include "tree.h"
18 #include "gimple.h"
19 #include "convert.h"
20 #include "tree-iterator.h"
21 #include "tree-flow.h"
22 #include "real.h"
23
24 #ifndef ENABLE_BUILD_WITH_CXX
25 }
26 #endif
27
28 #include "go-c.h"
29 #include "types.h"
30 #include "expressions.h"
31 #include "gogo.h"
32 #include "statements.h"
33
34 // Class Statement.
35
36 Statement::Statement(Statement_classification classification,
37                      source_location location)
38   : classification_(classification), location_(location)
39 {
40 }
41
42 Statement::~Statement()
43 {
44 }
45
46 // Traverse the tree.  The work of walking the components is handled
47 // by the subclasses.
48
49 int
50 Statement::traverse(Block* block, size_t* pindex, Traverse* traverse)
51 {
52   if (this->classification_ == STATEMENT_ERROR)
53     return TRAVERSE_CONTINUE;
54
55   unsigned int traverse_mask = traverse->traverse_mask();
56
57   if ((traverse_mask & Traverse::traverse_statements) != 0)
58     {
59       int t = traverse->statement(block, pindex, this);
60       if (t == TRAVERSE_EXIT)
61         return TRAVERSE_EXIT;
62       else if (t == TRAVERSE_SKIP_COMPONENTS)
63         return TRAVERSE_CONTINUE;
64     }
65
66   // No point in checking traverse_mask here--a statement may contain
67   // other blocks or statements, and if we got here we always want to
68   // walk them.
69   return this->do_traverse(traverse);
70 }
71
72 // Traverse the contents of a statement.
73
74 int
75 Statement::traverse_contents(Traverse* traverse)
76 {
77   return this->do_traverse(traverse);
78 }
79
80 // Traverse assignments.
81
82 bool
83 Statement::traverse_assignments(Traverse_assignments* tassign)
84 {
85   if (this->classification_ == STATEMENT_ERROR)
86     return false;
87   return this->do_traverse_assignments(tassign);
88 }
89
90 // Traverse an expression in a statement.  This is a helper function
91 // for child classes.
92
93 int
94 Statement::traverse_expression(Traverse* traverse, Expression** expr)
95 {
96   if ((traverse->traverse_mask()
97        & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0)
98     return TRAVERSE_CONTINUE;
99   return Expression::traverse(expr, traverse);
100 }
101
102 // Traverse an expression list in a statement.  This is a helper
103 // function for child classes.
104
105 int
106 Statement::traverse_expression_list(Traverse* traverse,
107                                     Expression_list* expr_list)
108 {
109   if (expr_list == NULL)
110     return TRAVERSE_CONTINUE;
111   if ((traverse->traverse_mask()
112        & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0)
113     return TRAVERSE_CONTINUE;
114   return expr_list->traverse(traverse);
115 }
116
117 // Traverse a type in a statement.  This is a helper function for
118 // child classes.
119
120 int
121 Statement::traverse_type(Traverse* traverse, Type* type)
122 {
123   if ((traverse->traverse_mask()
124        & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0)
125     return TRAVERSE_CONTINUE;
126   return Type::traverse(type, traverse);
127 }
128
129 // Set type information for unnamed constants.  This is really done by
130 // the child class.
131
132 void
133 Statement::determine_types()
134 {
135   this->do_determine_types();
136 }
137
138 // If this is a thunk statement, return it.
139
140 Thunk_statement*
141 Statement::thunk_statement()
142 {
143   Thunk_statement* ret = this->convert<Thunk_statement, STATEMENT_GO>();
144   if (ret == NULL)
145     ret = this->convert<Thunk_statement, STATEMENT_DEFER>();
146   return ret;
147 }
148
149 // Get a tree for a Statement.  This is really done by the child
150 // class.
151
152 tree
153 Statement::get_tree(Translate_context* context)
154 {
155   if (this->classification_ == STATEMENT_ERROR)
156     return error_mark_node;
157
158   return this->do_get_tree(context);
159 }
160
161 // Build tree nodes and set locations.
162
163 tree
164 Statement::build_stmt_1(int tree_code_value, tree node)
165 {
166   tree ret = build1(static_cast<tree_code>(tree_code_value),
167                     void_type_node, node);
168   SET_EXPR_LOCATION(ret, this->location_);
169   return ret;
170 }
171
172 // Note that this statement is erroneous.  This is called by children
173 // when they discover an error.
174
175 void
176 Statement::set_is_error()
177 {
178   this->classification_ = STATEMENT_ERROR;
179 }
180
181 // For children to call to report an error conveniently.
182
183 void
184 Statement::report_error(const char* msg)
185 {
186   error_at(this->location_, "%s", msg);
187   this->set_is_error();
188 }
189
190 // An error statement, used to avoid crashing after we report an
191 // error.
192
193 class Error_statement : public Statement
194 {
195  public:
196   Error_statement(source_location location)
197     : Statement(STATEMENT_ERROR, location)
198   { }
199
200  protected:
201   int
202   do_traverse(Traverse*)
203   { return TRAVERSE_CONTINUE; }
204
205   tree
206   do_get_tree(Translate_context*)
207   { gcc_unreachable(); }
208 };
209
210 // Make an error statement.
211
212 Statement*
213 Statement::make_error_statement(source_location location)
214 {
215   return new Error_statement(location);
216 }
217
218 // Class Variable_declaration_statement.
219
220 Variable_declaration_statement::Variable_declaration_statement(
221     Named_object* var)
222   : Statement(STATEMENT_VARIABLE_DECLARATION, var->var_value()->location()),
223     var_(var)
224 {
225 }
226
227 // We don't actually traverse the variable here; it was traversed
228 // while traversing the Block.
229
230 int
231 Variable_declaration_statement::do_traverse(Traverse*)
232 {
233   return TRAVERSE_CONTINUE;
234 }
235
236 // Traverse the assignments in a variable declaration.  Note that this
237 // traversal is different from the usual traversal.
238
239 bool
240 Variable_declaration_statement::do_traverse_assignments(
241     Traverse_assignments* tassign)
242 {
243   tassign->initialize_variable(this->var_);
244   return true;
245 }
246
247 // Return the tree for a variable declaration.
248
249 tree
250 Variable_declaration_statement::do_get_tree(Translate_context* context)
251 {
252   tree val = this->var_->get_tree(context->gogo(), context->function());
253   if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
254     return error_mark_node;
255   Variable* variable = this->var_->var_value();
256
257   tree init = variable->get_init_tree(context->gogo(), context->function());
258   if (init == error_mark_node)
259     return error_mark_node;
260
261   // If this variable lives on the heap, we need to allocate it now.
262   if (!variable->is_in_heap())
263     {
264       DECL_INITIAL(val) = init;
265       return this->build_stmt_1(DECL_EXPR, val);
266     }
267   else
268     {
269       gcc_assert(TREE_CODE(val) == INDIRECT_REF);
270       tree decl = TREE_OPERAND(val, 0);
271       gcc_assert(TREE_CODE(decl) == VAR_DECL);
272       tree type = TREE_TYPE(decl);
273       gcc_assert(POINTER_TYPE_P(type));
274       tree size = TYPE_SIZE_UNIT(TREE_TYPE(type));
275       tree space = context->gogo()->allocate_memory(variable->type(), size,
276                                                     this->location());
277       space = fold_convert(TREE_TYPE(decl), space);
278       DECL_INITIAL(decl) = space;
279       return build2(COMPOUND_EXPR, void_type_node,
280                     this->build_stmt_1(DECL_EXPR, decl),
281                     build2(MODIFY_EXPR, void_type_node, val, init));
282     }
283 }
284
285 // Make a variable declaration.
286
287 Statement*
288 Statement::make_variable_declaration(Named_object* var)
289 {
290   return new Variable_declaration_statement(var);
291 }
292
293 // Class Temporary_statement.
294
295 // Return the type of the temporary variable.
296
297 Type*
298 Temporary_statement::type() const
299 {
300   return this->type_ != NULL ? this->type_ : this->init_->type();
301 }
302
303 // Return the tree for the temporary variable.
304
305 tree
306 Temporary_statement::get_decl() const
307 {
308   if (this->decl_ == NULL)
309     {
310       gcc_assert(saw_errors());
311       return error_mark_node;
312     }
313   return this->decl_;
314 }
315
316 // Traversal.
317
318 int
319 Temporary_statement::do_traverse(Traverse* traverse)
320 {
321   if (this->init_ == NULL)
322     return TRAVERSE_CONTINUE;
323   else
324     return this->traverse_expression(traverse, &this->init_);
325 }
326
327 // Traverse assignments.
328
329 bool
330 Temporary_statement::do_traverse_assignments(Traverse_assignments* tassign)
331 {
332   if (this->init_ == NULL)
333     return false;
334   tassign->value(&this->init_, true, true);
335   return true;
336 }
337
338 // Determine types.
339
340 void
341 Temporary_statement::do_determine_types()
342 {
343   if (this->type_ != NULL && this->type_->is_abstract())
344     this->type_ = this->type_->make_non_abstract_type();
345
346   if (this->init_ != NULL)
347     {
348       if (this->type_ == NULL)
349         this->init_->determine_type_no_context();
350       else
351         {
352           Type_context context(this->type_, false);
353           this->init_->determine_type(&context);
354         }
355     }
356
357   if (this->type_ == NULL)
358     {
359       this->type_ = this->init_->type();
360       gcc_assert(!this->type_->is_abstract());
361     }
362 }
363
364 // Check types.
365
366 void
367 Temporary_statement::do_check_types(Gogo*)
368 {
369   if (this->type_ != NULL && this->init_ != NULL)
370     {
371       std::string reason;
372       if (!Type::are_assignable(this->type_, this->init_->type(), &reason))
373         {
374           if (reason.empty())
375             error_at(this->location(), "incompatible types in assignment");
376           else
377             error_at(this->location(), "incompatible types in assignment (%s)",
378                      reason.c_str());
379           this->set_is_error();
380         }
381     }
382 }
383
384 // Return a tree.
385
386 tree
387 Temporary_statement::do_get_tree(Translate_context* context)
388 {
389   gcc_assert(this->decl_ == NULL_TREE);
390   tree type_tree = this->type()->get_tree(context->gogo());
391   if (type_tree == error_mark_node)
392     {
393       this->decl_ = error_mark_node;
394       return error_mark_node;
395     }
396   // We can only use create_tmp_var if the type is not addressable.
397   if (!TREE_ADDRESSABLE(type_tree))
398     {
399       this->decl_ = create_tmp_var(type_tree, "GOTMP");
400       DECL_SOURCE_LOCATION(this->decl_) = this->location();
401     }
402   else
403     {
404       gcc_assert(context->function() != NULL && context->block() != NULL);
405       tree decl = build_decl(this->location(), VAR_DECL,
406                              create_tmp_var_name("GOTMP"),
407                              type_tree);
408       DECL_ARTIFICIAL(decl) = 1;
409       DECL_IGNORED_P(decl) = 1;
410       TREE_USED(decl) = 1;
411       gcc_assert(current_function_decl != NULL_TREE);
412       DECL_CONTEXT(decl) = current_function_decl;
413
414       // We have to add this variable to the block so that it winds up
415       // in a BIND_EXPR.
416       tree block_tree = context->block_tree();
417       gcc_assert(block_tree != NULL_TREE);
418       DECL_CHAIN(decl) = BLOCK_VARS(block_tree);
419       BLOCK_VARS(block_tree) = decl;
420
421       this->decl_ = decl;
422     }
423   if (this->init_ != NULL)
424     DECL_INITIAL(this->decl_) =
425       Expression::convert_for_assignment(context, this->type(),
426                                          this->init_->type(),
427                                          this->init_->get_tree(context),
428                                          this->location());
429   if (this->is_address_taken_)
430     TREE_ADDRESSABLE(this->decl_) = 1;
431   return this->build_stmt_1(DECL_EXPR, this->decl_);
432 }
433
434 // Make and initialize a temporary variable in BLOCK.
435
436 Temporary_statement*
437 Statement::make_temporary(Type* type, Expression* init,
438                           source_location location)
439 {
440   return new Temporary_statement(type, init, location);
441 }
442
443 // An assignment statement.
444
445 class Assignment_statement : public Statement
446 {
447  public:
448   Assignment_statement(Expression* lhs, Expression* rhs,
449                        source_location location)
450     : Statement(STATEMENT_ASSIGNMENT, location),
451       lhs_(lhs), rhs_(rhs)
452   { }
453
454  protected:
455   int
456   do_traverse(Traverse* traverse);
457
458   bool
459   do_traverse_assignments(Traverse_assignments*);
460
461   void
462   do_determine_types();
463
464   void
465   do_check_types(Gogo*);
466
467   tree
468   do_get_tree(Translate_context*);
469
470  private:
471   // Left hand side--the lvalue.
472   Expression* lhs_;
473   // Right hand side--the rvalue.
474   Expression* rhs_;
475 };
476
477 // Traversal.
478
479 int
480 Assignment_statement::do_traverse(Traverse* traverse)
481 {
482   if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT)
483     return TRAVERSE_EXIT;
484   return this->traverse_expression(traverse, &this->rhs_);
485 }
486
487 bool
488 Assignment_statement::do_traverse_assignments(Traverse_assignments* tassign)
489 {
490   tassign->assignment(&this->lhs_, &this->rhs_);
491   return true;
492 }
493
494 // Set types for the assignment.
495
496 void
497 Assignment_statement::do_determine_types()
498 {
499   this->lhs_->determine_type_no_context();
500   Type_context context(this->lhs_->type(), false);
501   this->rhs_->determine_type(&context);
502 }
503
504 // Check types for an assignment.
505
506 void
507 Assignment_statement::do_check_types(Gogo*)
508 {
509   // The left hand side must be either addressable, a map index
510   // expression, or the blank identifier.
511   if (!this->lhs_->is_addressable()
512       && this->lhs_->map_index_expression() == NULL
513       && !this->lhs_->is_sink_expression())
514     {
515       if (!this->lhs_->type()->is_error_type())
516         this->report_error(_("invalid left hand side of assignment"));
517       return;
518     }
519
520   Type* lhs_type = this->lhs_->type();
521   Type* rhs_type = this->rhs_->type();
522   std::string reason;
523   if (!Type::are_assignable(lhs_type, rhs_type, &reason))
524     {
525       if (reason.empty())
526         error_at(this->location(), "incompatible types in assignment");
527       else
528         error_at(this->location(), "incompatible types in assignment (%s)",
529                  reason.c_str());
530       this->set_is_error();
531     }
532
533   if (lhs_type->is_error_type()
534       || rhs_type->is_error_type()
535       || lhs_type->is_undefined()
536       || rhs_type->is_undefined())
537     {
538       // Make sure we get the error for an undefined type.
539       lhs_type->base();
540       rhs_type->base();
541       this->set_is_error();
542     }
543 }
544
545 // Build a tree for an assignment statement.
546
547 tree
548 Assignment_statement::do_get_tree(Translate_context* context)
549 {
550   tree rhs_tree = this->rhs_->get_tree(context);
551
552   if (this->lhs_->is_sink_expression())
553     return rhs_tree;
554
555   tree lhs_tree = this->lhs_->get_tree(context);
556
557   if (lhs_tree == error_mark_node || rhs_tree == error_mark_node)
558     return error_mark_node;
559
560   rhs_tree = Expression::convert_for_assignment(context, this->lhs_->type(),
561                                                 this->rhs_->type(), rhs_tree,
562                                                 this->location());
563   if (rhs_tree == error_mark_node)
564     return error_mark_node;
565
566   return fold_build2_loc(this->location(), MODIFY_EXPR, void_type_node,
567                          lhs_tree, rhs_tree);
568 }
569
570 // Make an assignment statement.
571
572 Statement*
573 Statement::make_assignment(Expression* lhs, Expression* rhs,
574                            source_location location)
575 {
576   return new Assignment_statement(lhs, rhs, location);
577 }
578
579 // The Move_ordered_evals class is used to find any subexpressions of
580 // an expression that have an evaluation order dependency.  It creates
581 // temporary variables to hold them.
582
583 class Move_ordered_evals : public Traverse
584 {
585  public:
586   Move_ordered_evals(Block* block)
587     : Traverse(traverse_expressions),
588       block_(block)
589   { }
590
591  protected:
592   int
593   expression(Expression**);
594
595  private:
596   // The block where new temporary variables should be added.
597   Block* block_;
598 };
599
600 int
601 Move_ordered_evals::expression(Expression** pexpr)
602 {
603   // We have to look at subexpressions first.
604   if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
605     return TRAVERSE_EXIT;
606   if ((*pexpr)->must_eval_in_order())
607     {
608       source_location loc = (*pexpr)->location();
609       Temporary_statement* temp = Statement::make_temporary(NULL, *pexpr, loc);
610       this->block_->add_statement(temp);
611       *pexpr = Expression::make_temporary_reference(temp, loc);
612     }
613   return TRAVERSE_SKIP_COMPONENTS;
614 }
615
616 // An assignment operation statement.
617
618 class Assignment_operation_statement : public Statement
619 {
620  public:
621   Assignment_operation_statement(Operator op, Expression* lhs, Expression* rhs,
622                                  source_location location)
623     : Statement(STATEMENT_ASSIGNMENT_OPERATION, location),
624       op_(op), lhs_(lhs), rhs_(rhs)
625   { }
626
627  protected:
628   int
629   do_traverse(Traverse*);
630
631   bool
632   do_traverse_assignments(Traverse_assignments*)
633   { gcc_unreachable(); }
634
635   Statement*
636   do_lower(Gogo*, Block*);
637
638   tree
639   do_get_tree(Translate_context*)
640   { gcc_unreachable(); }
641
642  private:
643   // The operator (OPERATOR_PLUSEQ, etc.).
644   Operator op_;
645   // Left hand side.
646   Expression* lhs_;
647   // Right hand side.
648   Expression* rhs_;
649 };
650
651 // Traversal.
652
653 int
654 Assignment_operation_statement::do_traverse(Traverse* traverse)
655 {
656   if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT)
657     return TRAVERSE_EXIT;
658   return this->traverse_expression(traverse, &this->rhs_);
659 }
660
661 // Lower an assignment operation statement to a regular assignment
662 // statement.
663
664 Statement*
665 Assignment_operation_statement::do_lower(Gogo*, Block* enclosing)
666 {
667   source_location loc = this->location();
668
669   // We have to evaluate the left hand side expression only once.  We
670   // do this by moving out any expression with side effects.
671   Block* b = new Block(enclosing, loc);
672   Move_ordered_evals moe(b);
673   this->lhs_->traverse_subexpressions(&moe);
674
675   Expression* lval = this->lhs_->copy();
676
677   Operator op;
678   switch (this->op_)
679     {
680     case OPERATOR_PLUSEQ:
681       op = OPERATOR_PLUS;
682       break;
683     case OPERATOR_MINUSEQ:
684       op = OPERATOR_MINUS;
685       break;
686     case OPERATOR_OREQ:
687       op = OPERATOR_OR;
688       break;
689     case OPERATOR_XOREQ:
690       op = OPERATOR_XOR;
691       break;
692     case OPERATOR_MULTEQ:
693       op = OPERATOR_MULT;
694       break;
695     case OPERATOR_DIVEQ:
696       op = OPERATOR_DIV;
697       break;
698     case OPERATOR_MODEQ:
699       op = OPERATOR_MOD;
700       break;
701     case OPERATOR_LSHIFTEQ:
702       op = OPERATOR_LSHIFT;
703       break;
704     case OPERATOR_RSHIFTEQ:
705       op = OPERATOR_RSHIFT;
706       break;
707     case OPERATOR_ANDEQ:
708       op = OPERATOR_AND;
709       break;
710     case OPERATOR_BITCLEAREQ:
711       op = OPERATOR_BITCLEAR;
712       break;
713     default:
714       gcc_unreachable();
715     }
716
717   Expression* binop = Expression::make_binary(op, lval, this->rhs_, loc);
718   Statement* s = Statement::make_assignment(this->lhs_, binop, loc);
719   if (b->statements()->empty())
720     {
721       delete b;
722       return s;
723     }
724   else
725     {
726       b->add_statement(s);
727       return Statement::make_block_statement(b, loc);
728     }
729 }
730
731 // Make an assignment operation statement.
732
733 Statement*
734 Statement::make_assignment_operation(Operator op, Expression* lhs,
735                                      Expression* rhs, source_location location)
736 {
737   return new Assignment_operation_statement(op, lhs, rhs, location);
738 }
739
740 // A tuple assignment statement.  This differs from an assignment
741 // statement in that the right-hand-side expressions are evaluated in
742 // parallel.
743
744 class Tuple_assignment_statement : public Statement
745 {
746  public:
747   Tuple_assignment_statement(Expression_list* lhs, Expression_list* rhs,
748                              source_location location)
749     : Statement(STATEMENT_TUPLE_ASSIGNMENT, location),
750       lhs_(lhs), rhs_(rhs)
751   { }
752
753  protected:
754   int
755   do_traverse(Traverse* traverse);
756
757   bool
758   do_traverse_assignments(Traverse_assignments*)
759   { gcc_unreachable(); }
760
761   Statement*
762   do_lower(Gogo*, Block*);
763
764   tree
765   do_get_tree(Translate_context*)
766   { gcc_unreachable(); }
767
768  private:
769   // Left hand side--a list of lvalues.
770   Expression_list* lhs_;
771   // Right hand side--a list of rvalues.
772   Expression_list* rhs_;
773 };
774
775 // Traversal.
776
777 int
778 Tuple_assignment_statement::do_traverse(Traverse* traverse)
779 {
780   if (this->traverse_expression_list(traverse, this->lhs_) == TRAVERSE_EXIT)
781     return TRAVERSE_EXIT;
782   return this->traverse_expression_list(traverse, this->rhs_);
783 }
784
785 // Lower a tuple assignment.  We use temporary variables to split it
786 // up into a set of single assignments.
787
788 Statement*
789 Tuple_assignment_statement::do_lower(Gogo*, Block* enclosing)
790 {
791   source_location loc = this->location();
792
793   Block* b = new Block(enclosing, loc);
794   
795   // First move out any subexpressions on the left hand side.  The
796   // right hand side will be evaluated in the required order anyhow.
797   Move_ordered_evals moe(b);
798   for (Expression_list::const_iterator plhs = this->lhs_->begin();
799        plhs != this->lhs_->end();
800        ++plhs)
801     (*plhs)->traverse_subexpressions(&moe);
802
803   std::vector<Temporary_statement*> temps;
804   temps.reserve(this->lhs_->size());
805
806   Expression_list::const_iterator prhs = this->rhs_->begin();
807   for (Expression_list::const_iterator plhs = this->lhs_->begin();
808        plhs != this->lhs_->end();
809        ++plhs, ++prhs)
810     {
811       gcc_assert(prhs != this->rhs_->end());
812
813       if ((*plhs)->is_error_expression()
814           || (*plhs)->type()->is_error_type()
815           || (*prhs)->is_error_expression()
816           || (*prhs)->type()->is_error_type())
817         continue;
818
819       if ((*plhs)->is_sink_expression())
820         {
821           b->add_statement(Statement::make_statement(*prhs));
822           continue;
823         }
824
825       Temporary_statement* temp = Statement::make_temporary((*plhs)->type(),
826                                                             *prhs, loc);
827       b->add_statement(temp);
828       temps.push_back(temp);
829
830     }
831   gcc_assert(prhs == this->rhs_->end());
832
833   prhs = this->rhs_->begin();
834   std::vector<Temporary_statement*>::const_iterator ptemp = temps.begin();
835   for (Expression_list::const_iterator plhs = this->lhs_->begin();
836        plhs != this->lhs_->end();
837        ++plhs, ++prhs)
838     {
839       if ((*plhs)->is_error_expression()
840           || (*plhs)->type()->is_error_type()
841           || (*prhs)->is_error_expression()
842           || (*prhs)->type()->is_error_type())
843         continue;
844
845       if ((*plhs)->is_sink_expression())
846         continue;
847
848       Expression* ref = Expression::make_temporary_reference(*ptemp, loc);
849       Statement* s = Statement::make_assignment(*plhs, ref, loc);
850       b->add_statement(s);
851       ++ptemp;
852     }
853   gcc_assert(ptemp == temps.end());
854
855   return Statement::make_block_statement(b, loc);
856 }
857
858 // Make a tuple assignment statement.
859
860 Statement*
861 Statement::make_tuple_assignment(Expression_list* lhs, Expression_list* rhs,
862                                  source_location location)
863 {
864   return new Tuple_assignment_statement(lhs, rhs, location);
865 }
866
867 // A tuple assignment from a map index expression.
868 //   v, ok = m[k]
869
870 class Tuple_map_assignment_statement : public Statement
871 {
872 public:
873   Tuple_map_assignment_statement(Expression* val, Expression* present,
874                                  Expression* map_index,
875                                  source_location location)
876     : Statement(STATEMENT_TUPLE_MAP_ASSIGNMENT, location),
877       val_(val), present_(present), map_index_(map_index)
878   { }
879
880  protected:
881   int
882   do_traverse(Traverse* traverse);
883
884   bool
885   do_traverse_assignments(Traverse_assignments*)
886   { gcc_unreachable(); }
887
888   Statement*
889   do_lower(Gogo*, Block*);
890
891   tree
892   do_get_tree(Translate_context*)
893   { gcc_unreachable(); }
894
895  private:
896   // Lvalue which receives the value from the map.
897   Expression* val_;
898   // Lvalue which receives whether the key value was present.
899   Expression* present_;
900   // The map index expression.
901   Expression* map_index_;
902 };
903
904 // Traversal.
905
906 int
907 Tuple_map_assignment_statement::do_traverse(Traverse* traverse)
908 {
909   if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT
910       || this->traverse_expression(traverse, &this->present_) == TRAVERSE_EXIT)
911     return TRAVERSE_EXIT;
912   return this->traverse_expression(traverse, &this->map_index_);
913 }
914
915 // Lower a tuple map assignment.
916
917 Statement*
918 Tuple_map_assignment_statement::do_lower(Gogo*, Block* enclosing)
919 {
920   source_location loc = this->location();
921
922   Map_index_expression* map_index = this->map_index_->map_index_expression();
923   if (map_index == NULL)
924     {
925       this->report_error(_("expected map index on right hand side"));
926       return Statement::make_error_statement(loc);
927     }
928   Map_type* map_type = map_index->get_map_type();
929   if (map_type == NULL)
930     return Statement::make_error_statement(loc);
931
932   Block* b = new Block(enclosing, loc);
933
934   // Move out any subexpressions to make sure that functions are
935   // called in the required order.
936   Move_ordered_evals moe(b);
937   this->val_->traverse_subexpressions(&moe);
938   this->present_->traverse_subexpressions(&moe);
939
940   // Copy the key value into a temporary so that we can take its
941   // address without pushing the value onto the heap.
942
943   // var key_temp KEY_TYPE = MAP_INDEX
944   Temporary_statement* key_temp =
945     Statement::make_temporary(map_type->key_type(), map_index->index(), loc);
946   b->add_statement(key_temp);
947
948   // var val_temp VAL_TYPE
949   Temporary_statement* val_temp =
950     Statement::make_temporary(map_type->val_type(), NULL, loc);
951   b->add_statement(val_temp);
952
953   // var present_temp bool
954   Temporary_statement* present_temp =
955     Statement::make_temporary(Type::lookup_bool_type(), NULL, loc);
956   b->add_statement(present_temp);
957
958   // func mapaccess2(hmap map[k]v, key *k, val *v) bool
959   source_location bloc = BUILTINS_LOCATION;
960   Typed_identifier_list* param_types = new Typed_identifier_list();
961   param_types->push_back(Typed_identifier("hmap", map_type, bloc));
962   Type* pkey_type = Type::make_pointer_type(map_type->key_type());
963   param_types->push_back(Typed_identifier("key", pkey_type, bloc));
964   Type* pval_type = Type::make_pointer_type(map_type->val_type());
965   param_types->push_back(Typed_identifier("val", pval_type, bloc));
966
967   Typed_identifier_list* ret_types = new Typed_identifier_list();
968   ret_types->push_back(Typed_identifier("", Type::make_boolean_type(), bloc));
969
970   Function_type* fntype = Type::make_function_type(NULL, param_types,
971                                                    ret_types, bloc);
972   Named_object* mapaccess2 =
973     Named_object::make_function_declaration("mapaccess2", NULL, fntype, bloc);
974   mapaccess2->func_declaration_value()->set_asm_name("runtime.mapaccess2");
975
976   // present_temp = mapaccess2(MAP, &key_temp, &val_temp)
977   Expression* func = Expression::make_func_reference(mapaccess2, NULL, loc);
978   Expression_list* params = new Expression_list();
979   params->push_back(map_index->map());
980   Expression* ref = Expression::make_temporary_reference(key_temp, loc);
981   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
982   ref = Expression::make_temporary_reference(val_temp, loc);
983   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
984   Expression* call = Expression::make_call(func, params, false, loc);
985
986   ref = Expression::make_temporary_reference(present_temp, loc);
987   Statement* s = Statement::make_assignment(ref, call, loc);
988   b->add_statement(s);
989
990   // val = val_temp
991   ref = Expression::make_temporary_reference(val_temp, loc);
992   s = Statement::make_assignment(this->val_, ref, loc);
993   b->add_statement(s);
994
995   // present = present_temp
996   ref = Expression::make_temporary_reference(present_temp, loc);
997   s = Statement::make_assignment(this->present_, ref, loc);
998   b->add_statement(s);
999
1000   return Statement::make_block_statement(b, loc);
1001 }
1002
1003 // Make a map assignment statement which returns a pair of values.
1004
1005 Statement*
1006 Statement::make_tuple_map_assignment(Expression* val, Expression* present,
1007                                      Expression* map_index,
1008                                      source_location location)
1009 {
1010   return new Tuple_map_assignment_statement(val, present, map_index, location);
1011 }
1012
1013 // Assign a pair of entries to a map.
1014 //   m[k] = v, p
1015
1016 class Map_assignment_statement : public Statement
1017 {
1018  public:
1019   Map_assignment_statement(Expression* map_index,
1020                            Expression* val, Expression* should_set,
1021                            source_location location)
1022     : Statement(STATEMENT_MAP_ASSIGNMENT, location),
1023       map_index_(map_index), val_(val), should_set_(should_set)
1024   { }
1025
1026  protected:
1027   int
1028   do_traverse(Traverse* traverse);
1029
1030   bool
1031   do_traverse_assignments(Traverse_assignments*)
1032   { gcc_unreachable(); }
1033
1034   Statement*
1035   do_lower(Gogo*, Block*);
1036
1037   tree
1038   do_get_tree(Translate_context*)
1039   { gcc_unreachable(); }
1040
1041  private:
1042   // A reference to the map index which should be set or deleted.
1043   Expression* map_index_;
1044   // The value to add to the map.
1045   Expression* val_;
1046   // Whether or not to add the value.
1047   Expression* should_set_;
1048 };
1049
1050 // Traverse a map assignment.
1051
1052 int
1053 Map_assignment_statement::do_traverse(Traverse* traverse)
1054 {
1055   if (this->traverse_expression(traverse, &this->map_index_) == TRAVERSE_EXIT
1056       || this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT)
1057     return TRAVERSE_EXIT;
1058   return this->traverse_expression(traverse, &this->should_set_);
1059 }
1060
1061 // Lower a map assignment to a function call.
1062
1063 Statement*
1064 Map_assignment_statement::do_lower(Gogo*, Block* enclosing)
1065 {
1066   source_location loc = this->location();
1067
1068   Map_index_expression* map_index = this->map_index_->map_index_expression();
1069   if (map_index == NULL)
1070     {
1071       this->report_error(_("expected map index on left hand side"));
1072       return Statement::make_error_statement(loc);
1073     }
1074   Map_type* map_type = map_index->get_map_type();
1075   if (map_type == NULL)
1076     return Statement::make_error_statement(loc);
1077
1078   Block* b = new Block(enclosing, loc);
1079
1080   // Evaluate the map first to get order of evaluation right.
1081   // map_temp := m // we are evaluating m[k] = v, p
1082   Temporary_statement* map_temp = Statement::make_temporary(map_type,
1083                                                             map_index->map(),
1084                                                             loc);
1085   b->add_statement(map_temp);
1086
1087   // var key_temp MAP_KEY_TYPE = k
1088   Temporary_statement* key_temp =
1089     Statement::make_temporary(map_type->key_type(), map_index->index(), loc);
1090   b->add_statement(key_temp);
1091
1092   // var val_temp MAP_VAL_TYPE = v
1093   Temporary_statement* val_temp =
1094     Statement::make_temporary(map_type->val_type(), this->val_, loc);
1095   b->add_statement(val_temp);
1096
1097   // func mapassign2(hmap map[k]v, key *k, val *v, p)
1098   source_location bloc = BUILTINS_LOCATION;
1099   Typed_identifier_list* param_types = new Typed_identifier_list();
1100   param_types->push_back(Typed_identifier("hmap", map_type, bloc));
1101   Type* pkey_type = Type::make_pointer_type(map_type->key_type());
1102   param_types->push_back(Typed_identifier("key", pkey_type, bloc));
1103   Type* pval_type = Type::make_pointer_type(map_type->val_type());
1104   param_types->push_back(Typed_identifier("val", pval_type, bloc));
1105   param_types->push_back(Typed_identifier("p", Type::lookup_bool_type(), bloc));
1106   Function_type* fntype = Type::make_function_type(NULL, param_types,
1107                                                    NULL, bloc);
1108   Named_object* mapassign2 =
1109     Named_object::make_function_declaration("mapassign2", NULL, fntype, bloc);
1110   mapassign2->func_declaration_value()->set_asm_name("runtime.mapassign2");
1111
1112   // mapassign2(map_temp, &key_temp, &val_temp, p)
1113   Expression* func = Expression::make_func_reference(mapassign2, NULL, loc);
1114   Expression_list* params = new Expression_list();
1115   params->push_back(Expression::make_temporary_reference(map_temp, loc));
1116   Expression* ref = Expression::make_temporary_reference(key_temp, loc);
1117   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
1118   ref = Expression::make_temporary_reference(val_temp, loc);
1119   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
1120   params->push_back(this->should_set_);
1121   Expression* call = Expression::make_call(func, params, false, loc);
1122   Statement* s = Statement::make_statement(call);
1123   b->add_statement(s);
1124
1125   return Statement::make_block_statement(b, loc);
1126 }
1127
1128 // Make a statement which assigns a pair of entries to a map.
1129
1130 Statement*
1131 Statement::make_map_assignment(Expression* map_index,
1132                                Expression* val, Expression* should_set,
1133                                source_location location)
1134 {
1135   return new Map_assignment_statement(map_index, val, should_set, location);
1136 }
1137
1138 // A tuple assignment from a receive statement.
1139
1140 class Tuple_receive_assignment_statement : public Statement
1141 {
1142  public:
1143   Tuple_receive_assignment_statement(Expression* val, Expression* success,
1144                                      Expression* channel,
1145                                      source_location location)
1146     : Statement(STATEMENT_TUPLE_RECEIVE_ASSIGNMENT, location),
1147       val_(val), success_(success), channel_(channel)
1148   { }
1149
1150  protected:
1151   int
1152   do_traverse(Traverse* traverse);
1153
1154   bool
1155   do_traverse_assignments(Traverse_assignments*)
1156   { gcc_unreachable(); }
1157
1158   Statement*
1159   do_lower(Gogo*, Block*);
1160
1161   tree
1162   do_get_tree(Translate_context*)
1163   { gcc_unreachable(); }
1164
1165  private:
1166   // Lvalue which receives the value from the channel.
1167   Expression* val_;
1168   // Lvalue which receives whether the read succeeded or failed.
1169   Expression* success_;
1170   // The channel on which we receive the value.
1171   Expression* channel_;
1172 };
1173
1174 // Traversal.
1175
1176 int
1177 Tuple_receive_assignment_statement::do_traverse(Traverse* traverse)
1178 {
1179   if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT
1180       || this->traverse_expression(traverse, &this->success_) == TRAVERSE_EXIT)
1181     return TRAVERSE_EXIT;
1182   return this->traverse_expression(traverse, &this->channel_);
1183 }
1184
1185 // Lower to a function call.
1186
1187 Statement*
1188 Tuple_receive_assignment_statement::do_lower(Gogo*, Block* enclosing)
1189 {
1190   source_location loc = this->location();
1191
1192   Channel_type* channel_type = this->channel_->type()->channel_type();
1193   if (channel_type == NULL)
1194     {
1195       this->report_error(_("expected channel"));
1196       return Statement::make_error_statement(loc);
1197     }
1198   if (!channel_type->may_receive())
1199     {
1200       this->report_error(_("invalid receive on send-only channel"));
1201       return Statement::make_error_statement(loc);
1202     }
1203
1204   Block* b = new Block(enclosing, loc);
1205
1206   // Make sure that any subexpressions on the left hand side are
1207   // evaluated in the right order.
1208   Move_ordered_evals moe(b);
1209   this->val_->traverse_subexpressions(&moe);
1210   this->success_->traverse_subexpressions(&moe);
1211
1212   // var val_temp ELEMENT_TYPE
1213   Temporary_statement* val_temp =
1214     Statement::make_temporary(channel_type->element_type(), NULL, loc);
1215   b->add_statement(val_temp);
1216
1217   // var success_temp bool
1218   Temporary_statement* success_temp =
1219     Statement::make_temporary(Type::lookup_bool_type(), NULL, loc);
1220   b->add_statement(success_temp);
1221
1222   // func chanrecv2(c chan T, val *T) bool
1223   source_location bloc = BUILTINS_LOCATION;
1224   Typed_identifier_list* param_types = new Typed_identifier_list();
1225   param_types->push_back(Typed_identifier("c", channel_type, bloc));
1226   Type* pelement_type = Type::make_pointer_type(channel_type->element_type());
1227   param_types->push_back(Typed_identifier("val", pelement_type, bloc));
1228
1229   Typed_identifier_list* ret_types = new Typed_identifier_list();
1230   ret_types->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1231
1232   Function_type* fntype = Type::make_function_type(NULL, param_types,
1233                                                    ret_types, bloc);
1234   Named_object* chanrecv2 =
1235     Named_object::make_function_declaration("chanrecv2", NULL, fntype, bloc);
1236   chanrecv2->func_declaration_value()->set_asm_name("runtime.chanrecv2");
1237
1238   // success_temp = chanrecv2(channel, &val_temp)
1239   Expression* func = Expression::make_func_reference(chanrecv2, NULL, loc);
1240   Expression_list* params = new Expression_list();
1241   params->push_back(this->channel_);
1242   Expression* ref = Expression::make_temporary_reference(val_temp, loc);
1243   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
1244   Expression* call = Expression::make_call(func, params, false, loc);
1245   ref = Expression::make_temporary_reference(success_temp, loc);
1246   Statement* s = Statement::make_assignment(ref, call, loc);
1247   b->add_statement(s);
1248
1249   // val = val_temp
1250   ref = Expression::make_temporary_reference(val_temp, loc);
1251   s = Statement::make_assignment(this->val_, ref, loc);
1252   b->add_statement(s);
1253
1254   // success = success_temp
1255   ref = Expression::make_temporary_reference(success_temp, loc);
1256   s = Statement::make_assignment(this->success_, ref, loc);
1257   b->add_statement(s);
1258
1259   return Statement::make_block_statement(b, loc);
1260 }
1261
1262 // Make a nonblocking receive statement.
1263
1264 Statement*
1265 Statement::make_tuple_receive_assignment(Expression* val, Expression* success,
1266                                          Expression* channel,
1267                                          source_location location)
1268 {
1269   return new Tuple_receive_assignment_statement(val, success, channel,
1270                                                 location);
1271 }
1272
1273 // An assignment to a pair of values from a type guard.  This is a
1274 // conditional type guard.  v, ok = i.(type).
1275
1276 class Tuple_type_guard_assignment_statement : public Statement
1277 {
1278  public:
1279   Tuple_type_guard_assignment_statement(Expression* val, Expression* ok,
1280                                         Expression* expr, Type* type,
1281                                         source_location location)
1282     : Statement(STATEMENT_TUPLE_TYPE_GUARD_ASSIGNMENT, location),
1283       val_(val), ok_(ok), expr_(expr), type_(type)
1284   { }
1285
1286  protected:
1287   int
1288   do_traverse(Traverse*);
1289
1290   bool
1291   do_traverse_assignments(Traverse_assignments*)
1292   { gcc_unreachable(); }
1293
1294   Statement*
1295   do_lower(Gogo*, Block*);
1296
1297   tree
1298   do_get_tree(Translate_context*)
1299   { gcc_unreachable(); }
1300
1301  private:
1302   Call_expression*
1303   lower_to_empty_interface(const char*);
1304
1305   Call_expression*
1306   lower_to_type(const char*);
1307
1308   void
1309   lower_to_object_type(Block*, const char*);
1310
1311   // The variable which recieves the converted value.
1312   Expression* val_;
1313   // The variable which receives the indication of success.
1314   Expression* ok_;
1315   // The expression being converted.
1316   Expression* expr_;
1317   // The type to which the expression is being converted.
1318   Type* type_;
1319 };
1320
1321 // Traverse a type guard tuple assignment.
1322
1323 int
1324 Tuple_type_guard_assignment_statement::do_traverse(Traverse* traverse)
1325 {
1326   if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT
1327       || this->traverse_expression(traverse, &this->ok_) == TRAVERSE_EXIT
1328       || this->traverse_type(traverse, this->type_) == TRAVERSE_EXIT)
1329     return TRAVERSE_EXIT;
1330   return this->traverse_expression(traverse, &this->expr_);
1331 }
1332
1333 // Lower to a function call.
1334
1335 Statement*
1336 Tuple_type_guard_assignment_statement::do_lower(Gogo*, Block* enclosing)
1337 {
1338   source_location loc = this->location();
1339
1340   Type* expr_type = this->expr_->type();
1341   if (expr_type->interface_type() == NULL)
1342     {
1343       if (!expr_type->is_error_type() && !this->type_->is_error_type())
1344         this->report_error(_("type assertion only valid for interface types"));
1345       return Statement::make_error_statement(loc);
1346     }
1347
1348   Block* b = new Block(enclosing, loc);
1349
1350   // Make sure that any subexpressions on the left hand side are
1351   // evaluated in the right order.
1352   Move_ordered_evals moe(b);
1353   this->val_->traverse_subexpressions(&moe);
1354   this->ok_->traverse_subexpressions(&moe);
1355
1356   bool expr_is_empty = expr_type->interface_type()->is_empty();
1357   Call_expression* call;
1358   if (this->type_->interface_type() != NULL)
1359     {
1360       if (this->type_->interface_type()->is_empty())
1361         call = this->lower_to_empty_interface(expr_is_empty
1362                                               ? "ifaceE2E2"
1363                                               : "ifaceI2E2");
1364       else
1365         call = this->lower_to_type(expr_is_empty ? "ifaceE2I2" : "ifaceI2I2");
1366     }
1367   else if (this->type_->points_to() != NULL)
1368     call = this->lower_to_type(expr_is_empty ? "ifaceE2T2P" : "ifaceI2T2P");
1369   else
1370     {
1371       this->lower_to_object_type(b, expr_is_empty ? "ifaceE2T2" : "ifaceI2T2");
1372       call = NULL;
1373     }
1374
1375   if (call != NULL)
1376     {
1377       Expression* res = Expression::make_call_result(call, 0);
1378       Statement* s = Statement::make_assignment(this->val_, res, loc);
1379       b->add_statement(s);
1380
1381       res = Expression::make_call_result(call, 1);
1382       s = Statement::make_assignment(this->ok_, res, loc);
1383       b->add_statement(s);
1384     }
1385
1386   return Statement::make_block_statement(b, loc);
1387 }
1388
1389 // Lower a conversion to an empty interface type.
1390
1391 Call_expression*
1392 Tuple_type_guard_assignment_statement::lower_to_empty_interface(
1393     const char *fnname)
1394 {
1395   source_location loc = this->location();
1396
1397   // func FNNAME(interface) (empty, bool)
1398   source_location bloc = BUILTINS_LOCATION;
1399   Typed_identifier_list* param_types = new Typed_identifier_list();
1400   param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc));
1401   Typed_identifier_list* ret_types = new Typed_identifier_list();
1402   ret_types->push_back(Typed_identifier("ret", this->type_, bloc));
1403   ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc));
1404   Function_type* fntype = Type::make_function_type(NULL, param_types,
1405                                                    ret_types, bloc);
1406   Named_object* fn =
1407     Named_object::make_function_declaration(fnname, NULL, fntype, bloc);
1408   std::string asm_name = "runtime.";
1409   asm_name += fnname;
1410   fn->func_declaration_value()->set_asm_name(asm_name);
1411
1412   // val, ok = FNNAME(expr)
1413   Expression* func = Expression::make_func_reference(fn, NULL, loc);
1414   Expression_list* params = new Expression_list();
1415   params->push_back(this->expr_);
1416   return Expression::make_call(func, params, false, loc);
1417 }
1418
1419 // Lower a conversion to a non-empty interface type or a pointer type.
1420
1421 Call_expression*
1422 Tuple_type_guard_assignment_statement::lower_to_type(const char* fnname)
1423 {
1424   source_location loc = this->location();
1425
1426   // func FNNAME(*descriptor, interface) (interface, bool)
1427   source_location bloc = BUILTINS_LOCATION;
1428   Typed_identifier_list* param_types = new Typed_identifier_list();
1429   param_types->push_back(Typed_identifier("inter",
1430                                           Type::make_type_descriptor_ptr_type(),
1431                                           bloc));
1432   param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc));
1433   Typed_identifier_list* ret_types = new Typed_identifier_list();
1434   ret_types->push_back(Typed_identifier("ret", this->type_, bloc));
1435   ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc));
1436   Function_type* fntype = Type::make_function_type(NULL, param_types,
1437                                                    ret_types, bloc);
1438   Named_object* fn =
1439     Named_object::make_function_declaration(fnname, NULL, fntype, bloc);
1440   std::string asm_name = "runtime.";
1441   asm_name += fnname;
1442   fn->func_declaration_value()->set_asm_name(asm_name);
1443
1444   // val, ok = FNNAME(type_descriptor, expr)
1445   Expression* func = Expression::make_func_reference(fn, NULL, loc);
1446   Expression_list* params = new Expression_list();
1447   params->push_back(Expression::make_type_descriptor(this->type_, loc));
1448   params->push_back(this->expr_);
1449   return Expression::make_call(func, params, false, loc);
1450 }
1451
1452 // Lower a conversion to a non-interface non-pointer type.
1453
1454 void
1455 Tuple_type_guard_assignment_statement::lower_to_object_type(Block* b,
1456                                                             const char *fnname)
1457 {
1458   source_location loc = this->location();
1459
1460   // var val_temp TYPE
1461   Temporary_statement* val_temp = Statement::make_temporary(this->type_,
1462                                                             NULL, loc);
1463   b->add_statement(val_temp);
1464
1465   // func FNNAME(*descriptor, interface, *T) bool
1466   source_location bloc = BUILTINS_LOCATION;
1467   Typed_identifier_list* param_types = new Typed_identifier_list();
1468   param_types->push_back(Typed_identifier("inter",
1469                                           Type::make_type_descriptor_ptr_type(),
1470                                           bloc));
1471   param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc));
1472   Type* ptype = Type::make_pointer_type(this->type_);
1473   param_types->push_back(Typed_identifier("v", ptype, bloc));
1474   Typed_identifier_list* ret_types = new Typed_identifier_list();
1475   ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc));
1476   Function_type* fntype = Type::make_function_type(NULL, param_types,
1477                                                    ret_types, bloc);
1478   Named_object* fn =
1479     Named_object::make_function_declaration(fnname, NULL, fntype, bloc);
1480   std::string asm_name = "runtime.";
1481   asm_name += fnname;
1482   fn->func_declaration_value()->set_asm_name(asm_name);
1483
1484   // ok = FNNAME(type_descriptor, expr, &val_temp)
1485   Expression* func = Expression::make_func_reference(fn, NULL, loc);
1486   Expression_list* params = new Expression_list();
1487   params->push_back(Expression::make_type_descriptor(this->type_, loc));
1488   params->push_back(this->expr_);
1489   Expression* ref = Expression::make_temporary_reference(val_temp, loc);
1490   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
1491   Expression* call = Expression::make_call(func, params, false, loc);
1492   Statement* s = Statement::make_assignment(this->ok_, call, loc);
1493   b->add_statement(s);
1494
1495   // val = val_temp
1496   ref = Expression::make_temporary_reference(val_temp, loc);
1497   s = Statement::make_assignment(this->val_, ref, loc);
1498   b->add_statement(s);
1499 }
1500
1501 // Make an assignment from a type guard to a pair of variables.
1502
1503 Statement*
1504 Statement::make_tuple_type_guard_assignment(Expression* val, Expression* ok,
1505                                             Expression* expr, Type* type,
1506                                             source_location location)
1507 {
1508   return new Tuple_type_guard_assignment_statement(val, ok, expr, type,
1509                                                    location);
1510 }
1511
1512 // An expression statement.
1513
1514 class Expression_statement : public Statement
1515 {
1516  public:
1517   Expression_statement(Expression* expr)
1518     : Statement(STATEMENT_EXPRESSION, expr->location()),
1519       expr_(expr)
1520   { }
1521
1522  protected:
1523   int
1524   do_traverse(Traverse* traverse)
1525   { return this->traverse_expression(traverse, &this->expr_); }
1526
1527   void
1528   do_determine_types()
1529   { this->expr_->determine_type_no_context(); }
1530
1531   bool
1532   do_may_fall_through() const;
1533
1534   tree
1535   do_get_tree(Translate_context* context)
1536   { return this->expr_->get_tree(context); }
1537
1538  private:
1539   Expression* expr_;
1540 };
1541
1542 // An expression statement may fall through unless it is a call to a
1543 // function which does not return.
1544
1545 bool
1546 Expression_statement::do_may_fall_through() const
1547 {
1548   const Call_expression* call = this->expr_->call_expression();
1549   if (call != NULL)
1550     {
1551       const Expression* fn = call->fn();
1552       const Func_expression* fe = fn->func_expression();
1553       if (fe != NULL)
1554         {
1555           const Named_object* no = fe->named_object();
1556
1557           Function_type* fntype;
1558           if (no->is_function())
1559             fntype = no->func_value()->type();
1560           else if (no->is_function_declaration())
1561             fntype = no->func_declaration_value()->type();
1562           else
1563             fntype = NULL;
1564
1565           // The builtin function panic does not return.
1566           if (fntype != NULL && fntype->is_builtin() && no->name() == "panic")
1567             return false;
1568         }
1569     }
1570   return true;
1571 }
1572
1573 // Make an expression statement from an Expression.
1574
1575 Statement*
1576 Statement::make_statement(Expression* expr)
1577 {
1578   return new Expression_statement(expr);
1579 }
1580
1581 // A block statement--a list of statements which may include variable
1582 // definitions.
1583
1584 class Block_statement : public Statement
1585 {
1586  public:
1587   Block_statement(Block* block, source_location location)
1588     : Statement(STATEMENT_BLOCK, location),
1589       block_(block)
1590   { }
1591
1592  protected:
1593   int
1594   do_traverse(Traverse* traverse)
1595   { return this->block_->traverse(traverse); }
1596
1597   void
1598   do_determine_types()
1599   { this->block_->determine_types(); }
1600
1601   bool
1602   do_may_fall_through() const
1603   { return this->block_->may_fall_through(); }
1604
1605   tree
1606   do_get_tree(Translate_context* context)
1607   { return this->block_->get_tree(context); }
1608
1609  private:
1610   Block* block_;
1611 };
1612
1613 // Make a block statement.
1614
1615 Statement*
1616 Statement::make_block_statement(Block* block, source_location location)
1617 {
1618   return new Block_statement(block, location);
1619 }
1620
1621 // An increment or decrement statement.
1622
1623 class Inc_dec_statement : public Statement
1624 {
1625  public:
1626   Inc_dec_statement(bool is_inc, Expression* expr)
1627     : Statement(STATEMENT_INCDEC, expr->location()),
1628       expr_(expr), is_inc_(is_inc)
1629   { }
1630
1631  protected:
1632   int
1633   do_traverse(Traverse* traverse)
1634   { return this->traverse_expression(traverse, &this->expr_); }
1635
1636   bool
1637   do_traverse_assignments(Traverse_assignments*)
1638   { gcc_unreachable(); }
1639
1640   Statement*
1641   do_lower(Gogo*, Block*);
1642
1643   tree
1644   do_get_tree(Translate_context*)
1645   { gcc_unreachable(); }
1646
1647  private:
1648   // The l-value to increment or decrement.
1649   Expression* expr_;
1650   // Whether to increment or decrement.
1651   bool is_inc_;
1652 };
1653
1654 // Lower to += or -=.
1655
1656 Statement*
1657 Inc_dec_statement::do_lower(Gogo*, Block*)
1658 {
1659   source_location loc = this->location();
1660
1661   mpz_t oval;
1662   mpz_init_set_ui(oval, 1UL);
1663   Expression* oexpr = Expression::make_integer(&oval, NULL, loc);
1664   mpz_clear(oval);
1665
1666   Operator op = this->is_inc_ ? OPERATOR_PLUSEQ : OPERATOR_MINUSEQ;
1667   return Statement::make_assignment_operation(op, this->expr_, oexpr, loc);
1668 }
1669
1670 // Make an increment statement.
1671
1672 Statement*
1673 Statement::make_inc_statement(Expression* expr)
1674 {
1675   return new Inc_dec_statement(true, expr);
1676 }
1677
1678 // Make a decrement statement.
1679
1680 Statement*
1681 Statement::make_dec_statement(Expression* expr)
1682 {
1683   return new Inc_dec_statement(false, expr);
1684 }
1685
1686 // Class Thunk_statement.  This is the base class for go and defer
1687 // statements.
1688
1689 const char* const Thunk_statement::thunk_field_fn = "fn";
1690
1691 const char* const Thunk_statement::thunk_field_receiver = "receiver";
1692
1693 // Constructor.
1694
1695 Thunk_statement::Thunk_statement(Statement_classification classification,
1696                                  Call_expression* call,
1697                                  source_location location)
1698     : Statement(classification, location),
1699       call_(call), struct_type_(NULL)
1700 {
1701 }
1702
1703 // Return whether this is a simple statement which does not require a
1704 // thunk.
1705
1706 bool
1707 Thunk_statement::is_simple(Function_type* fntype) const
1708 {
1709   // We need a thunk to call a method, or to pass a variable number of
1710   // arguments.
1711   if (fntype->is_method() || fntype->is_varargs())
1712     return false;
1713
1714   // A defer statement requires a thunk to set up for whether the
1715   // function can call recover.
1716   if (this->classification() == STATEMENT_DEFER)
1717     return false;
1718
1719   // We can only permit a single parameter of pointer type.
1720   const Typed_identifier_list* parameters = fntype->parameters();
1721   if (parameters != NULL
1722       && (parameters->size() > 1
1723           || (parameters->size() == 1
1724               && parameters->begin()->type()->points_to() == NULL)))
1725     return false;
1726
1727   // If the function returns multiple values, or returns a type other
1728   // than integer, floating point, or pointer, then it may get a
1729   // hidden first parameter, in which case we need the more
1730   // complicated approach.  This is true even though we are going to
1731   // ignore the return value.
1732   const Typed_identifier_list* results = fntype->results();
1733   if (results != NULL
1734       && (results->size() > 1
1735           || (results->size() == 1
1736               && !results->begin()->type()->is_basic_type()
1737               && results->begin()->type()->points_to() == NULL)))
1738     return false;
1739
1740   // If this calls something which is not a simple function, then we
1741   // need a thunk.
1742   Expression* fn = this->call_->call_expression()->fn();
1743   if (fn->bound_method_expression() != NULL
1744       || fn->interface_field_reference_expression() != NULL)
1745     return false;
1746
1747   return true;
1748 }
1749
1750 // Traverse a thunk statement.
1751
1752 int
1753 Thunk_statement::do_traverse(Traverse* traverse)
1754 {
1755   return this->traverse_expression(traverse, &this->call_);
1756 }
1757
1758 // We implement traverse_assignment for a thunk statement because it
1759 // effectively copies the function call.
1760
1761 bool
1762 Thunk_statement::do_traverse_assignments(Traverse_assignments* tassign)
1763 {
1764   Expression* fn = this->call_->call_expression()->fn();
1765   Expression* fn2 = fn;
1766   tassign->value(&fn2, true, false);
1767   return true;
1768 }
1769
1770 // Determine types in a thunk statement.
1771
1772 void
1773 Thunk_statement::do_determine_types()
1774 {
1775   this->call_->determine_type_no_context();
1776
1777   // Now that we know the types of the call, build the struct used to
1778   // pass parameters.
1779   Call_expression* ce = this->call_->call_expression();
1780   if (ce == NULL)
1781     return;
1782   Function_type* fntype = ce->get_function_type();
1783   if (fntype != NULL && !this->is_simple(fntype))
1784     this->struct_type_ = this->build_struct(fntype);
1785 }
1786
1787 // Check types in a thunk statement.
1788
1789 void
1790 Thunk_statement::do_check_types(Gogo*)
1791 {
1792   Call_expression* ce = this->call_->call_expression();
1793   if (ce == NULL)
1794     {
1795       if (!this->call_->is_error_expression())
1796         this->report_error("expected call expression");
1797       return;
1798     }
1799   Function_type* fntype = ce->get_function_type();
1800   if (fntype != NULL && fntype->is_method())
1801     {
1802       Expression* fn = ce->fn();
1803       if (fn->bound_method_expression() == NULL
1804           && fn->interface_field_reference_expression() == NULL)
1805         this->report_error(_("no object for method call"));
1806     }
1807 }
1808
1809 // The Traverse class used to find and simplify thunk statements.
1810
1811 class Simplify_thunk_traverse : public Traverse
1812 {
1813  public:
1814   Simplify_thunk_traverse(Gogo* gogo)
1815     : Traverse(traverse_blocks),
1816       gogo_(gogo)
1817   { }
1818
1819   int
1820   block(Block*);
1821
1822  private:
1823   Gogo* gogo_;
1824 };
1825
1826 int
1827 Simplify_thunk_traverse::block(Block* b)
1828 {
1829   // The parser ensures that thunk statements always appear at the end
1830   // of a block.
1831   if (b->statements()->size() < 1)
1832     return TRAVERSE_CONTINUE;
1833   Thunk_statement* stat = b->statements()->back()->thunk_statement();
1834   if (stat == NULL)
1835     return TRAVERSE_CONTINUE;
1836   if (stat->simplify_statement(this->gogo_, b))
1837     return TRAVERSE_SKIP_COMPONENTS;
1838   return TRAVERSE_CONTINUE;
1839 }
1840
1841 // Simplify all thunk statements.
1842
1843 void
1844 Gogo::simplify_thunk_statements()
1845 {
1846   Simplify_thunk_traverse thunk_traverse(this);
1847   this->traverse(&thunk_traverse);
1848 }
1849
1850 // Simplify complex thunk statements into simple ones.  A complicated
1851 // thunk statement is one which takes anything other than zero
1852 // parameters or a single pointer parameter.  We rewrite it into code
1853 // which allocates a struct, stores the parameter values into the
1854 // struct, and does a simple go or defer statement which passes the
1855 // struct to a thunk.  The thunk does the real call.
1856
1857 bool
1858 Thunk_statement::simplify_statement(Gogo* gogo, Block* block)
1859 {
1860   if (this->classification() == STATEMENT_ERROR)
1861     return false;
1862   if (this->call_->is_error_expression())
1863     return false;
1864
1865   Call_expression* ce = this->call_->call_expression();
1866   Function_type* fntype = ce->get_function_type();
1867   if (fntype == NULL)
1868     {
1869       gcc_assert(saw_errors());
1870       this->set_is_error();
1871       return false;
1872     }
1873   if (this->is_simple(fntype))
1874     return false;
1875
1876   Expression* fn = ce->fn();
1877   Bound_method_expression* bound_method = fn->bound_method_expression();
1878   Interface_field_reference_expression* interface_method =
1879     fn->interface_field_reference_expression();
1880   const bool is_method = bound_method != NULL || interface_method != NULL;
1881
1882   source_location location = this->location();
1883
1884   std::string thunk_name = Gogo::thunk_name();
1885
1886   // Build the thunk.
1887   this->build_thunk(gogo, thunk_name, fntype);
1888
1889   // Generate code to call the thunk.
1890
1891   // Get the values to store into the struct which is the single
1892   // argument to the thunk.
1893
1894   Expression_list* vals = new Expression_list();
1895   if (fntype->is_builtin())
1896     ;
1897   else if (!is_method)
1898     vals->push_back(fn);
1899   else if (interface_method != NULL)
1900     vals->push_back(interface_method->expr());
1901   else if (bound_method != NULL)
1902     {
1903       vals->push_back(bound_method->method());
1904       Expression* first_arg = bound_method->first_argument();
1905
1906       // We always pass a pointer when calling a method.
1907       if (first_arg->type()->points_to() == NULL)
1908         first_arg = Expression::make_unary(OPERATOR_AND, first_arg, location);
1909
1910       // If we are calling a method which was inherited from an
1911       // embedded struct, and the method did not get a stub, then the
1912       // first type may be wrong.
1913       Type* fatype = bound_method->first_argument_type();
1914       if (fatype != NULL)
1915         {
1916           if (fatype->points_to() == NULL)
1917             fatype = Type::make_pointer_type(fatype);
1918           Type* unsafe = Type::make_pointer_type(Type::make_void_type());
1919           first_arg = Expression::make_cast(unsafe, first_arg, location);
1920           first_arg = Expression::make_cast(fatype, first_arg, location);
1921         }
1922
1923       vals->push_back(first_arg);
1924     }
1925   else
1926     gcc_unreachable();
1927
1928   if (ce->args() != NULL)
1929     {
1930       for (Expression_list::const_iterator p = ce->args()->begin();
1931            p != ce->args()->end();
1932            ++p)
1933         vals->push_back(*p);
1934     }
1935
1936   // Build the struct.
1937   Expression* constructor =
1938     Expression::make_struct_composite_literal(this->struct_type_, vals,
1939                                               location);
1940
1941   // Allocate the initialized struct on the heap.
1942   constructor = Expression::make_heap_composite(constructor, location);
1943
1944   // Look up the thunk.
1945   Named_object* named_thunk = gogo->lookup(thunk_name, NULL);
1946   gcc_assert(named_thunk != NULL && named_thunk->is_function());
1947
1948   // Build the call.
1949   Expression* func = Expression::make_func_reference(named_thunk, NULL,
1950                                                      location);
1951   Expression_list* params = new Expression_list();
1952   params->push_back(constructor);
1953   Call_expression* call = Expression::make_call(func, params, false, location);
1954
1955   // Build the simple go or defer statement.
1956   Statement* s;
1957   if (this->classification() == STATEMENT_GO)
1958     s = Statement::make_go_statement(call, location);
1959   else if (this->classification() == STATEMENT_DEFER)
1960     s = Statement::make_defer_statement(call, location);
1961   else
1962     gcc_unreachable();
1963
1964   // The current block should end with the go statement.
1965   gcc_assert(block->statements()->size() >= 1);
1966   gcc_assert(block->statements()->back() == this);
1967   block->replace_statement(block->statements()->size() - 1, s);
1968
1969   // We already ran the determine_types pass, so we need to run it now
1970   // for the new statement.
1971   s->determine_types();
1972
1973   // Sanity check.
1974   gogo->check_types_in_block(block);
1975
1976   // Return true to tell the block not to keep looking at statements.
1977   return true;
1978 }
1979
1980 // Set the name to use for thunk parameter N.
1981
1982 void
1983 Thunk_statement::thunk_field_param(int n, char* buf, size_t buflen)
1984 {
1985   snprintf(buf, buflen, "a%d", n);
1986 }
1987
1988 // Build a new struct type to hold the parameters for a complicated
1989 // thunk statement.  FNTYPE is the type of the function call.
1990
1991 Struct_type*
1992 Thunk_statement::build_struct(Function_type* fntype)
1993 {
1994   source_location location = this->location();
1995
1996   Struct_field_list* fields = new Struct_field_list();
1997
1998   Call_expression* ce = this->call_->call_expression();
1999   Expression* fn = ce->fn();
2000
2001   Interface_field_reference_expression* interface_method =
2002     fn->interface_field_reference_expression();
2003   if (interface_method != NULL)
2004     {
2005       // If this thunk statement calls a method on an interface, we
2006       // pass the interface object to the thunk.
2007       Typed_identifier tid(Thunk_statement::thunk_field_fn,
2008                            interface_method->expr()->type(),
2009                            location);
2010       fields->push_back(Struct_field(tid));
2011     }
2012   else if (!fntype->is_builtin())
2013     {
2014       // The function to call.
2015       Typed_identifier tid(Go_statement::thunk_field_fn, fntype, location);
2016       fields->push_back(Struct_field(tid));
2017     }
2018   else if (ce->is_recover_call())
2019     {
2020       // The predeclared recover function has no argument.  However,
2021       // we add an argument when building recover thunks.  Handle that
2022       // here.
2023       fields->push_back(Struct_field(Typed_identifier("can_recover",
2024                                                       Type::make_boolean_type(),
2025                                                       location)));
2026     }
2027
2028   if (fn->bound_method_expression() != NULL)
2029     {
2030       gcc_assert(fntype->is_method());
2031       Type* rtype = fntype->receiver()->type();
2032       // We always pass the receiver as a pointer.
2033       if (rtype->points_to() == NULL)
2034         rtype = Type::make_pointer_type(rtype);
2035       Typed_identifier tid(Thunk_statement::thunk_field_receiver, rtype,
2036                            location);
2037       fields->push_back(Struct_field(tid));
2038     }
2039
2040   const Expression_list* args = ce->args();
2041   if (args != NULL)
2042     {
2043       int i = 0;
2044       for (Expression_list::const_iterator p = args->begin();
2045            p != args->end();
2046            ++p, ++i)
2047         {
2048           char buf[50];
2049           this->thunk_field_param(i, buf, sizeof buf);
2050           fields->push_back(Struct_field(Typed_identifier(buf, (*p)->type(),
2051                                                           location)));
2052         }
2053     }
2054
2055   return Type::make_struct_type(fields, location);
2056 }
2057
2058 // Build the thunk we are going to call.  This is a brand new, albeit
2059 // artificial, function.
2060
2061 void
2062 Thunk_statement::build_thunk(Gogo* gogo, const std::string& thunk_name,
2063                              Function_type* fntype)
2064 {
2065   source_location location = this->location();
2066
2067   Call_expression* ce = this->call_->call_expression();
2068
2069   bool may_call_recover = false;
2070   if (this->classification() == STATEMENT_DEFER)
2071     {
2072       Func_expression* fn = ce->fn()->func_expression();
2073       if (fn == NULL)
2074         may_call_recover = true;
2075       else
2076         {
2077           const Named_object* no = fn->named_object();
2078           if (!no->is_function())
2079             may_call_recover = true;
2080           else
2081             may_call_recover = no->func_value()->calls_recover();
2082         }
2083     }
2084
2085   // Build the type of the thunk.  The thunk takes a single parameter,
2086   // which is a pointer to the special structure we build.
2087   const char* const parameter_name = "__go_thunk_parameter";
2088   Typed_identifier_list* thunk_parameters = new Typed_identifier_list();
2089   Type* pointer_to_struct_type = Type::make_pointer_type(this->struct_type_);
2090   thunk_parameters->push_back(Typed_identifier(parameter_name,
2091                                                pointer_to_struct_type,
2092                                                location));
2093
2094   Typed_identifier_list* thunk_results = NULL;
2095   if (may_call_recover)
2096     {
2097       // When deferring a function which may call recover, add a
2098       // return value, to disable tail call optimizations which will
2099       // break the way we check whether recover is permitted.
2100       thunk_results = new Typed_identifier_list();
2101       thunk_results->push_back(Typed_identifier("", Type::make_boolean_type(),
2102                                                 location));
2103     }
2104
2105   Function_type* thunk_type = Type::make_function_type(NULL, thunk_parameters,
2106                                                        thunk_results,
2107                                                        location);
2108
2109   // Start building the thunk.
2110   Named_object* function = gogo->start_function(thunk_name, thunk_type, true,
2111                                                 location);
2112
2113   // For a defer statement, start with a call to
2114   // __go_set_defer_retaddr.  */
2115   Label* retaddr_label = NULL; 
2116   if (may_call_recover)
2117     {
2118       retaddr_label = gogo->add_label_reference("retaddr");
2119       Expression* arg = Expression::make_label_addr(retaddr_label, location);
2120       Expression_list* args = new Expression_list();
2121       args->push_back(arg);
2122
2123       static Named_object* set_defer_retaddr;
2124       if (set_defer_retaddr == NULL)
2125         {
2126           const source_location bloc = BUILTINS_LOCATION;
2127           Typed_identifier_list* param_types = new Typed_identifier_list();
2128           Type *voidptr_type = Type::make_pointer_type(Type::make_void_type());
2129           param_types->push_back(Typed_identifier("r", voidptr_type, bloc));
2130
2131           Typed_identifier_list* result_types = new Typed_identifier_list();
2132           result_types->push_back(Typed_identifier("",
2133                                                    Type::make_boolean_type(),
2134                                                    bloc));
2135
2136           Function_type* t = Type::make_function_type(NULL, param_types,
2137                                                       result_types, bloc);
2138           set_defer_retaddr =
2139             Named_object::make_function_declaration("__go_set_defer_retaddr",
2140                                                     NULL, t, bloc);
2141           const char* n = "__go_set_defer_retaddr";
2142           set_defer_retaddr->func_declaration_value()->set_asm_name(n);
2143         }
2144
2145       Expression* fn = Expression::make_func_reference(set_defer_retaddr,
2146                                                        NULL, location);
2147       Expression* call = Expression::make_call(fn, args, false, location);
2148
2149       // This is a hack to prevent the middle-end from deleting the
2150       // label.
2151       gogo->start_block(location);
2152       gogo->add_statement(Statement::make_goto_statement(retaddr_label,
2153                                                          location));
2154       Block* then_block = gogo->finish_block(location);
2155       then_block->determine_types();
2156
2157       Statement* s = Statement::make_if_statement(call, then_block, NULL,
2158                                                   location);
2159       s->determine_types();
2160       gogo->add_statement(s);
2161     }
2162
2163   // Get a reference to the parameter.
2164   Named_object* named_parameter = gogo->lookup(parameter_name, NULL);
2165   gcc_assert(named_parameter != NULL && named_parameter->is_variable());
2166
2167   // Build the call.  Note that the field names are the same as the
2168   // ones used in build_struct.
2169   Expression* thunk_parameter = Expression::make_var_reference(named_parameter,
2170                                                                location);
2171   thunk_parameter = Expression::make_unary(OPERATOR_MULT, thunk_parameter,
2172                                            location);
2173
2174   Bound_method_expression* bound_method = ce->fn()->bound_method_expression();
2175   Interface_field_reference_expression* interface_method =
2176     ce->fn()->interface_field_reference_expression();
2177
2178   Expression* func_to_call;
2179   unsigned int next_index;
2180   if (!fntype->is_builtin())
2181     {
2182       func_to_call = Expression::make_field_reference(thunk_parameter,
2183                                                       0, location);
2184       next_index = 1;
2185     }
2186   else
2187     {
2188       gcc_assert(bound_method == NULL && interface_method == NULL);
2189       func_to_call = ce->fn();
2190       next_index = 0;
2191     }
2192
2193   if (bound_method != NULL)
2194     {
2195       Expression* r = Expression::make_field_reference(thunk_parameter, 1,
2196                                                        location);
2197       // The main program passes in a function pointer from the
2198       // interface expression, so here we can make a bound method in
2199       // all cases.
2200       func_to_call = Expression::make_bound_method(r, func_to_call,
2201                                                    location);
2202       next_index = 2;
2203     }
2204   else if (interface_method != NULL)
2205     {
2206       // The main program passes the interface object.
2207       const std::string& name(interface_method->name());
2208       func_to_call = Expression::make_interface_field_reference(func_to_call,
2209                                                                 name,
2210                                                                 location);
2211     }
2212
2213   Expression_list* call_params = new Expression_list();
2214   const Struct_field_list* fields = this->struct_type_->fields();
2215   Struct_field_list::const_iterator p = fields->begin();
2216   for (unsigned int i = 0; i < next_index; ++i)
2217     ++p;
2218   bool is_recover_call = ce->is_recover_call();
2219   Expression* recover_arg = NULL;
2220   for (; p != fields->end(); ++p, ++next_index)
2221     {
2222       Expression* thunk_param = Expression::make_var_reference(named_parameter,
2223                                                                location);
2224       thunk_param = Expression::make_unary(OPERATOR_MULT, thunk_param,
2225                                            location);
2226       Expression* param = Expression::make_field_reference(thunk_param,
2227                                                            next_index,
2228                                                            location);
2229       if (!is_recover_call)
2230         call_params->push_back(param);
2231       else
2232         {
2233           gcc_assert(call_params->empty());
2234           recover_arg = param;
2235         }
2236     }
2237
2238   if (call_params->empty())
2239     {
2240       delete call_params;
2241       call_params = NULL;
2242     }
2243
2244   Expression* call = Expression::make_call(func_to_call, call_params, false,
2245                                            location);
2246   // We need to lower in case this is a builtin function.
2247   call = call->lower(gogo, function, -1);
2248   Call_expression* call_ce = call->call_expression();
2249   if (call_ce != NULL && may_call_recover)
2250     call_ce->set_is_deferred();
2251
2252   Statement* call_statement = Statement::make_statement(call);
2253
2254   // We already ran the determine_types pass, so we need to run it
2255   // just for this statement now.
2256   call_statement->determine_types();
2257
2258   // Sanity check.
2259   call->check_types(gogo);
2260
2261   if (call_ce != NULL && recover_arg != NULL)
2262     call_ce->set_recover_arg(recover_arg);
2263
2264   gogo->add_statement(call_statement);
2265
2266   // If this is a defer statement, the label comes immediately after
2267   // the call.
2268   if (may_call_recover)
2269     {
2270       gogo->add_label_definition("retaddr", location);
2271
2272       Expression_list* vals = new Expression_list();
2273       vals->push_back(Expression::make_boolean(false, location));
2274       const Typed_identifier_list* results =
2275         function->func_value()->type()->results();
2276       gogo->add_statement(Statement::make_return_statement(results, vals,
2277                                                           location));
2278     }
2279
2280   // That is all the thunk has to do.
2281   gogo->finish_function(location);
2282 }
2283
2284 // Get the function and argument trees.
2285
2286 void
2287 Thunk_statement::get_fn_and_arg(Translate_context* context, tree* pfn,
2288                                 tree* parg)
2289 {
2290   if (this->call_->is_error_expression())
2291     {
2292       *pfn = error_mark_node;
2293       *parg = error_mark_node;
2294       return;
2295     }
2296
2297   Call_expression* ce = this->call_->call_expression();
2298
2299   Expression* fn = ce->fn();
2300   *pfn = fn->get_tree(context);
2301
2302   const Expression_list* args = ce->args();
2303   if (args == NULL || args->empty())
2304     *parg = null_pointer_node;
2305   else
2306     {
2307       gcc_assert(args->size() == 1);
2308       *parg = args->front()->get_tree(context);
2309     }
2310 }
2311
2312 // Class Go_statement.
2313
2314 tree
2315 Go_statement::do_get_tree(Translate_context* context)
2316 {
2317   tree fn_tree;
2318   tree arg_tree;
2319   this->get_fn_and_arg(context, &fn_tree, &arg_tree);
2320
2321   static tree go_fndecl;
2322
2323   tree fn_arg_type = NULL_TREE;
2324   if (go_fndecl == NULL_TREE)
2325     {
2326       // Only build FN_ARG_TYPE if we need it.
2327       tree subargtypes = tree_cons(NULL_TREE, ptr_type_node, void_list_node);
2328       tree subfntype = build_function_type(ptr_type_node, subargtypes);
2329       fn_arg_type = build_pointer_type(subfntype);
2330     }
2331
2332   return Gogo::call_builtin(&go_fndecl,
2333                             this->location(),
2334                             "__go_go",
2335                             2,
2336                             void_type_node,
2337                             fn_arg_type,
2338                             fn_tree,
2339                             ptr_type_node,
2340                             arg_tree);
2341 }
2342
2343 // Make a go statement.
2344
2345 Statement*
2346 Statement::make_go_statement(Call_expression* call, source_location location)
2347 {
2348   return new Go_statement(call, location);
2349 }
2350
2351 // Class Defer_statement.
2352
2353 tree
2354 Defer_statement::do_get_tree(Translate_context* context)
2355 {
2356   source_location loc = this->location();
2357
2358   tree fn_tree;
2359   tree arg_tree;
2360   this->get_fn_and_arg(context, &fn_tree, &arg_tree);
2361   if (fn_tree == error_mark_node || arg_tree == error_mark_node)
2362     return error_mark_node;
2363
2364   static tree defer_fndecl;
2365
2366   tree fn_arg_type = NULL_TREE;
2367   if (defer_fndecl == NULL_TREE)
2368     {
2369       // Only build FN_ARG_TYPE if we need it.
2370       tree subargtypes = tree_cons(NULL_TREE, ptr_type_node, void_list_node);
2371       tree subfntype = build_function_type(ptr_type_node, subargtypes);
2372       fn_arg_type = build_pointer_type(subfntype);
2373     }
2374
2375   tree defer_stack = context->function()->func_value()->defer_stack(loc);
2376
2377   return Gogo::call_builtin(&defer_fndecl,
2378                             loc,
2379                             "__go_defer",
2380                             3,
2381                             void_type_node,
2382                             ptr_type_node,
2383                             defer_stack,
2384                             fn_arg_type,
2385                             fn_tree,
2386                             ptr_type_node,
2387                             arg_tree);
2388 }
2389
2390 // Make a defer statement.
2391
2392 Statement*
2393 Statement::make_defer_statement(Call_expression* call,
2394                                 source_location location)
2395 {
2396   return new Defer_statement(call, location);
2397 }
2398
2399 // Class Return_statement.
2400
2401 // Traverse assignments.  We treat each return value as a top level
2402 // RHS in an expression.
2403
2404 bool
2405 Return_statement::do_traverse_assignments(Traverse_assignments* tassign)
2406 {
2407   Expression_list* vals = this->vals_;
2408   if (vals != NULL)
2409     {
2410       for (Expression_list::iterator p = vals->begin();
2411            p != vals->end();
2412            ++p)
2413         tassign->value(&*p, true, true);
2414     }
2415   return true;
2416 }
2417
2418 // Lower a return statement.  If we are returning a function call
2419 // which returns multiple values which match the current function,
2420 // split up the call's results.  If the function has named result
2421 // variables, and the return statement lists explicit values, then
2422 // implement it by assigning the values to the result variables and
2423 // changing the statement to not list any values.  This lets
2424 // panic/recover work correctly.
2425
2426 Statement*
2427 Return_statement::do_lower(Gogo*, Block* enclosing)
2428 {
2429   if (this->vals_ == NULL)
2430     return this;
2431
2432   const Typed_identifier_list* results = this->results_;
2433   if (results == NULL || results->empty())
2434     return this;
2435
2436   // If the current function has multiple return values, and we are
2437   // returning a single call expression, split up the call expression.
2438   size_t results_count = results->size();
2439   if (results_count > 1
2440       && this->vals_->size() == 1
2441       && this->vals_->front()->call_expression() != NULL)
2442     {
2443       Call_expression* call = this->vals_->front()->call_expression();
2444       size_t count = results->size();
2445       Expression_list* vals = new Expression_list;
2446       for (size_t i = 0; i < count; ++i)
2447         vals->push_back(Expression::make_call_result(call, i));
2448       delete this->vals_;
2449       this->vals_ = vals;
2450     }
2451
2452   if (results->front().name().empty())
2453     return this;
2454
2455   if (results_count != this->vals_->size())
2456     {
2457       // Presumably an error which will be reported in check_types.
2458       return this;
2459     }
2460
2461   // Assign to named return values and then return them.
2462
2463   source_location loc = this->location();
2464   const Block* top = enclosing;
2465   while (top->enclosing() != NULL)
2466     top = top->enclosing();
2467
2468   const Bindings *bindings = top->bindings();
2469   Block* b = new Block(enclosing, loc);
2470
2471   Expression_list* lhs = new Expression_list();
2472   Expression_list* rhs = new Expression_list();
2473
2474   Expression_list::const_iterator pe = this->vals_->begin();
2475   int i = 1;
2476   for (Typed_identifier_list::const_iterator pr = results->begin();
2477        pr != results->end();
2478        ++pr, ++pe, ++i)
2479     {
2480       Named_object* rv = bindings->lookup_local(pr->name());
2481       if (rv == NULL || !rv->is_result_variable())
2482         {
2483           // Presumably an error.
2484           delete b;
2485           delete lhs;
2486           delete rhs;
2487           return this;
2488         }
2489
2490       Expression* e = *pe;
2491
2492       // Check types now so that we give a good error message.  The
2493       // result type is known.  We determine the expression type
2494       // early.
2495
2496       Type *rvtype = rv->result_var_value()->type();
2497       Type_context type_context(rvtype, false);
2498       e->determine_type(&type_context);
2499
2500       std::string reason;
2501       if (Type::are_assignable(rvtype, e->type(), &reason))
2502         {
2503           Expression* ve = Expression::make_var_reference(rv, e->location());
2504           lhs->push_back(ve);
2505           rhs->push_back(e);
2506         }
2507       else
2508         {
2509           if (reason.empty())
2510             error_at(e->location(), "incompatible type for return value %d", i);
2511           else
2512             error_at(e->location(),
2513                      "incompatible type for return value %d (%s)",
2514                      i, reason.c_str());
2515         }
2516     }
2517   gcc_assert(lhs->size() == rhs->size());
2518
2519   if (lhs->empty())
2520     ;
2521   else if (lhs->size() == 1)
2522     {
2523       b->add_statement(Statement::make_assignment(lhs->front(), rhs->front(),
2524                                                   loc));
2525       delete lhs;
2526       delete rhs;
2527     }
2528   else
2529     b->add_statement(Statement::make_tuple_assignment(lhs, rhs, loc));
2530
2531   b->add_statement(Statement::make_return_statement(this->results_, NULL,
2532                                                     loc));
2533
2534   return Statement::make_block_statement(b, loc);
2535 }
2536
2537 // Determine types.
2538
2539 void
2540 Return_statement::do_determine_types()
2541 {
2542   if (this->vals_ == NULL)
2543     return;
2544   const Typed_identifier_list* results = this->results_;
2545
2546   Typed_identifier_list::const_iterator pt;
2547   if (results != NULL)
2548     pt = results->begin();
2549   for (Expression_list::iterator pe = this->vals_->begin();
2550        pe != this->vals_->end();
2551        ++pe)
2552     {
2553       if (results == NULL || pt == results->end())
2554         (*pe)->determine_type_no_context();
2555       else
2556         {
2557           Type_context context(pt->type(), false);
2558           (*pe)->determine_type(&context);
2559           ++pt;
2560         }
2561     }
2562 }
2563
2564 // Check types.
2565
2566 void
2567 Return_statement::do_check_types(Gogo*)
2568 {
2569   if (this->vals_ == NULL)
2570     return;
2571
2572   const Typed_identifier_list* results = this->results_;
2573   if (results == NULL)
2574     {
2575       this->report_error(_("return with value in function "
2576                            "with no return type"));
2577       return;
2578     }
2579
2580   int i = 1;
2581   Typed_identifier_list::const_iterator pt = results->begin();
2582   for (Expression_list::const_iterator pe = this->vals_->begin();
2583        pe != this->vals_->end();
2584        ++pe, ++pt, ++i)
2585     {
2586       if (pt == results->end())
2587         {
2588           this->report_error(_("too many values in return statement"));
2589           return;
2590         }
2591       std::string reason;
2592       if (!Type::are_assignable(pt->type(), (*pe)->type(), &reason))
2593         {
2594           if (reason.empty())
2595             error_at(this->location(),
2596                      "incompatible type for return value %d",
2597                      i);
2598           else
2599             error_at(this->location(),
2600                      "incompatible type for return value %d (%s)",
2601                      i, reason.c_str());
2602           this->set_is_error();
2603         }
2604       else if (pt->type()->is_error_type()
2605                || (*pe)->type()->is_error_type()
2606                || pt->type()->is_undefined()
2607                || (*pe)->type()->is_undefined())
2608         {
2609           // Make sure we get the error for an undefined type.
2610           pt->type()->base();
2611           (*pe)->type()->base();
2612           this->set_is_error();
2613         }
2614     }
2615
2616   if (pt != results->end())
2617     this->report_error(_("not enough values in return statement"));
2618 }
2619
2620 // Build a RETURN_EXPR tree.
2621
2622 tree
2623 Return_statement::do_get_tree(Translate_context* context)
2624 {
2625   Function* function = context->function()->func_value();
2626   tree fndecl = function->get_decl();
2627   if (fndecl == error_mark_node || DECL_RESULT(fndecl) == error_mark_node)
2628     return error_mark_node;
2629
2630   const Typed_identifier_list* results = this->results_;
2631
2632   if (this->vals_ == NULL)
2633     {
2634       tree stmt_list = NULL_TREE;
2635       tree retval = function->return_value(context->gogo(),
2636                                            context->function(),
2637                                            this->location(),
2638                                            &stmt_list);
2639       tree set;
2640       if (retval == NULL_TREE)
2641         set = NULL_TREE;
2642       else if (retval == error_mark_node)
2643         return error_mark_node;
2644       else
2645         set = fold_build2_loc(this->location(), MODIFY_EXPR, void_type_node,
2646                               DECL_RESULT(fndecl), retval);
2647       append_to_statement_list(this->build_stmt_1(RETURN_EXPR, set),
2648                                &stmt_list);
2649       return stmt_list;
2650     }
2651   else if (this->vals_->size() == 1)
2652     {
2653       gcc_assert(!VOID_TYPE_P(TREE_TYPE(TREE_TYPE(fndecl))));
2654       tree val = (*this->vals_->begin())->get_tree(context);
2655       gcc_assert(results != NULL && results->size() == 1);
2656       val = Expression::convert_for_assignment(context,
2657                                                results->begin()->type(),
2658                                                (*this->vals_->begin())->type(),
2659                                                val, this->location());
2660       if (val == error_mark_node)
2661         return error_mark_node;
2662       tree set = build2(MODIFY_EXPR, void_type_node,
2663                         DECL_RESULT(fndecl), val);
2664       SET_EXPR_LOCATION(set, this->location());
2665       return this->build_stmt_1(RETURN_EXPR, set);
2666     }
2667   else
2668     {
2669       gcc_assert(!VOID_TYPE_P(TREE_TYPE(TREE_TYPE(fndecl))));
2670       tree stmt_list = NULL_TREE;
2671       tree rettype = TREE_TYPE(DECL_RESULT(fndecl));
2672       tree retvar = create_tmp_var(rettype, "RESULT");
2673       gcc_assert(results != NULL && results->size() == this->vals_->size());
2674       Expression_list::const_iterator pv = this->vals_->begin();
2675       Typed_identifier_list::const_iterator pr = results->begin();
2676       for (tree field = TYPE_FIELDS(rettype);
2677            field != NULL_TREE;
2678            ++pv, ++pr, field = DECL_CHAIN(field))
2679         {
2680           gcc_assert(pv != this->vals_->end());
2681           tree val = (*pv)->get_tree(context);
2682           val = Expression::convert_for_assignment(context, pr->type(),
2683                                                    (*pv)->type(), val,
2684                                                    this->location());
2685           if (val == error_mark_node)
2686             return error_mark_node;
2687           tree set = build2(MODIFY_EXPR, void_type_node,
2688                             build3(COMPONENT_REF, TREE_TYPE(field),
2689                                    retvar, field, NULL_TREE),
2690                             val);
2691           SET_EXPR_LOCATION(set, this->location());
2692           append_to_statement_list(set, &stmt_list);
2693         }
2694       tree set = build2(MODIFY_EXPR, void_type_node, DECL_RESULT(fndecl),
2695                         retvar);
2696       append_to_statement_list(this->build_stmt_1(RETURN_EXPR, set),
2697                                &stmt_list);
2698       return stmt_list;
2699     }
2700 }
2701
2702 // Make a return statement.
2703
2704 Statement*
2705 Statement::make_return_statement(const Typed_identifier_list* results,
2706                                  Expression_list* vals,
2707                                  source_location location)
2708 {
2709   return new Return_statement(results, vals, location);
2710 }
2711
2712 // A break or continue statement.
2713
2714 class Bc_statement : public Statement
2715 {
2716  public:
2717   Bc_statement(bool is_break, Unnamed_label* label, source_location location)
2718     : Statement(STATEMENT_BREAK_OR_CONTINUE, location),
2719       label_(label), is_break_(is_break)
2720   { }
2721
2722   bool
2723   is_break() const
2724   { return this->is_break_; }
2725
2726  protected:
2727   int
2728   do_traverse(Traverse*)
2729   { return TRAVERSE_CONTINUE; }
2730
2731   bool
2732   do_may_fall_through() const
2733   { return false; }
2734
2735   tree
2736   do_get_tree(Translate_context*)
2737   { return this->label_->get_goto(this->location()); }
2738
2739  private:
2740   // The label that this branches to.
2741   Unnamed_label* label_;
2742   // True if this is "break", false if it is "continue".
2743   bool is_break_;
2744 };
2745
2746 // Make a break statement.
2747
2748 Statement*
2749 Statement::make_break_statement(Unnamed_label* label, source_location location)
2750 {
2751   return new Bc_statement(true, label, location);
2752 }
2753
2754 // Make a continue statement.
2755
2756 Statement*
2757 Statement::make_continue_statement(Unnamed_label* label,
2758                                    source_location location)
2759 {
2760   return new Bc_statement(false, label, location);
2761 }
2762
2763 // A goto statement.
2764
2765 class Goto_statement : public Statement
2766 {
2767  public:
2768   Goto_statement(Label* label, source_location location)
2769     : Statement(STATEMENT_GOTO, location),
2770       label_(label)
2771   { }
2772
2773  protected:
2774   int
2775   do_traverse(Traverse*)
2776   { return TRAVERSE_CONTINUE; }
2777
2778   void
2779   do_check_types(Gogo*);
2780
2781   bool
2782   do_may_fall_through() const
2783   { return false; }
2784
2785   tree
2786   do_get_tree(Translate_context*);
2787
2788  private:
2789   Label* label_;
2790 };
2791
2792 // Check types for a label.  There aren't any types per se, but we use
2793 // this to give an error if the label was never defined.
2794
2795 void
2796 Goto_statement::do_check_types(Gogo*)
2797 {
2798   if (!this->label_->is_defined())
2799     {
2800       error_at(this->location(), "reference to undefined label %qs",
2801                Gogo::message_name(this->label_->name()).c_str());
2802       this->set_is_error();
2803     }
2804 }
2805
2806 // Return the tree for the goto statement.
2807
2808 tree
2809 Goto_statement::do_get_tree(Translate_context*)
2810 {
2811   return this->build_stmt_1(GOTO_EXPR, this->label_->get_decl());
2812 }
2813
2814 // Make a goto statement.
2815
2816 Statement*
2817 Statement::make_goto_statement(Label* label, source_location location)
2818 {
2819   return new Goto_statement(label, location);
2820 }
2821
2822 // A goto statement to an unnamed label.
2823
2824 class Goto_unnamed_statement : public Statement
2825 {
2826  public:
2827   Goto_unnamed_statement(Unnamed_label* label, source_location location)
2828     : Statement(STATEMENT_GOTO_UNNAMED, location),
2829       label_(label)
2830   { }
2831
2832  protected:
2833   int
2834   do_traverse(Traverse*)
2835   { return TRAVERSE_CONTINUE; }
2836
2837   bool
2838   do_may_fall_through() const
2839   { return false; }
2840
2841   tree
2842   do_get_tree(Translate_context*)
2843   { return this->label_->get_goto(this->location()); }
2844
2845  private:
2846   Unnamed_label* label_;
2847 };
2848
2849 // Make a goto statement to an unnamed label.
2850
2851 Statement*
2852 Statement::make_goto_unnamed_statement(Unnamed_label* label,
2853                                        source_location location)
2854 {
2855   return new Goto_unnamed_statement(label, location);
2856 }
2857
2858 // Class Label_statement.
2859
2860 // Traversal.
2861
2862 int
2863 Label_statement::do_traverse(Traverse*)
2864 {
2865   return TRAVERSE_CONTINUE;
2866 }
2867
2868 // Return a tree defining this label.
2869
2870 tree
2871 Label_statement::do_get_tree(Translate_context*)
2872 {
2873   return this->build_stmt_1(LABEL_EXPR, this->label_->get_decl());
2874 }
2875
2876 // Make a label statement.
2877
2878 Statement*
2879 Statement::make_label_statement(Label* label, source_location location)
2880 {
2881   return new Label_statement(label, location);
2882 }
2883
2884 // An unnamed label statement.
2885
2886 class Unnamed_label_statement : public Statement
2887 {
2888  public:
2889   Unnamed_label_statement(Unnamed_label* label)
2890     : Statement(STATEMENT_UNNAMED_LABEL, label->location()),
2891       label_(label)
2892   { }
2893
2894  protected:
2895   int
2896   do_traverse(Traverse*)
2897   { return TRAVERSE_CONTINUE; }
2898
2899   tree
2900   do_get_tree(Translate_context*)
2901   { return this->label_->get_definition(); }
2902
2903  private:
2904   // The label.
2905   Unnamed_label* label_;
2906 };
2907
2908 // Make an unnamed label statement.
2909
2910 Statement*
2911 Statement::make_unnamed_label_statement(Unnamed_label* label)
2912 {
2913   return new Unnamed_label_statement(label);
2914 }
2915
2916 // An if statement.
2917
2918 class If_statement : public Statement
2919 {
2920  public:
2921   If_statement(Expression* cond, Block* then_block, Block* else_block,
2922                source_location location)
2923     : Statement(STATEMENT_IF, location),
2924       cond_(cond), then_block_(then_block), else_block_(else_block)
2925   { }
2926
2927  protected:
2928   int
2929   do_traverse(Traverse*);
2930
2931   void
2932   do_determine_types();
2933
2934   void
2935   do_check_types(Gogo*);
2936
2937   bool
2938   do_may_fall_through() const;
2939
2940   tree
2941   do_get_tree(Translate_context*);
2942
2943  private:
2944   Expression* cond_;
2945   Block* then_block_;
2946   Block* else_block_;
2947 };
2948
2949 // Traversal.
2950
2951 int
2952 If_statement::do_traverse(Traverse* traverse)
2953 {
2954   if (this->cond_ != NULL)
2955     {
2956       if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT)
2957         return TRAVERSE_EXIT;
2958     }
2959   if (this->then_block_->traverse(traverse) == TRAVERSE_EXIT)
2960     return TRAVERSE_EXIT;
2961   if (this->else_block_ != NULL)
2962     {
2963       if (this->else_block_->traverse(traverse) == TRAVERSE_EXIT)
2964         return TRAVERSE_EXIT;
2965     }
2966   return TRAVERSE_CONTINUE;
2967 }
2968
2969 void
2970 If_statement::do_determine_types()
2971 {
2972   if (this->cond_ != NULL)
2973     {
2974       Type_context context(Type::lookup_bool_type(), false);
2975       this->cond_->determine_type(&context);
2976     }
2977   this->then_block_->determine_types();
2978   if (this->else_block_ != NULL)
2979     this->else_block_->determine_types();
2980 }
2981
2982 // Check types.
2983
2984 void
2985 If_statement::do_check_types(Gogo*)
2986 {
2987   if (this->cond_ != NULL)
2988     {
2989       Type* type = this->cond_->type();
2990       if (type->is_error_type())
2991         this->set_is_error();
2992       else if (!type->is_boolean_type())
2993         this->report_error(_("expected boolean expression"));
2994     }
2995 }
2996
2997 // Whether the overall statement may fall through.
2998
2999 bool
3000 If_statement::do_may_fall_through() const
3001 {
3002   return (this->else_block_ == NULL
3003           || this->then_block_->may_fall_through()
3004           || this->else_block_->may_fall_through());
3005 }
3006
3007 // Get tree.
3008
3009 tree
3010 If_statement::do_get_tree(Translate_context* context)
3011 {
3012   gcc_assert(this->cond_ == NULL
3013              || this->cond_->type()->is_boolean_type()
3014              || this->cond_->type()->is_error_type());
3015   tree cond_tree = (this->cond_ == NULL
3016                     ? boolean_true_node
3017                     : this->cond_->get_tree(context));
3018   tree then_tree = this->then_block_->get_tree(context);
3019   tree else_tree = (this->else_block_ == NULL
3020                     ? NULL_TREE
3021                     : this->else_block_->get_tree(context));
3022   if (cond_tree == error_mark_node
3023       || then_tree == error_mark_node
3024       || else_tree == error_mark_node)
3025     return error_mark_node;
3026   tree ret = build3(COND_EXPR, void_type_node, cond_tree, then_tree,
3027                     else_tree);
3028   SET_EXPR_LOCATION(ret, this->location());
3029   return ret;
3030 }
3031
3032 // Make an if statement.
3033
3034 Statement*
3035 Statement::make_if_statement(Expression* cond, Block* then_block,
3036                              Block* else_block, source_location location)
3037 {
3038   return new If_statement(cond, then_block, else_block, location);
3039 }
3040
3041 // Class Case_clauses::Case_clause.
3042
3043 // Traversal.
3044
3045 int
3046 Case_clauses::Case_clause::traverse(Traverse* traverse)
3047 {
3048   if (this->cases_ != NULL
3049       && (traverse->traverse_mask()
3050           & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0)
3051     {
3052       if (this->cases_->traverse(traverse) == TRAVERSE_EXIT)
3053         return TRAVERSE_EXIT;
3054     }
3055   if (this->statements_ != NULL)
3056     {
3057       if (this->statements_->traverse(traverse) == TRAVERSE_EXIT)
3058         return TRAVERSE_EXIT;
3059     }
3060   return TRAVERSE_CONTINUE;
3061 }
3062
3063 // Check whether all the case expressions are integer constants.
3064
3065 bool
3066 Case_clauses::Case_clause::is_constant() const
3067 {
3068   if (this->cases_ != NULL)
3069     {
3070       for (Expression_list::const_iterator p = this->cases_->begin();
3071            p != this->cases_->end();
3072            ++p)
3073         if (!(*p)->is_constant() || (*p)->type()->integer_type() == NULL)
3074           return false;
3075     }
3076   return true;
3077 }
3078
3079 // Lower a case clause for a nonconstant switch.  VAL_TEMP is the
3080 // value we are switching on; it may be NULL.  If START_LABEL is not
3081 // NULL, it goes at the start of the statements, after the condition
3082 // test.  We branch to FINISH_LABEL at the end of the statements.
3083
3084 void
3085 Case_clauses::Case_clause::lower(Block* b, Temporary_statement* val_temp,
3086                                  Unnamed_label* start_label,
3087                                  Unnamed_label* finish_label) const
3088 {
3089   source_location loc = this->location_;
3090   Unnamed_label* next_case_label;
3091   if (this->cases_ == NULL || this->cases_->empty())
3092     {
3093       gcc_assert(this->is_default_);
3094       next_case_label = NULL;
3095     }
3096   else
3097     {
3098       Expression* cond = NULL;
3099
3100       for (Expression_list::const_iterator p = this->cases_->begin();
3101            p != this->cases_->end();
3102            ++p)
3103         {
3104           Expression* this_cond;
3105           if (val_temp == NULL)
3106             this_cond = *p;
3107           else
3108             {
3109               Expression* ref = Expression::make_temporary_reference(val_temp,
3110                                                                      loc);
3111               this_cond = Expression::make_binary(OPERATOR_EQEQ, ref, *p, loc);
3112             }
3113
3114           if (cond == NULL)
3115             cond = this_cond;
3116           else
3117             cond = Expression::make_binary(OPERATOR_OROR, cond, this_cond, loc);
3118         }
3119
3120       Block* then_block = new Block(b, loc);
3121       next_case_label = new Unnamed_label(UNKNOWN_LOCATION);
3122       Statement* s = Statement::make_goto_unnamed_statement(next_case_label,
3123                                                             loc);
3124       then_block->add_statement(s);
3125
3126       // if !COND { goto NEXT_CASE_LABEL }
3127       cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3128       s = Statement::make_if_statement(cond, then_block, NULL, loc);
3129       b->add_statement(s);
3130     }
3131
3132   if (start_label != NULL)
3133     b->add_statement(Statement::make_unnamed_label_statement(start_label));
3134
3135   if (this->statements_ != NULL)
3136     b->add_statement(Statement::make_block_statement(this->statements_, loc));
3137
3138   Statement* s = Statement::make_goto_unnamed_statement(finish_label, loc);
3139   b->add_statement(s);
3140
3141   if (next_case_label != NULL)
3142     b->add_statement(Statement::make_unnamed_label_statement(next_case_label));
3143 }
3144
3145 // Determine types.
3146
3147 void
3148 Case_clauses::Case_clause::determine_types(Type* type)
3149 {
3150   if (this->cases_ != NULL)
3151     {
3152       Type_context case_context(type, false);
3153       for (Expression_list::iterator p = this->cases_->begin();
3154            p != this->cases_->end();
3155            ++p)
3156         (*p)->determine_type(&case_context);
3157     }
3158   if (this->statements_ != NULL)
3159     this->statements_->determine_types();
3160 }
3161
3162 // Check types.  Returns false if there was an error.
3163
3164 bool
3165 Case_clauses::Case_clause::check_types(Type* type)
3166 {
3167   if (this->cases_ != NULL)
3168     {
3169       for (Expression_list::iterator p = this->cases_->begin();
3170            p != this->cases_->end();
3171            ++p)
3172         {
3173           if (!Type::are_assignable(type, (*p)->type(), NULL)
3174               && !Type::are_assignable((*p)->type(), type, NULL))
3175             {
3176               error_at((*p)->location(),
3177                        "type mismatch between switch value and case clause");
3178               return false;
3179             }
3180         }
3181     }
3182   return true;
3183 }
3184
3185 // Return true if this clause may fall through to the following
3186 // statements.  Note that this is not the same as whether the case
3187 // uses the "fallthrough" keyword.
3188
3189 bool
3190 Case_clauses::Case_clause::may_fall_through() const
3191 {
3192   if (this->statements_ == NULL)
3193     return true;
3194   return this->statements_->may_fall_through();
3195 }
3196
3197 // Build up the body of a SWITCH_EXPR.
3198
3199 void
3200 Case_clauses::Case_clause::get_constant_tree(Translate_context* context,
3201                                              Unnamed_label* break_label,
3202                                              Case_constants* case_constants,
3203                                              tree* stmt_list) const
3204 {
3205   if (this->cases_ != NULL)
3206     {
3207       for (Expression_list::const_iterator p = this->cases_->begin();
3208            p != this->cases_->end();
3209            ++p)
3210         {
3211           Type* itype;
3212           mpz_t ival;
3213           mpz_init(ival);
3214           if (!(*p)->integer_constant_value(true, ival, &itype))
3215             gcc_unreachable();
3216           gcc_assert(itype != NULL);
3217           tree type_tree = itype->get_tree(context->gogo());
3218           tree val = Expression::integer_constant_tree(ival, type_tree);
3219           mpz_clear(ival);
3220
3221           if (val != error_mark_node)
3222             {
3223               gcc_assert(TREE_CODE(val) == INTEGER_CST);
3224
3225               std::pair<Case_constants::iterator, bool> ins =
3226                 case_constants->insert(val);
3227               if (!ins.second)
3228                 {
3229                   // Value was already present.
3230                   warning_at(this->location_, 0,
3231                              "duplicate case value will never match");
3232                   continue;
3233                 }
3234
3235               tree label = create_artificial_label(this->location_);
3236               append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node,
3237                                               val, NULL_TREE, label),
3238                                        stmt_list);
3239             }
3240         }
3241     }
3242
3243   if (this->is_default_)
3244     {
3245       tree label = create_artificial_label(this->location_);
3246       append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node,
3247                                       NULL_TREE, NULL_TREE, label),
3248                                stmt_list);
3249     }
3250
3251   if (this->statements_ != NULL)
3252     {
3253       tree block_tree = this->statements_->get_tree(context);
3254       if (block_tree != error_mark_node)
3255         append_to_statement_list(block_tree, stmt_list);
3256     }
3257
3258   if (!this->is_fallthrough_)
3259     append_to_statement_list(break_label->get_goto(this->location_), stmt_list);
3260 }
3261
3262 // Class Case_clauses.
3263
3264 // Traversal.
3265
3266 int
3267 Case_clauses::traverse(Traverse* traverse)
3268 {
3269   for (Clauses::iterator p = this->clauses_.begin();
3270        p != this->clauses_.end();
3271        ++p)
3272     {
3273       if (p->traverse(traverse) == TRAVERSE_EXIT)
3274         return TRAVERSE_EXIT;
3275     }
3276   return TRAVERSE_CONTINUE;
3277 }
3278
3279 // Check whether all the case expressions are constant.
3280
3281 bool
3282 Case_clauses::is_constant() const
3283 {
3284   for (Clauses::const_iterator p = this->clauses_.begin();
3285        p != this->clauses_.end();
3286        ++p)
3287     if (!p->is_constant())
3288       return false;
3289   return true;
3290 }
3291
3292 // Lower case clauses for a nonconstant switch.
3293
3294 void
3295 Case_clauses::lower(Block* b, Temporary_statement* val_temp,
3296                     Unnamed_label* break_label) const
3297 {
3298   // The default case.
3299   const Case_clause* default_case = NULL;
3300
3301   // The label for the fallthrough of the previous case.
3302   Unnamed_label* last_fallthrough_label = NULL;
3303
3304   // The label for the start of the default case.  This is used if the
3305   // case before the default case falls through.
3306   Unnamed_label* default_start_label = NULL;
3307
3308   // The label for the end of the default case.  This normally winds
3309   // up as BREAK_LABEL, but it will be different if the default case
3310   // falls through.
3311   Unnamed_label* default_finish_label = NULL;
3312
3313   for (Clauses::const_iterator p = this->clauses_.begin();
3314        p != this->clauses_.end();
3315        ++p)
3316     {
3317       // The label to use for the start of the statements for this
3318       // case.  This is NULL unless the previous case falls through.
3319       Unnamed_label* start_label = last_fallthrough_label;
3320
3321       // The label to jump to after the end of the statements for this
3322       // case.
3323       Unnamed_label* finish_label = break_label;
3324
3325       last_fallthrough_label = NULL;
3326       if (p->is_fallthrough() && p + 1 != this->clauses_.end())
3327         {
3328           finish_label = new Unnamed_label(p->location());
3329           last_fallthrough_label = finish_label;
3330         }
3331
3332       if (!p->is_default())
3333         p->lower(b, val_temp, start_label, finish_label);
3334       else
3335         {
3336           // We have to move the default case to the end, so that we
3337           // only use it if all the other tests fail.
3338           default_case = &*p;
3339           default_start_label = start_label;
3340           default_finish_label = finish_label;
3341         }
3342     }
3343
3344   if (default_case != NULL)
3345     default_case->lower(b, val_temp, default_start_label,
3346                         default_finish_label);
3347       
3348 }
3349
3350 // Determine types.
3351
3352 void
3353 Case_clauses::determine_types(Type* type)
3354 {
3355   for (Clauses::iterator p = this->clauses_.begin();
3356        p != this->clauses_.end();
3357        ++p)
3358     p->determine_types(type);
3359 }
3360
3361 // Check types.  Returns false if there was an error.
3362
3363 bool
3364 Case_clauses::check_types(Type* type)
3365 {
3366   bool ret = true;
3367   for (Clauses::iterator p = this->clauses_.begin();
3368        p != this->clauses_.end();
3369        ++p)
3370     {
3371       if (!p->check_types(type))
3372         ret = false;
3373     }
3374   return ret;
3375 }
3376
3377 // Return true if these clauses may fall through to the statements
3378 // following the switch statement.
3379
3380 bool
3381 Case_clauses::may_fall_through() const
3382 {
3383   bool found_default = false;
3384   for (Clauses::const_iterator p = this->clauses_.begin();
3385        p != this->clauses_.end();
3386        ++p)
3387     {
3388       if (p->may_fall_through() && !p->is_fallthrough())
3389         return true;
3390       if (p->is_default())
3391         found_default = true;
3392     }
3393   return !found_default;
3394 }
3395
3396 // Return a tree when all case expressions are constants.
3397
3398 tree
3399 Case_clauses::get_constant_tree(Translate_context* context,
3400                                 Unnamed_label* break_label) const
3401 {
3402   Case_constants case_constants;
3403   tree stmt_list = NULL_TREE;
3404   for (Clauses::const_iterator p = this->clauses_.begin();
3405        p != this->clauses_.end();
3406        ++p)
3407     p->get_constant_tree(context, break_label, &case_constants,
3408                          &stmt_list);
3409   return stmt_list;
3410 }
3411
3412 // A constant switch statement.  A Switch_statement is lowered to this
3413 // when all the cases are constants.
3414
3415 class Constant_switch_statement : public Statement
3416 {
3417  public:
3418   Constant_switch_statement(Expression* val, Case_clauses* clauses,
3419                             Unnamed_label* break_label,
3420                             source_location location)
3421     : Statement(STATEMENT_CONSTANT_SWITCH, location),
3422       val_(val), clauses_(clauses), break_label_(break_label)
3423   { }
3424
3425  protected:
3426   int
3427   do_traverse(Traverse*);
3428
3429   void
3430   do_determine_types();
3431
3432   void
3433   do_check_types(Gogo*);
3434
3435   bool
3436   do_may_fall_through() const;
3437
3438   tree
3439   do_get_tree(Translate_context*);
3440
3441  private:
3442   // The value to switch on.
3443   Expression* val_;
3444   // The case clauses.
3445   Case_clauses* clauses_;
3446   // The break label, if needed.
3447   Unnamed_label* break_label_;
3448 };
3449
3450 // Traversal.
3451
3452 int
3453 Constant_switch_statement::do_traverse(Traverse* traverse)
3454 {
3455   if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT)
3456     return TRAVERSE_EXIT;
3457   return this->clauses_->traverse(traverse);
3458 }
3459
3460 // Determine types.
3461
3462 void
3463 Constant_switch_statement::do_determine_types()
3464 {
3465   this->val_->determine_type_no_context();
3466   this->clauses_->determine_types(this->val_->type());
3467 }
3468
3469 // Check types.
3470
3471 void
3472 Constant_switch_statement::do_check_types(Gogo*)
3473 {
3474   if (!this->clauses_->check_types(this->val_->type()))
3475     this->set_is_error();
3476 }
3477
3478 // Return whether this switch may fall through.
3479
3480 bool
3481 Constant_switch_statement::do_may_fall_through() const
3482 {
3483   if (this->clauses_ == NULL)
3484     return true;
3485
3486   // If we have a break label, then some case needed it.  That implies
3487   // that the switch statement as a whole can fall through.
3488   if (this->break_label_ != NULL)
3489     return true;
3490
3491   return this->clauses_->may_fall_through();
3492 }
3493
3494 // Convert to GENERIC.
3495
3496 tree
3497 Constant_switch_statement::do_get_tree(Translate_context* context)
3498 {
3499   tree switch_val_tree = this->val_->get_tree(context);
3500
3501   Unnamed_label* break_label = this->break_label_;
3502   if (break_label == NULL)
3503     break_label = new Unnamed_label(this->location());
3504
3505   tree stmt_list = NULL_TREE;
3506   tree s = build3(SWITCH_EXPR, void_type_node, switch_val_tree,
3507                   this->clauses_->get_constant_tree(context, break_label),
3508                   NULL_TREE);
3509   SET_EXPR_LOCATION(s, this->location());
3510   append_to_statement_list(s, &stmt_list);
3511
3512   append_to_statement_list(break_label->get_definition(), &stmt_list);
3513
3514   return stmt_list;
3515 }
3516
3517 // Class Switch_statement.
3518
3519 // Traversal.
3520
3521 int
3522 Switch_statement::do_traverse(Traverse* traverse)
3523 {
3524   if (this->val_ != NULL)
3525     {
3526       if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT)
3527         return TRAVERSE_EXIT;
3528     }
3529   return this->clauses_->traverse(traverse);
3530 }
3531
3532 // Lower a Switch_statement to a Constant_switch_statement or a series
3533 // of if statements.
3534
3535 Statement*
3536 Switch_statement::do_lower(Gogo*, Block* enclosing)
3537 {
3538   source_location loc = this->location();
3539
3540   if (this->val_ != NULL
3541       && (this->val_->is_error_expression()
3542           || this->val_->type()->is_error_type()))
3543     return Statement::make_error_statement(loc);
3544
3545   if (this->val_ != NULL
3546       && this->val_->type()->integer_type() != NULL
3547       && !this->clauses_->empty()
3548       && this->clauses_->is_constant())
3549     return new Constant_switch_statement(this->val_, this->clauses_,
3550                                          this->break_label_, loc);
3551
3552   Block* b = new Block(enclosing, loc);
3553
3554   if (this->clauses_->empty())
3555     {
3556       Expression* val = this->val_;
3557       if (val == NULL)
3558         val = Expression::make_boolean(true, loc);
3559       return Statement::make_statement(val);
3560     }
3561
3562   Temporary_statement* val_temp;
3563   if (this->val_ == NULL)
3564     val_temp = NULL;
3565   else
3566     {
3567       // var val_temp VAL_TYPE = VAL
3568       val_temp = Statement::make_temporary(NULL, this->val_, loc);
3569       b->add_statement(val_temp);
3570     }
3571
3572   this->clauses_->lower(b, val_temp, this->break_label());
3573
3574   Statement* s = Statement::make_unnamed_label_statement(this->break_label_);
3575   b->add_statement(s);
3576
3577   return Statement::make_block_statement(b, loc);
3578 }
3579
3580 // Return the break label for this switch statement, creating it if
3581 // necessary.
3582
3583 Unnamed_label*
3584 Switch_statement::break_label()
3585 {
3586   if (this->break_label_ == NULL)
3587     this->break_label_ = new Unnamed_label(this->location());
3588   return this->break_label_;
3589 }
3590
3591 // Make a switch statement.
3592
3593 Switch_statement*
3594 Statement::make_switch_statement(Expression* val, source_location location)
3595 {
3596   return new Switch_statement(val, location);
3597 }
3598
3599 // Class Type_case_clauses::Type_case_clause.
3600
3601 // Traversal.
3602
3603 int
3604 Type_case_clauses::Type_case_clause::traverse(Traverse* traverse)
3605 {
3606   if (!this->is_default_
3607       && ((traverse->traverse_mask()
3608            & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0)
3609       && Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3610     return TRAVERSE_EXIT;
3611   if (this->statements_ != NULL)
3612     return this->statements_->traverse(traverse);
3613   return TRAVERSE_CONTINUE;
3614 }
3615
3616 // Lower one clause in a type switch.  Add statements to the block B.
3617 // The type descriptor we are switching on is in DESCRIPTOR_TEMP.
3618 // BREAK_LABEL is the label at the end of the type switch.
3619 // *STMTS_LABEL, if not NULL, is a label to put at the start of the
3620 // statements.
3621
3622 void
3623 Type_case_clauses::Type_case_clause::lower(Block* b,
3624                                            Temporary_statement* descriptor_temp,
3625                                            Unnamed_label* break_label,
3626                                            Unnamed_label** stmts_label) const
3627 {
3628   source_location loc = this->location_;
3629
3630   Unnamed_label* next_case_label = NULL;
3631   if (!this->is_default_)
3632     {
3633       Type* type = this->type_;
3634
3635       Expression* cond;
3636       // The language permits case nil, which is of course a constant
3637       // rather than a type.  It will appear here as an invalid
3638       // forwarding type.
3639       if (type->is_nil_constant_as_type())
3640         {
3641           Expression* ref =
3642             Expression::make_temporary_reference(descriptor_temp, loc);
3643           cond = Expression::make_binary(OPERATOR_EQEQ, ref,
3644                                          Expression::make_nil(loc),
3645                                          loc);
3646         }
3647       else
3648         {
3649           Expression* func;
3650           if (type->interface_type() == NULL)
3651             {
3652               // func ifacetypeeq(*descriptor, *descriptor) bool
3653               static Named_object* ifacetypeeq;
3654               if (ifacetypeeq == NULL)
3655                 {
3656                   const source_location bloc = BUILTINS_LOCATION;
3657                   Typed_identifier_list* param_types =
3658                     new Typed_identifier_list();
3659                   Type* descriptor_type = Type::make_type_descriptor_ptr_type();
3660                   param_types->push_back(Typed_identifier("a", descriptor_type,
3661                                                           bloc));
3662                   param_types->push_back(Typed_identifier("b", descriptor_type,
3663                                                           bloc));
3664                   Typed_identifier_list* ret_types =
3665                     new Typed_identifier_list();
3666                   Type* bool_type = Type::lookup_bool_type();
3667                   ret_types->push_back(Typed_identifier("", bool_type, bloc));
3668                   Function_type* fntype = Type::make_function_type(NULL,
3669                                                                    param_types,
3670                                                                    ret_types,
3671                                                                    bloc);
3672                   ifacetypeeq =
3673                     Named_object::make_function_declaration("ifacetypeeq", NULL,
3674                                                             fntype, bloc);
3675                   const char* n = "runtime.ifacetypeeq";
3676                   ifacetypeeq->func_declaration_value()->set_asm_name(n);
3677                 }
3678
3679               // ifacetypeeq(descriptor_temp, DESCRIPTOR)
3680               func = Expression::make_func_reference(ifacetypeeq, NULL, loc);
3681             }
3682           else
3683             {
3684               // func ifaceI2Tp(*descriptor, *descriptor) bool
3685               static Named_object* ifaceI2Tp;
3686               if (ifaceI2Tp == NULL)
3687                 {
3688                   const source_location bloc = BUILTINS_LOCATION;
3689                   Typed_identifier_list* param_types =
3690                     new Typed_identifier_list();
3691                   Type* descriptor_type = Type::make_type_descriptor_ptr_type();
3692                   param_types->push_back(Typed_identifier("a", descriptor_type,
3693                                                           bloc));
3694                   param_types->push_back(Typed_identifier("b", descriptor_type,
3695                                                           bloc));
3696                   Typed_identifier_list* ret_types =
3697                     new Typed_identifier_list();
3698                   Type* bool_type = Type::lookup_bool_type();
3699                   ret_types->push_back(Typed_identifier("", bool_type, bloc));
3700                   Function_type* fntype = Type::make_function_type(NULL,
3701                                                                    param_types,
3702                                                                    ret_types,
3703                                                                    bloc);
3704                   ifaceI2Tp =
3705                     Named_object::make_function_declaration("ifaceI2Tp", NULL,
3706                                                             fntype, bloc);
3707                   const char* n = "runtime.ifaceI2Tp";
3708                   ifaceI2Tp->func_declaration_value()->set_asm_name(n);
3709                 }
3710
3711               // ifaceI2Tp(descriptor_temp, DESCRIPTOR)
3712               func = Expression::make_func_reference(ifaceI2Tp, NULL, loc);
3713             }
3714           Expression_list* params = new Expression_list();
3715           params->push_back(Expression::make_type_descriptor(type, loc));
3716           Expression* ref =
3717             Expression::make_temporary_reference(descriptor_temp, loc);
3718           params->push_back(ref);
3719           cond = Expression::make_call(func, params, false, loc);
3720         }
3721
3722       Unnamed_label* dest;
3723       if (!this->is_fallthrough_)
3724         {
3725           // if !COND { goto NEXT_CASE_LABEL }
3726           next_case_label = new Unnamed_label(UNKNOWN_LOCATION);
3727           dest = next_case_label;
3728           cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3729         }
3730       else
3731         {
3732           // if COND { goto STMTS_LABEL }
3733           gcc_assert(stmts_label != NULL);
3734           if (*stmts_label == NULL)
3735             *stmts_label = new Unnamed_label(UNKNOWN_LOCATION);
3736           dest = *stmts_label;
3737         }
3738       Block* then_block = new Block(b, loc);
3739       Statement* s = Statement::make_goto_unnamed_statement(dest, loc);
3740       then_block->add_statement(s);
3741       s = Statement::make_if_statement(cond, then_block, NULL, loc);
3742       b->add_statement(s);
3743     }
3744
3745   if (this->statements_ != NULL
3746       || (!this->is_fallthrough_
3747           && stmts_label != NULL
3748           && *stmts_label != NULL))
3749     {
3750       gcc_assert(!this->is_fallthrough_);
3751       if (stmts_label != NULL && *stmts_label != NULL)
3752         {
3753           gcc_assert(!this->is_default_);
3754           if (this->statements_ != NULL)
3755             (*stmts_label)->set_location(this->statements_->start_location());
3756           Statement* s = Statement::make_unnamed_label_statement(*stmts_label);
3757           b->add_statement(s);
3758           *stmts_label = NULL;
3759         }
3760       if (this->statements_ != NULL)
3761         b->add_statement(Statement::make_block_statement(this->statements_,
3762                                                          loc));
3763     }
3764
3765   if (this->is_fallthrough_)
3766     gcc_assert(next_case_label == NULL);
3767   else
3768     {
3769       source_location gloc = (this->statements_ == NULL
3770                               ? loc
3771                               : this->statements_->end_location());
3772       b->add_statement(Statement::make_goto_unnamed_statement(break_label,
3773                                                               gloc));
3774       if (next_case_label != NULL)
3775         {
3776           Statement* s =
3777             Statement::make_unnamed_label_statement(next_case_label);
3778           b->add_statement(s);
3779         }
3780     }
3781 }
3782
3783 // Class Type_case_clauses.
3784
3785 // Traversal.
3786
3787 int
3788 Type_case_clauses::traverse(Traverse* traverse)
3789 {
3790   for (Type_clauses::iterator p = this->clauses_.begin();
3791        p != this->clauses_.end();
3792        ++p)
3793     {
3794       if (p->traverse(traverse) == TRAVERSE_EXIT)
3795         return TRAVERSE_EXIT;
3796     }
3797   return TRAVERSE_CONTINUE;
3798 }
3799
3800 // Check for duplicate types.
3801
3802 void
3803 Type_case_clauses::check_duplicates() const
3804 {
3805   typedef Unordered_set_hash(const Type*, Type_hash_identical,
3806                              Type_identical) Types_seen;
3807   Types_seen types_seen;
3808   for (Type_clauses::const_iterator p = this->clauses_.begin();
3809        p != this->clauses_.end();
3810        ++p)
3811     {
3812       Type* t = p->type();
3813       if (t == NULL)
3814         continue;
3815       if (t->is_nil_constant_as_type())
3816         t = Type::make_nil_type();
3817       std::pair<Types_seen::iterator, bool> ins = types_seen.insert(t);
3818       if (!ins.second)
3819         error_at(p->location(), "duplicate type in switch");
3820     }
3821 }
3822
3823 // Lower the clauses in a type switch.  Add statements to the block B.
3824 // The type descriptor we are switching on is in DESCRIPTOR_TEMP.
3825 // BREAK_LABEL is the label at the end of the type switch.
3826
3827 void
3828 Type_case_clauses::lower(Block* b, Temporary_statement* descriptor_temp,
3829                          Unnamed_label* break_label) const
3830 {
3831   const Type_case_clause* default_case = NULL;
3832
3833   Unnamed_label* stmts_label = NULL;
3834   for (Type_clauses::const_iterator p = this->clauses_.begin();
3835        p != this->clauses_.end();
3836        ++p)
3837     {
3838       if (!p->is_default())
3839         p->lower(b, descriptor_temp, break_label, &stmts_label);
3840       else
3841         {
3842           // We are generating a series of tests, which means that we
3843           // need to move the default case to the end.
3844           default_case = &*p;
3845         }
3846     }
3847   gcc_assert(stmts_label == NULL);
3848
3849   if (default_case != NULL)
3850     default_case->lower(b, descriptor_temp, break_label, NULL);
3851 }
3852
3853 // Class Type_switch_statement.
3854
3855 // Traversal.
3856
3857 int
3858 Type_switch_statement::do_traverse(Traverse* traverse)
3859 {
3860   if (this->var_ == NULL)
3861     {
3862       if (this->traverse_expression(traverse, &this->expr_) == TRAVERSE_EXIT)
3863         return TRAVERSE_EXIT;
3864     }
3865   if (this->clauses_ != NULL)
3866     return this->clauses_->traverse(traverse);
3867   return TRAVERSE_CONTINUE;
3868 }
3869
3870 // Lower a type switch statement to a series of if statements.  The gc
3871 // compiler is able to generate a table in some cases.  However, that
3872 // does not work for us because we may have type descriptors in
3873 // different shared libraries, so we can't compare them with simple
3874 // equality testing.
3875
3876 Statement*
3877 Type_switch_statement::do_lower(Gogo*, Block* enclosing)
3878 {
3879   const source_location loc = this->location();
3880
3881   if (this->clauses_ != NULL)
3882     this->clauses_->check_duplicates();
3883
3884   Block* b = new Block(enclosing, loc);
3885
3886   Type* val_type = (this->var_ != NULL
3887                     ? this->var_->var_value()->type()
3888                     : this->expr_->type());
3889
3890   // var descriptor_temp DESCRIPTOR_TYPE
3891   Type* descriptor_type = Type::make_type_descriptor_ptr_type();
3892   Temporary_statement* descriptor_temp =
3893     Statement::make_temporary(descriptor_type, NULL, loc);
3894   b->add_statement(descriptor_temp);
3895
3896   if (val_type->interface_type() == NULL)
3897     {
3898       // Doing a type switch on a non-interface type.  Should we issue
3899       // a warning for this case?
3900       // descriptor_temp = DESCRIPTOR
3901       Expression* lhs = Expression::make_temporary_reference(descriptor_temp,
3902                                                              loc);
3903       Expression* rhs = Expression::make_type_descriptor(val_type, loc);
3904       Statement* s = Statement::make_assignment(lhs, rhs, loc);
3905       b->add_statement(s);
3906     }
3907   else
3908     {
3909       const source_location bloc = BUILTINS_LOCATION;
3910
3911       // func {efacetype,ifacetype}(*interface) *descriptor
3912       // FIXME: This should be inlined.
3913       Typed_identifier_list* param_types = new Typed_identifier_list();
3914       param_types->push_back(Typed_identifier("i", val_type, bloc));
3915       Typed_identifier_list* ret_types = new Typed_identifier_list();
3916       ret_types->push_back(Typed_identifier("", descriptor_type, bloc));
3917       Function_type* fntype = Type::make_function_type(NULL, param_types,
3918                                                        ret_types, bloc);
3919       bool is_empty = val_type->interface_type()->is_empty();
3920       const char* fnname = is_empty ? "efacetype" : "ifacetype";
3921       Named_object* fn =
3922         Named_object::make_function_declaration(fnname, NULL, fntype, bloc);
3923       const char* asm_name = (is_empty
3924                               ? "runtime.efacetype"
3925                               : "runtime.ifacetype");
3926       fn->func_declaration_value()->set_asm_name(asm_name);
3927
3928       // descriptor_temp = ifacetype(val_temp)
3929       Expression* func = Expression::make_func_reference(fn, NULL, loc);
3930       Expression_list* params = new Expression_list();
3931       Expression* ref;
3932       if (this->var_ == NULL)
3933         ref = this->expr_;
3934       else
3935         ref = Expression::make_var_reference(this->var_, loc);
3936       params->push_back(ref);
3937       Expression* call = Expression::make_call(func, params, false, loc);
3938       Expression* lhs = Expression::make_temporary_reference(descriptor_temp,
3939                                                              loc);
3940       Statement* s = Statement::make_assignment(lhs, call, loc);
3941       b->add_statement(s);
3942     }
3943
3944   if (this->clauses_ != NULL)
3945     this->clauses_->lower(b, descriptor_temp, this->break_label());
3946
3947   Statement* s = Statement::make_unnamed_label_statement(this->break_label_);
3948   b->add_statement(s);
3949
3950   return Statement::make_block_statement(b, loc);
3951 }
3952
3953 // Return the break label for this type switch statement, creating it
3954 // if necessary.
3955
3956 Unnamed_label*
3957 Type_switch_statement::break_label()
3958 {
3959   if (this->break_label_ == NULL)
3960     this->break_label_ = new Unnamed_label(this->location());
3961   return this->break_label_;
3962 }
3963
3964 // Make a type switch statement.
3965
3966 Type_switch_statement*
3967 Statement::make_type_switch_statement(Named_object* var, Expression* expr,
3968                                       source_location location)
3969 {
3970   return new Type_switch_statement(var, expr, location);
3971 }
3972
3973 // Class Select_clauses::Select_clause.
3974
3975 // Traversal.
3976
3977 int
3978 Select_clauses::Select_clause::traverse(Traverse* traverse)
3979 {
3980   if (!this->is_lowered_
3981       && (traverse->traverse_mask()
3982           & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0)
3983     {
3984       if (this->channel_ != NULL)
3985         {
3986           if (Expression::traverse(&this->channel_, traverse) == TRAVERSE_EXIT)
3987             return TRAVERSE_EXIT;
3988         }
3989       if (this->val_ != NULL)
3990         {
3991           if (Expression::traverse(&this->val_, traverse) == TRAVERSE_EXIT)
3992             return TRAVERSE_EXIT;
3993         }
3994     }
3995   if (this->statements_ != NULL)
3996     {
3997       if (this->statements_->traverse(traverse) == TRAVERSE_EXIT)
3998         return TRAVERSE_EXIT;
3999     }
4000   return TRAVERSE_CONTINUE;
4001 }
4002
4003 // Lowering.  Here we pull out the channel and the send values, to
4004 // enforce the order of evaluation.  We also add explicit send and
4005 // receive statements to the clauses.
4006
4007 void
4008 Select_clauses::Select_clause::lower(Block* b)
4009 {
4010   if (this->is_default_)
4011     {
4012       gcc_assert(this->channel_ == NULL && this->val_ == NULL);
4013       this->is_lowered_ = true;
4014       return;
4015     }
4016
4017   source_location loc = this->location_;
4018
4019   // Evaluate the channel before the select statement.
4020   Temporary_statement* channel_temp = Statement::make_temporary(NULL,
4021                                                                 this->channel_,
4022                                                                 loc);
4023   b->add_statement(channel_temp);
4024   this->channel_ = Expression::make_temporary_reference(channel_temp, loc);
4025
4026   // If this is a send clause, evaluate the value to send before the
4027   // select statement.
4028   Temporary_statement* val_temp = NULL;
4029   if (this->is_send_)
4030     {
4031       val_temp = Statement::make_temporary(NULL, this->val_, loc);
4032       b->add_statement(val_temp);
4033     }
4034
4035   // Add the send or receive before the rest of the statements if any.
4036   Block *init = new Block(b, loc);
4037   Expression* ref = Expression::make_temporary_reference(channel_temp, loc);
4038   if (this->is_send_)
4039     {
4040       Expression* ref2 = Expression::make_temporary_reference(val_temp, loc);
4041       Send_expression* send = Expression::make_send(ref, ref2, loc);
4042       send->discarding_value();
4043       send->set_for_select();
4044       init->add_statement(Statement::make_statement(send));
4045     }
4046   else
4047     {
4048       Receive_expression* recv = Expression::make_receive(ref, loc);
4049       recv->set_for_select();
4050       if (this->val_ != NULL)
4051         {
4052           gcc_assert(this->var_ == NULL);
4053           init->add_statement(Statement::make_assignment(this->val_, recv,
4054                                                          loc));
4055         }
4056       else if (this->var_ != NULL)
4057         {
4058           this->var_->var_value()->set_init(recv);
4059           this->var_->var_value()->clear_type_from_chan_element();
4060         }
4061       else
4062         {
4063           recv->discarding_value();
4064           init->add_statement(Statement::make_statement(recv));
4065         }
4066     }
4067
4068   if (this->statements_ != NULL)
4069     init->add_statement(Statement::make_block_statement(this->statements_,
4070                                                         loc));
4071
4072   this->statements_ = init;
4073
4074   // Now all references should be handled through the statements, not
4075   // through here.
4076   this->is_lowered_ = true;
4077   this->val_ = NULL;
4078   this->var_ = NULL;
4079 }
4080
4081 // Determine types.
4082
4083 void
4084 Select_clauses::Select_clause::determine_types()
4085 {
4086   gcc_assert(this->is_lowered_);
4087   if (this->statements_ != NULL)
4088     this->statements_->determine_types();
4089 }
4090
4091 // Whether this clause may fall through to the statement which follows
4092 // the overall select statement.
4093
4094 bool
4095 Select_clauses::Select_clause::may_fall_through() const
4096 {
4097   if (this->statements_ == NULL)
4098     return true;
4099   return this->statements_->may_fall_through();
4100 }
4101
4102 // Return a tree for the statements to execute.
4103
4104 tree
4105 Select_clauses::Select_clause::get_statements_tree(Translate_context* context)
4106 {
4107   if (this->statements_ == NULL)
4108     return NULL_TREE;
4109   return this->statements_->get_tree(context);
4110 }
4111
4112 // Class Select_clauses.
4113
4114 // Traversal.
4115
4116 int
4117 Select_clauses::traverse(Traverse* traverse)
4118 {
4119   for (Clauses::iterator p = this->clauses_.begin();
4120        p != this->clauses_.end();
4121        ++p)
4122     {
4123       if (p->traverse(traverse) == TRAVERSE_EXIT)
4124         return TRAVERSE_EXIT;
4125     }
4126   return TRAVERSE_CONTINUE;
4127 }
4128
4129 // Lowering.  Here we pull out the channel and the send values, to
4130 // enforce the order of evaluation.  We also add explicit send and
4131 // receive statements to the clauses.
4132
4133 void
4134 Select_clauses::lower(Block* b)
4135 {
4136   for (Clauses::iterator p = this->clauses_.begin();
4137        p != this->clauses_.end();
4138        ++p)
4139     p->lower(b);
4140 }
4141
4142 // Determine types.
4143
4144 void
4145 Select_clauses::determine_types()
4146 {
4147   for (Clauses::iterator p = this->clauses_.begin();
4148        p != this->clauses_.end();
4149        ++p)
4150     p->determine_types();
4151 }
4152
4153 // Return whether these select clauses fall through to the statement
4154 // following the overall select statement.
4155
4156 bool
4157 Select_clauses::may_fall_through() const
4158 {
4159   for (Clauses::const_iterator p = this->clauses_.begin();
4160        p != this->clauses_.end();
4161        ++p)
4162     if (p->may_fall_through())
4163       return true;
4164   return false;
4165 }
4166
4167 // Return a tree.  We build a call to
4168 //   size_t __go_select(size_t count, _Bool has_default,
4169 //                      channel* channels, _Bool* is_send)
4170 //
4171 // There are COUNT entries in the CHANNELS and IS_SEND arrays.  The
4172 // value in the IS_SEND array is true for send, false for receive.
4173 // __go_select returns an integer from 0 to COUNT, inclusive.  A
4174 // return of 0 means that the default case should be run; this only
4175 // happens if HAS_DEFAULT is non-zero.  Otherwise the number indicates
4176 // the case to run.
4177
4178 // FIXME: This doesn't handle channels which send interface types
4179 // where the receiver has a static type which matches that interface.
4180
4181 tree
4182 Select_clauses::get_tree(Translate_context* context,
4183                          Unnamed_label *break_label,
4184                          source_location location)
4185 {
4186   size_t count = this->clauses_.size();
4187   VEC(constructor_elt, gc)* chan_init = VEC_alloc(constructor_elt, gc, count);
4188   VEC(constructor_elt, gc)* is_send_init = VEC_alloc(constructor_elt, gc,
4189                                                      count);
4190   Select_clause* default_clause = NULL;
4191   tree final_stmt_list = NULL_TREE;
4192   tree channel_type_tree = NULL_TREE;
4193
4194   size_t i = 0;
4195   for (Clauses::iterator p = this->clauses_.begin();
4196        p != this->clauses_.end();
4197        ++p)
4198     {
4199       if (p->is_default())
4200         {
4201           default_clause = &*p;
4202           --count;
4203           continue;
4204         }
4205
4206       if (p->channel()->type()->channel_type() == NULL)
4207         {
4208           // We should have given an error in the send or receive
4209           // statement we created via lowering.
4210           gcc_assert(saw_errors());
4211           return error_mark_node;
4212         }
4213
4214       tree channel_tree = p->channel()->get_tree(context);
4215       if (channel_tree == error_mark_node)
4216         return error_mark_node;
4217       channel_type_tree = TREE_TYPE(channel_tree);
4218
4219       constructor_elt* elt = VEC_quick_push(constructor_elt, chan_init, NULL);
4220       elt->index = build_int_cstu(sizetype, i);
4221       elt->value = channel_tree;
4222
4223       elt = VEC_quick_push(constructor_elt, is_send_init, NULL);
4224       elt->index = build_int_cstu(sizetype, i);
4225       elt->value = p->is_send() ? boolean_true_node : boolean_false_node;
4226
4227       ++i;
4228     }
4229   gcc_assert(i == count);
4230
4231   if (i == 0 && default_clause != NULL)
4232     {
4233       // There is only a default clause.
4234       gcc_assert(final_stmt_list == NULL_TREE);
4235       tree stmt_list = NULL_TREE;
4236       append_to_statement_list(default_clause->get_statements_tree(context),
4237                                &stmt_list);
4238       append_to_statement_list(break_label->get_definition(), &stmt_list);
4239       return stmt_list;
4240     }
4241
4242   tree pointer_chan_type_tree = (channel_type_tree == NULL_TREE
4243                                  ? ptr_type_node
4244                                  : build_pointer_type(channel_type_tree));
4245   tree chans_arg;
4246   tree pointer_boolean_type_tree = build_pointer_type(boolean_type_node);
4247   tree is_sends_arg;
4248
4249   if (i == 0)
4250     {
4251       chans_arg = fold_convert_loc(location, pointer_chan_type_tree,
4252                                    null_pointer_node);
4253       is_sends_arg = fold_convert_loc(location, pointer_boolean_type_tree,
4254                                       null_pointer_node);
4255     }
4256   else
4257     {
4258       tree index_type_tree = build_index_type(size_int(count - 1));
4259       tree chan_array_type_tree = build_array_type(channel_type_tree,
4260                                                    index_type_tree);
4261       tree chan_constructor = build_constructor(chan_array_type_tree,
4262                                                 chan_init);
4263       tree chan_var = create_tmp_var(chan_array_type_tree, "CHAN");
4264       DECL_IGNORED_P(chan_var) = 0;
4265       DECL_INITIAL(chan_var) = chan_constructor;
4266       DECL_SOURCE_LOCATION(chan_var) = location;
4267       TREE_ADDRESSABLE(chan_var) = 1;
4268       tree decl_expr = build1(DECL_EXPR, void_type_node, chan_var);
4269       SET_EXPR_LOCATION(decl_expr, location);
4270       append_to_statement_list(decl_expr, &final_stmt_list);
4271
4272       tree is_send_array_type_tree = build_array_type(boolean_type_node,
4273                                                       index_type_tree);
4274       tree is_send_constructor = build_constructor(is_send_array_type_tree,
4275                                                    is_send_init);
4276       tree is_send_var = create_tmp_var(is_send_array_type_tree, "ISSEND");
4277       DECL_IGNORED_P(is_send_var) = 0;
4278       DECL_INITIAL(is_send_var) = is_send_constructor;
4279       DECL_SOURCE_LOCATION(is_send_var) = location;
4280       TREE_ADDRESSABLE(is_send_var) = 1;
4281       decl_expr = build1(DECL_EXPR, void_type_node, is_send_var);
4282       SET_EXPR_LOCATION(decl_expr, location);
4283       append_to_statement_list(decl_expr, &final_stmt_list);
4284
4285       chans_arg = fold_convert_loc(location, pointer_chan_type_tree,
4286                                    build_fold_addr_expr_loc(location,
4287                                                             chan_var));
4288       is_sends_arg = fold_convert_loc(location, pointer_boolean_type_tree,
4289                                       build_fold_addr_expr_loc(location,
4290                                                                is_send_var));
4291     }
4292
4293   static tree select_fndecl;
4294   tree call = Gogo::call_builtin(&select_fndecl,
4295                                  location,
4296                                  "__go_select",
4297                                  4,
4298                                  sizetype,
4299                                  sizetype,
4300                                  size_int(count),
4301                                  boolean_type_node,
4302                                  (default_clause == NULL
4303                                   ? boolean_false_node
4304                                   : boolean_true_node),
4305                                  pointer_chan_type_tree,
4306                                  chans_arg,
4307                                  pointer_boolean_type_tree,
4308                                  is_sends_arg);
4309   if (call == error_mark_node)
4310     return error_mark_node;
4311
4312   tree stmt_list = NULL_TREE;
4313
4314   if (default_clause != NULL)
4315     this->add_clause_tree(context, 0, default_clause, break_label, &stmt_list);
4316
4317   i = 1;
4318   for (Clauses::iterator p = this->clauses_.begin();
4319        p != this->clauses_.end();
4320        ++p)
4321     {
4322       if (!p->is_default())
4323         {
4324           this->add_clause_tree(context, i, &*p, break_label, &stmt_list);
4325           ++i;
4326         }
4327     }
4328
4329   append_to_statement_list(break_label->get_definition(), &stmt_list);
4330
4331   tree switch_stmt = build3(SWITCH_EXPR, sizetype, call, stmt_list, NULL_TREE);
4332   SET_EXPR_LOCATION(switch_stmt, location);
4333   append_to_statement_list(switch_stmt, &final_stmt_list);
4334
4335   return final_stmt_list;
4336 }
4337
4338 // Add the tree for CLAUSE to STMT_LIST.
4339
4340 void
4341 Select_clauses::add_clause_tree(Translate_context* context, int case_index,
4342                                 Select_clause* clause,
4343                                 Unnamed_label* bottom_label, tree* stmt_list)
4344 {
4345   tree label = create_artificial_label(clause->location());
4346   append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node,
4347                                   build_int_cst(sizetype, case_index),
4348                                   NULL_TREE, label),
4349                            stmt_list);
4350   append_to_statement_list(clause->get_statements_tree(context), stmt_list);
4351   tree g = bottom_label->get_goto(clause->statements() == NULL
4352                                   ? clause->location()
4353                                   : clause->statements()->end_location());
4354   append_to_statement_list(g, stmt_list);
4355 }
4356
4357 // Class Select_statement.
4358
4359 // Return the break label for this switch statement, creating it if
4360 // necessary.
4361
4362 Unnamed_label*
4363 Select_statement::break_label()
4364 {
4365   if (this->break_label_ == NULL)
4366     this->break_label_ = new Unnamed_label(this->location());
4367   return this->break_label_;
4368 }
4369
4370 // Lower a select statement.  This will still return a select
4371 // statement, but it will be modified to implement the order of
4372 // evaluation rules, and to include the send and receive statements as
4373 // explicit statements in the clauses.
4374
4375 Statement*
4376 Select_statement::do_lower(Gogo*, Block* enclosing)
4377 {
4378   if (this->is_lowered_)
4379     return this;
4380   Block* b = new Block(enclosing, this->location());
4381   this->clauses_->lower(b);
4382   this->is_lowered_ = true;
4383   b->add_statement(this);
4384   return Statement::make_block_statement(b, this->location());
4385 }
4386
4387 // Return the tree for a select statement.
4388
4389 tree
4390 Select_statement::do_get_tree(Translate_context* context)
4391 {
4392   return this->clauses_->get_tree(context, this->break_label(),
4393                                   this->location());
4394 }
4395
4396 // Make a select statement.
4397
4398 Select_statement*
4399 Statement::make_select_statement(source_location location)
4400 {
4401   return new Select_statement(location);
4402 }
4403
4404 // Class For_statement.
4405
4406 // Traversal.
4407
4408 int
4409 For_statement::do_traverse(Traverse* traverse)
4410 {
4411   if (this->init_ != NULL)
4412     {
4413       if (this->init_->traverse(traverse) == TRAVERSE_EXIT)
4414         return TRAVERSE_EXIT;
4415     }
4416   if (this->cond_ != NULL)
4417     {
4418       if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT)
4419         return TRAVERSE_EXIT;
4420     }
4421   if (this->post_ != NULL)
4422     {
4423       if (this->post_->traverse(traverse) == TRAVERSE_EXIT)
4424         return TRAVERSE_EXIT;
4425     }
4426   return this->statements_->traverse(traverse);
4427 }
4428
4429 // Lower a For_statement into if statements and gotos.  Getting rid of
4430 // complex statements make it easier to handle garbage collection.
4431
4432 Statement*
4433 For_statement::do_lower(Gogo*, Block* enclosing)
4434 {
4435   Statement* s;
4436   source_location loc = this->location();
4437
4438   Block* b = new Block(enclosing, this->location());
4439   if (this->init_ != NULL)
4440     {
4441       s = Statement::make_block_statement(this->init_,
4442                                           this->init_->start_location());
4443       b->add_statement(s);
4444     }
4445
4446   Unnamed_label* entry = NULL;
4447   if (this->cond_ != NULL)
4448     {
4449       entry = new Unnamed_label(this->location());
4450       b->add_statement(Statement::make_goto_unnamed_statement(entry, loc));
4451     }
4452
4453   Unnamed_label* top = new Unnamed_label(this->location());
4454   b->add_statement(Statement::make_unnamed_label_statement(top));
4455
4456   s = Statement::make_block_statement(this->statements_,
4457                                       this->statements_->start_location());
4458   b->add_statement(s);
4459
4460   source_location end_loc = this->statements_->end_location();
4461
4462   Unnamed_label* cont = this->continue_label_;
4463   if (cont != NULL)
4464     b->add_statement(Statement::make_unnamed_label_statement(cont));
4465
4466   if (this->post_ != NULL)
4467     {
4468       s = Statement::make_block_statement(this->post_,
4469                                           this->post_->start_location());
4470       b->add_statement(s);
4471       end_loc = this->post_->end_location();
4472     }
4473
4474   if (this->cond_ == NULL)
4475     b->add_statement(Statement::make_goto_unnamed_statement(top, end_loc));
4476   else
4477     {
4478       b->add_statement(Statement::make_unnamed_label_statement(entry));
4479
4480       source_location cond_loc = this->cond_->location();
4481       Block* then_block = new Block(b, cond_loc);
4482       s = Statement::make_goto_unnamed_statement(top, cond_loc);
4483       then_block->add_statement(s);
4484
4485       s = Statement::make_if_statement(this->cond_, then_block, NULL, cond_loc);
4486       b->add_statement(s);
4487     }
4488
4489   Unnamed_label* brk = this->break_label_;
4490   if (brk != NULL)
4491     b->add_statement(Statement::make_unnamed_label_statement(brk));
4492
4493   b->set_end_location(end_loc);
4494
4495   return Statement::make_block_statement(b, loc);
4496 }
4497
4498 // Return the break label, creating it if necessary.
4499
4500 Unnamed_label*
4501 For_statement::break_label()
4502 {
4503   if (this->break_label_ == NULL)
4504     this->break_label_ = new Unnamed_label(this->location());
4505   return this->break_label_;
4506 }
4507
4508 // Return the continue LABEL_EXPR.
4509
4510 Unnamed_label*
4511 For_statement::continue_label()
4512 {
4513   if (this->continue_label_ == NULL)
4514     this->continue_label_ = new Unnamed_label(this->location());
4515   return this->continue_label_;
4516 }
4517
4518 // Set the break and continue labels a for statement.  This is used
4519 // when lowering a for range statement.
4520
4521 void
4522 For_statement::set_break_continue_labels(Unnamed_label* break_label,
4523                                          Unnamed_label* continue_label)
4524 {
4525   gcc_assert(this->break_label_ == NULL && this->continue_label_ == NULL);
4526   this->break_label_ = break_label;
4527   this->continue_label_ = continue_label;
4528 }
4529
4530 // Make a for statement.
4531
4532 For_statement*
4533 Statement::make_for_statement(Block* init, Expression* cond, Block* post,
4534                               source_location location)
4535 {
4536   return new For_statement(init, cond, post, location);
4537 }
4538
4539 // Class For_range_statement.
4540
4541 // Traversal.
4542
4543 int
4544 For_range_statement::do_traverse(Traverse* traverse)
4545 {
4546   if (this->traverse_expression(traverse, &this->index_var_) == TRAVERSE_EXIT)
4547     return TRAVERSE_EXIT;
4548   if (this->value_var_ != NULL)
4549     {
4550       if (this->traverse_expression(traverse, &this->value_var_)
4551           == TRAVERSE_EXIT)
4552         return TRAVERSE_EXIT;
4553     }
4554   if (this->traverse_expression(traverse, &this->range_) == TRAVERSE_EXIT)
4555     return TRAVERSE_EXIT;
4556   return this->statements_->traverse(traverse);
4557 }
4558
4559 // Lower a for range statement.  For simplicity we lower this into a
4560 // for statement, which will then be lowered in turn to goto
4561 // statements.
4562
4563 Statement*
4564 For_range_statement::do_lower(Gogo* gogo, Block* enclosing)
4565 {
4566   Type* range_type = this->range_->type();
4567   if (range_type->points_to() != NULL
4568       && range_type->points_to()->array_type() != NULL
4569       && !range_type->points_to()->is_open_array_type())
4570     range_type = range_type->points_to();
4571
4572   Type* index_type;
4573   Type* value_type = NULL;
4574   if (range_type->array_type() != NULL)
4575     {
4576       index_type = Type::lookup_integer_type("int");
4577       value_type = range_type->array_type()->element_type();
4578     }
4579   else if (range_type->is_string_type())
4580     {
4581       index_type = Type::lookup_integer_type("int");
4582       value_type = index_type;
4583     }
4584   else if (range_type->map_type() != NULL)
4585     {
4586       index_type = range_type->map_type()->key_type();
4587       value_type = range_type->map_type()->val_type();
4588     }
4589   else if (range_type->channel_type() != NULL)
4590     {
4591       index_type = range_type->channel_type()->element_type();
4592       if (this->value_var_ != NULL)
4593         {
4594           if (!this->value_var_->type()->is_error_type())
4595             this->report_error(_("too many variables for range clause "
4596                                  "with channel"));
4597           return Statement::make_error_statement(this->location());
4598         }
4599     }
4600   else
4601     {
4602       this->report_error(_("range clause must have "
4603                            "array, slice, setring, map, or channel type"));
4604       return Statement::make_error_statement(this->location());
4605     }
4606
4607   source_location loc = this->location();
4608   Block* temp_block = new Block(enclosing, loc);
4609
4610   Named_object* range_object = NULL;
4611   Temporary_statement* range_temp = NULL;
4612   Var_expression* ve = this->range_->var_expression();
4613   if (ve != NULL)
4614     range_object = ve->named_object();
4615   else
4616     {
4617       range_temp = Statement::make_temporary(NULL, this->range_, loc);
4618       temp_block->add_statement(range_temp);
4619     }
4620
4621   Temporary_statement* index_temp = Statement::make_temporary(index_type,
4622                                                               NULL, loc);
4623   temp_block->add_statement(index_temp);
4624
4625   Temporary_statement* value_temp = NULL;
4626   if (this->value_var_ != NULL)
4627     {
4628       value_temp = Statement::make_temporary(value_type, NULL, loc);
4629       temp_block->add_statement(value_temp);
4630     }
4631
4632   Block* body = new Block(temp_block, loc);
4633
4634   Block* init;
4635   Expression* cond;
4636   Block* iter_init;
4637   Block* post;
4638
4639   // Arrange to do a loop appropriate for the type.  We will produce
4640   //   for INIT ; COND ; POST {
4641   //           ITER_INIT
4642   //           INDEX = INDEX_TEMP
4643   //           VALUE = VALUE_TEMP // If there is a value
4644   //           original statements
4645   //   }
4646
4647   if (range_type->array_type() != NULL)
4648     this->lower_range_array(gogo, temp_block, body, range_object, range_temp,
4649                             index_temp, value_temp, &init, &cond, &iter_init,
4650                             &post);
4651   else if (range_type->is_string_type())
4652     this->lower_range_string(gogo, temp_block, body, range_object, range_temp,
4653                              index_temp, value_temp, &init, &cond, &iter_init,
4654                              &post);
4655   else if (range_type->map_type() != NULL)
4656     this->lower_range_map(gogo, temp_block, body, range_object, range_temp,
4657                           index_temp, value_temp, &init, &cond, &iter_init,
4658                           &post);
4659   else if (range_type->channel_type() != NULL)
4660     this->lower_range_channel(gogo, temp_block, body, range_object, range_temp,
4661                               index_temp, value_temp, &init, &cond, &iter_init,
4662                               &post);
4663   else
4664     gcc_unreachable();
4665
4666   if (iter_init != NULL)
4667     body->add_statement(Statement::make_block_statement(iter_init, loc));
4668
4669   Statement* assign;
4670   Expression* index_ref = Expression::make_temporary_reference(index_temp, loc);
4671   if (this->value_var_ == NULL)
4672     {
4673       assign = Statement::make_assignment(this->index_var_, index_ref, loc);
4674     }
4675   else
4676     {
4677       Expression_list* lhs = new Expression_list();
4678       lhs->push_back(this->index_var_);
4679       lhs->push_back(this->value_var_);
4680
4681       Expression_list* rhs = new Expression_list();
4682       rhs->push_back(index_ref);
4683       rhs->push_back(Expression::make_temporary_reference(value_temp, loc));
4684
4685       assign = Statement::make_tuple_assignment(lhs, rhs, loc);
4686     }
4687   body->add_statement(assign);
4688
4689   body->add_statement(Statement::make_block_statement(this->statements_, loc));
4690
4691   body->set_end_location(this->statements_->end_location());
4692
4693   For_statement* loop = Statement::make_for_statement(init, cond, post,
4694                                                       this->location());
4695   loop->add_statements(body);
4696   loop->set_break_continue_labels(this->break_label_, this->continue_label_);
4697
4698   temp_block->add_statement(loop);
4699
4700   return Statement::make_block_statement(temp_block, loc);
4701 }
4702
4703 // Return a reference to the range, which may be in RANGE_OBJECT or in
4704 // RANGE_TEMP.
4705
4706 Expression*
4707 For_range_statement::make_range_ref(Named_object* range_object,
4708                                     Temporary_statement* range_temp,
4709                                     source_location loc)
4710 {
4711   if (range_object != NULL)
4712     return Expression::make_var_reference(range_object, loc);
4713   else
4714     return Expression::make_temporary_reference(range_temp, loc);
4715 }
4716
4717 // Return a call to the predeclared function FUNCNAME passing a
4718 // reference to the temporary variable ARG.
4719
4720 Expression*
4721 For_range_statement::call_builtin(Gogo* gogo, const char* funcname,
4722                                   Expression* arg,
4723                                   source_location loc)
4724 {
4725   Named_object* no = gogo->lookup_global(funcname);
4726   gcc_assert(no != NULL && no->is_function_declaration());
4727   Expression* func = Expression::make_func_reference(no, NULL, loc);
4728   Expression_list* params = new Expression_list();
4729   params->push_back(arg);
4730   return Expression::make_call(func, params, false, loc);
4731 }
4732
4733 // Lower a for range over an array or slice.
4734
4735 void
4736 For_range_statement::lower_range_array(Gogo* gogo,
4737                                        Block* enclosing,
4738                                        Block* body_block,
4739                                        Named_object* range_object,
4740                                        Temporary_statement* range_temp,
4741                                        Temporary_statement* index_temp,
4742                                        Temporary_statement* value_temp,
4743                                        Block** pinit,
4744                                        Expression** pcond,
4745                                        Block** piter_init,
4746                                        Block** ppost)
4747 {
4748   source_location loc = this->location();
4749
4750   // The loop we generate:
4751   //   len_temp := len(range)
4752   //   for index_temp = 0; index_temp < len_temp; index_temp++ {
4753   //           value_temp = range[index_temp]
4754   //           index = index_temp
4755   //           value = value_temp
4756   //           original body
4757   //   }
4758
4759   // Set *PINIT to
4760   //   var len_temp int
4761   //   len_temp = len(range)
4762   //   index_temp = 0
4763
4764   Block* init = new Block(enclosing, loc);
4765
4766   Expression* ref = this->make_range_ref(range_object, range_temp, loc);
4767   Expression* len_call = this->call_builtin(gogo, "len", ref, loc);
4768   Temporary_statement* len_temp = Statement::make_temporary(index_temp->type(),
4769                                                             len_call, loc);
4770   init->add_statement(len_temp);
4771
4772   mpz_t zval;
4773   mpz_init_set_ui(zval, 0UL);
4774   Expression* zexpr = Expression::make_integer(&zval, NULL, loc);
4775   mpz_clear(zval);
4776
4777   ref = Expression::make_temporary_reference(index_temp, loc);
4778   Statement* s = Statement::make_assignment(ref, zexpr, loc);
4779   init->add_statement(s);
4780
4781   *pinit = init;
4782
4783   // Set *PCOND to
4784   //   index_temp < len_temp
4785
4786   ref = Expression::make_temporary_reference(index_temp, loc);
4787   Expression* ref2 = Expression::make_temporary_reference(len_temp, loc);
4788   Expression* lt = Expression::make_binary(OPERATOR_LT, ref, ref2, loc);
4789
4790   *pcond = lt;
4791
4792   // Set *PITER_INIT to
4793   //   value_temp = range[index_temp]
4794
4795   Block* iter_init = NULL;
4796   if (value_temp != NULL)
4797     {
4798       iter_init = new Block(body_block, loc);
4799
4800       ref = this->make_range_ref(range_object, range_temp, loc);
4801       Expression* ref2 = Expression::make_temporary_reference(index_temp, loc);
4802       Expression* index = Expression::make_index(ref, ref2, NULL, loc);
4803
4804       ref = Expression::make_temporary_reference(value_temp, loc);
4805       s = Statement::make_assignment(ref, index, loc);
4806
4807       iter_init->add_statement(s);
4808     }
4809   *piter_init = iter_init;
4810
4811   // Set *PPOST to
4812   //   index_temp++
4813
4814   Block* post = new Block(enclosing, loc);
4815   ref = Expression::make_temporary_reference(index_temp, loc);
4816   s = Statement::make_inc_statement(ref);
4817   post->add_statement(s);
4818   *ppost = post;
4819 }
4820
4821 // Lower a for range over a string.
4822
4823 void
4824 For_range_statement::lower_range_string(Gogo* gogo,
4825                                         Block* enclosing,
4826                                         Block* body_block,
4827                                         Named_object* range_object,
4828                                         Temporary_statement* range_temp,
4829                                         Temporary_statement* index_temp,
4830                                         Temporary_statement* value_temp,
4831                                         Block** pinit,
4832                                         Expression** pcond,
4833                                         Block** piter_init,
4834                                         Block** ppost)
4835 {
4836   source_location loc = this->location();
4837
4838   // The loop we generate:
4839   //   var next_index_temp int
4840   //   for index_temp = 0; ; index_temp = next_index_temp {
4841   //           next_index_temp, value_temp = stringiter2(range, index_temp)
4842   //           if next_index_temp == 0 {
4843   //                   break
4844   //           }
4845   //           index = index_temp
4846   //           value = value_temp
4847   //           original body
4848   //   }
4849
4850   // Set *PINIT to
4851   //   var next_index_temp int
4852   //   index_temp = 0
4853
4854   Block* init = new Block(enclosing, loc);
4855
4856   Temporary_statement* next_index_temp =
4857     Statement::make_temporary(index_temp->type(), NULL, loc);
4858   init->add_statement(next_index_temp);
4859
4860   mpz_t zval;
4861   mpz_init_set_ui(zval, 0UL);
4862   Expression* zexpr = Expression::make_integer(&zval, NULL, loc);
4863
4864   Expression* ref = Expression::make_temporary_reference(index_temp, loc);
4865   Statement* s = Statement::make_assignment(ref, zexpr, loc);
4866
4867   init->add_statement(s);
4868   *pinit = init;
4869
4870   // The loop has no condition.
4871
4872   *pcond = NULL;
4873
4874   // Set *PITER_INIT to
4875   //   next_index_temp = runtime.stringiter(range, index_temp)
4876   // or
4877   //   next_index_temp, value_temp = runtime.stringiter2(range, index_temp)
4878   // followed by
4879   //   if next_index_temp == 0 {
4880   //           break
4881   //   }
4882
4883   Block* iter_init = new Block(body_block, loc);
4884
4885   Named_object* no;
4886   if (value_temp == NULL)
4887     {
4888       static Named_object* stringiter;
4889       if (stringiter == NULL)
4890         {
4891           source_location bloc = BUILTINS_LOCATION;
4892           Type* int_type = gogo->lookup_global("int")->type_value();
4893
4894           Typed_identifier_list* params = new Typed_identifier_list();
4895           params->push_back(Typed_identifier("s", Type::make_string_type(),
4896                                              bloc));
4897           params->push_back(Typed_identifier("k", int_type, bloc));
4898
4899           Typed_identifier_list* results = new Typed_identifier_list();
4900           results->push_back(Typed_identifier("", int_type, bloc));
4901
4902           Function_type* fntype = Type::make_function_type(NULL, params,
4903                                                            results, bloc);
4904           stringiter = Named_object::make_function_declaration("stringiter",
4905                                                                NULL, fntype,
4906                                                                bloc);
4907           const char* n = "runtime.stringiter";
4908           stringiter->func_declaration_value()->set_asm_name(n);
4909         }
4910       no = stringiter;
4911     }
4912   else
4913     {
4914       static Named_object* stringiter2;
4915       if (stringiter2 == NULL)
4916         {
4917           source_location bloc = BUILTINS_LOCATION;
4918           Type* int_type = gogo->lookup_global("int")->type_value();
4919
4920           Typed_identifier_list* params = new Typed_identifier_list();
4921           params->push_back(Typed_identifier("s", Type::make_string_type(),
4922                                              bloc));
4923           params->push_back(Typed_identifier("k", int_type, bloc));
4924
4925           Typed_identifier_list* results = new Typed_identifier_list();
4926           results->push_back(Typed_identifier("", int_type, bloc));
4927           results->push_back(Typed_identifier("", int_type, bloc));
4928
4929           Function_type* fntype = Type::make_function_type(NULL, params,
4930                                                            results, bloc);
4931           stringiter2 = Named_object::make_function_declaration("stringiter",
4932                                                                 NULL, fntype,
4933                                                                 bloc);
4934           const char* n = "runtime.stringiter2";
4935           stringiter2->func_declaration_value()->set_asm_name(n);
4936         }
4937       no = stringiter2;
4938     }
4939
4940   Expression* func = Expression::make_func_reference(no, NULL, loc);
4941   Expression_list* params = new Expression_list();
4942   params->push_back(this->make_range_ref(range_object, range_temp, loc));
4943   params->push_back(Expression::make_temporary_reference(index_temp, loc));
4944   Call_expression* call = Expression::make_call(func, params, false, loc);
4945
4946   if (value_temp == NULL)
4947     {
4948       ref = Expression::make_temporary_reference(next_index_temp, loc);
4949       s = Statement::make_assignment(ref, call, loc);
4950     }
4951   else
4952     {
4953       Expression_list* lhs = new Expression_list();
4954       lhs->push_back(Expression::make_temporary_reference(next_index_temp,
4955                                                           loc));
4956       lhs->push_back(Expression::make_temporary_reference(value_temp, loc));
4957
4958       Expression_list* rhs = new Expression_list();
4959       rhs->push_back(Expression::make_call_result(call, 0));
4960       rhs->push_back(Expression::make_call_result(call, 1));
4961
4962       s = Statement::make_tuple_assignment(lhs, rhs, loc);
4963     }
4964   iter_init->add_statement(s);
4965
4966   ref = Expression::make_temporary_reference(next_index_temp, loc);
4967   zexpr = Expression::make_integer(&zval, NULL, loc);
4968   mpz_clear(zval);
4969   Expression* equals = Expression::make_binary(OPERATOR_EQEQ, ref, zexpr, loc);
4970
4971   Block* then_block = new Block(iter_init, loc);
4972   s = Statement::make_break_statement(this->break_label(), loc);
4973   then_block->add_statement(s);
4974
4975   s = Statement::make_if_statement(equals, then_block, NULL, loc);
4976   iter_init->add_statement(s);
4977
4978   *piter_init = iter_init;
4979
4980   // Set *PPOST to
4981   //   index_temp = next_index_temp
4982
4983   Block* post = new Block(enclosing, loc);
4984
4985   Expression* lhs = Expression::make_temporary_reference(index_temp, loc);
4986   Expression* rhs = Expression::make_temporary_reference(next_index_temp, loc);
4987   s = Statement::make_assignment(lhs, rhs, loc);
4988
4989   post->add_statement(s);
4990   *ppost = post;
4991 }
4992
4993 // Lower a for range over a map.
4994
4995 void
4996 For_range_statement::lower_range_map(Gogo* gogo,
4997                                      Block* enclosing,
4998                                      Block* body_block,
4999                                      Named_object* range_object,
5000                                      Temporary_statement* range_temp,
5001                                      Temporary_statement* index_temp,
5002                                      Temporary_statement* value_temp,
5003                                      Block** pinit,
5004                                      Expression** pcond,
5005                                      Block** piter_init,
5006                                      Block** ppost)
5007 {
5008   source_location loc = this->location();
5009
5010   // The runtime uses a struct to handle ranges over a map.  The
5011   // struct is four pointers long.  The first pointer is NULL when we
5012   // have completed the iteration.
5013
5014   // The loop we generate:
5015   //   var hiter map_iteration_struct
5016   //   for mapiterinit(range, &hiter); hiter[0] != nil; mapiternext(&hiter) {
5017   //           mapiter2(hiter, &index_temp, &value_temp)
5018   //           index = index_temp
5019   //           value = value_temp
5020   //           original body
5021   //   }
5022
5023   // Set *PINIT to
5024   //   var hiter map_iteration_struct
5025   //   runtime.mapiterinit(range, &hiter)
5026
5027   Block* init = new Block(enclosing, loc);
5028
5029   const unsigned long map_iteration_size = 4;
5030
5031   mpz_t ival;
5032   mpz_init_set_ui(ival, map_iteration_size);
5033   Expression* iexpr = Expression::make_integer(&ival, NULL, loc);
5034   mpz_clear(ival);
5035
5036   Type* byte_type = gogo->lookup_global("byte")->type_value();
5037   Type* ptr_type = Type::make_pointer_type(byte_type);
5038
5039   Type* map_iteration_type = Type::make_array_type(ptr_type, iexpr);
5040   Type* map_iteration_ptr = Type::make_pointer_type(map_iteration_type);
5041
5042   Temporary_statement* hiter = Statement::make_temporary(map_iteration_type,
5043                                                          NULL, loc);
5044   init->add_statement(hiter);
5045
5046   source_location bloc = BUILTINS_LOCATION;
5047   Typed_identifier_list* param_types = new Typed_identifier_list();
5048   param_types->push_back(Typed_identifier("map", this->range_->type(), bloc));
5049   param_types->push_back(Typed_identifier("it", map_iteration_ptr, bloc));
5050   Function_type* fntype = Type::make_function_type(NULL, param_types, NULL,
5051                                                    bloc);
5052
5053   Named_object* mapiterinit =
5054     Named_object::make_function_declaration("mapiterinit", NULL, fntype, bloc);
5055   const char* n = "runtime.mapiterinit";
5056   mapiterinit->func_declaration_value()->set_asm_name(n);
5057
5058   Expression* func = Expression::make_func_reference(mapiterinit, NULL, loc);
5059   Expression_list* params = new Expression_list();
5060   params->push_back(this->make_range_ref(range_object, range_temp, loc));
5061   Expression* ref = Expression::make_temporary_reference(hiter, loc);
5062   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5063   Expression* call = Expression::make_call(func, params, false, loc);
5064   init->add_statement(Statement::make_statement(call));
5065
5066   *pinit = init;
5067
5068   // Set *PCOND to
5069   //   hiter[0] != nil
5070
5071   ref = Expression::make_temporary_reference(hiter, loc);
5072
5073   mpz_t zval;
5074   mpz_init_set_ui(zval, 0UL);
5075   Expression* zexpr = Expression::make_integer(&zval, NULL, loc);
5076   mpz_clear(zval);
5077
5078   Expression* index = Expression::make_index(ref, zexpr, NULL, loc);
5079
5080   Expression* ne = Expression::make_binary(OPERATOR_NOTEQ, index,
5081                                            Expression::make_nil(loc),
5082                                            loc);
5083
5084   *pcond = ne;
5085
5086   // Set *PITER_INIT to
5087   //   mapiter1(hiter, &index_temp)
5088   // or
5089   //   mapiter2(hiter, &index_temp, &value_temp)
5090
5091   Block* iter_init = new Block(body_block, loc);
5092
5093   param_types = new Typed_identifier_list();
5094   param_types->push_back(Typed_identifier("hiter", map_iteration_ptr, bloc));
5095   Type* pkey_type = Type::make_pointer_type(index_temp->type());
5096   param_types->push_back(Typed_identifier("key", pkey_type, bloc));
5097   if (value_temp != NULL)
5098     {
5099       Type* pval_type = Type::make_pointer_type(value_temp->type());
5100       param_types->push_back(Typed_identifier("val", pval_type, bloc));
5101     }
5102   fntype = Type::make_function_type(NULL, param_types, NULL, bloc);
5103   n = value_temp == NULL ? "mapiter1" : "mapiter2";
5104   Named_object* mapiter = Named_object::make_function_declaration(n, NULL,
5105                                                                   fntype, bloc);
5106   n = value_temp == NULL ? "runtime.mapiter1" : "runtime.mapiter2";
5107   mapiter->func_declaration_value()->set_asm_name(n);
5108
5109   func = Expression::make_func_reference(mapiter, NULL, loc);
5110   params = new Expression_list();
5111   ref = Expression::make_temporary_reference(hiter, loc);
5112   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5113   ref = Expression::make_temporary_reference(index_temp, loc);
5114   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5115   if (value_temp != NULL)
5116     {
5117       ref = Expression::make_temporary_reference(value_temp, loc);
5118       params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5119     }
5120   call = Expression::make_call(func, params, false, loc);
5121   iter_init->add_statement(Statement::make_statement(call));
5122
5123   *piter_init = iter_init;
5124
5125   // Set *PPOST to
5126   //   mapiternext(&hiter)
5127
5128   Block* post = new Block(enclosing, loc);
5129
5130   static Named_object* mapiternext;
5131   if (mapiternext == NULL)
5132     {
5133       param_types = new Typed_identifier_list();
5134       param_types->push_back(Typed_identifier("it", map_iteration_ptr, bloc));
5135       fntype = Type::make_function_type(NULL, param_types, NULL, bloc);
5136       mapiternext = Named_object::make_function_declaration("mapiternext",
5137                                                             NULL, fntype,
5138                                                             bloc);
5139       const char* n = "runtime.mapiternext";
5140       mapiternext->func_declaration_value()->set_asm_name(n);
5141     }
5142
5143   func = Expression::make_func_reference(mapiternext, NULL, loc);
5144   params = new Expression_list();
5145   ref = Expression::make_temporary_reference(hiter, loc);
5146   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5147   call = Expression::make_call(func, params, false, loc);
5148   post->add_statement(Statement::make_statement(call));
5149
5150   *ppost = post;
5151 }
5152
5153 // Lower a for range over a channel.
5154
5155 void
5156 For_range_statement::lower_range_channel(Gogo* gogo,
5157                                          Block*,
5158                                          Block* body_block,
5159                                          Named_object* range_object,
5160                                          Temporary_statement* range_temp,
5161                                          Temporary_statement* index_temp,
5162                                          Temporary_statement* value_temp,
5163                                          Block** pinit,
5164                                          Expression** pcond,
5165                                          Block** piter_init,
5166                                          Block** ppost)
5167 {
5168   gcc_assert(value_temp == NULL);
5169
5170   source_location loc = this->location();
5171
5172   // The loop we generate:
5173   //   for {
5174   //           index_temp = <-range
5175   //           if closed(range) {
5176   //                   break
5177   //           }
5178   //           index = index_temp
5179   //           value = value_temp
5180   //           original body
5181   //   }
5182
5183   // We have no initialization code, no condition, and no post code.
5184
5185   *pinit = NULL;
5186   *pcond = NULL;
5187   *ppost = NULL;
5188
5189   // Set *PITER_INIT to
5190   //   index_temp = <-range
5191   //   if closed(range) {
5192   //           break
5193   //   }
5194
5195   Block* iter_init = new Block(body_block, loc);
5196
5197   Expression* ref = this->make_range_ref(range_object, range_temp, loc);
5198   Expression* cond = this->call_builtin(gogo, "closed", ref, loc);
5199
5200   ref = this->make_range_ref(range_object, range_temp, loc);
5201   Expression* recv = Expression::make_receive(ref, loc);
5202   ref = Expression::make_temporary_reference(index_temp, loc);
5203   Statement* s = Statement::make_assignment(ref, recv, loc);
5204   iter_init->add_statement(s);
5205
5206   Block* then_block = new Block(iter_init, loc);
5207   s = Statement::make_break_statement(this->break_label(), loc);
5208   then_block->add_statement(s);
5209
5210   s = Statement::make_if_statement(cond, then_block, NULL, loc);
5211   iter_init->add_statement(s);
5212
5213   *piter_init = iter_init;
5214 }
5215
5216 // Return the break LABEL_EXPR.
5217
5218 Unnamed_label*
5219 For_range_statement::break_label()
5220 {
5221   if (this->break_label_ == NULL)
5222     this->break_label_ = new Unnamed_label(this->location());
5223   return this->break_label_;
5224 }
5225
5226 // Return the continue LABEL_EXPR.
5227
5228 Unnamed_label*
5229 For_range_statement::continue_label()
5230 {
5231   if (this->continue_label_ == NULL)
5232     this->continue_label_ = new Unnamed_label(this->location());
5233   return this->continue_label_;
5234 }
5235
5236 // Make a for statement with a range clause.
5237
5238 For_range_statement*
5239 Statement::make_for_range_statement(Expression* index_var,
5240                                     Expression* value_var,
5241                                     Expression* range,
5242                                     source_location location)
5243 {
5244   return new For_range_statement(index_var, value_var, range, location);
5245 }