Merge pull request #3676 from chamons/SignalHandlerAPI_XM45
[mono.git] / mcs / mcs / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@ximian.com)
7 //   Marek Safar (marek.safar@gmail.com)
8 //
9 // Copyright 2001, 2002, 2003 Ximian, Inc.
10 // Copyright 2003, 2004 Novell, Inc.
11 // Copyright 2011 Xamarin Inc.
12 //
13
14 using System;
15 using System.Collections.Generic;
16
17 #if STATIC
18 using IKVM.Reflection.Emit;
19 #else
20 using System.Reflection.Emit;
21 #endif
22
23 namespace Mono.CSharp {
24         
25         public abstract class Statement {
26                 public Location loc;
27                 protected bool reachable;
28
29                 public bool IsUnreachable {
30                         get {
31                                 return !reachable;
32                         }
33                 }
34                 
35                 /// <summary>
36                 ///   Resolves the statement, true means that all sub-statements
37                 ///   did resolve ok.
38                 ///  </summary>
39                 public virtual bool Resolve (BlockContext bc)
40                 {
41                         return true;
42                 }
43
44                 /// <summary>
45                 ///   Return value indicates whether all code paths emitted return.
46                 /// </summary>
47                 protected abstract void DoEmit (EmitContext ec);
48
49                 public virtual void Emit (EmitContext ec)
50                 {
51                         ec.Mark (loc);
52                         DoEmit (ec);
53
54                         if (ec.StatementEpilogue != null) {
55                                 ec.EmitEpilogue ();
56                         }
57                 }
58
59                 //
60                 // This routine must be overrided in derived classes and make copies
61                 // of all the data that might be modified if resolved
62                 // 
63                 protected abstract void CloneTo (CloneContext clonectx, Statement target);
64
65                 public Statement Clone (CloneContext clonectx)
66                 {
67                         Statement s = (Statement) this.MemberwiseClone ();
68                         CloneTo (clonectx, s);
69                         return s;
70                 }
71
72                 public virtual Expression CreateExpressionTree (ResolveContext ec)
73                 {
74                         ec.Report.Error (834, loc, "A lambda expression with statement body cannot be converted to an expresion tree");
75                         return null;
76                 }
77                 
78                 public virtual object Accept (StructuralVisitor visitor)
79                 {
80                         return visitor.Visit (this);
81                 }
82
83                 //
84                 // Return value indicates whether statement has unreachable end
85                 //
86                 protected abstract bool DoFlowAnalysis (FlowAnalysisContext fc);
87
88                 public bool FlowAnalysis (FlowAnalysisContext fc)
89                 {
90                         if (reachable) {
91                                 fc.UnreachableReported = false;
92                                 var res = DoFlowAnalysis (fc);
93                                 return res;
94                         }
95
96                         //
97                         // Special handling cases
98                         //
99                         if (this is Block) {
100                                 return DoFlowAnalysis (fc);
101                         }
102
103                         if (this is EmptyStatement || loc.IsNull)
104                                 return true;
105
106                         if (fc.UnreachableReported)
107                                 return true;
108
109                         fc.Report.Warning (162, 2, loc, "Unreachable code detected");
110                         fc.UnreachableReported = true;
111                         return true;
112                 }
113
114                 public virtual Reachability MarkReachable (Reachability rc)
115                 {
116                         if (!rc.IsUnreachable)
117                                 reachable = true;
118
119                         return rc;
120                 }
121
122                 protected void CheckExitBoundaries (BlockContext bc, Block scope)
123                 {
124                         if (bc.CurrentBlock.ParametersBlock.Original != scope.ParametersBlock.Original) {
125                                 bc.Report.Error (1632, loc, "Control cannot leave the body of an anonymous method");
126                                 return;
127                         }
128
129                         for (var b = bc.CurrentBlock; b != null && b != scope; b = b.Parent) {
130                                 if (b.IsFinallyBlock) {
131                                         Error_FinallyClauseExit (bc);
132                                         break;
133                                 }
134                         }
135                 }
136
137                 protected void Error_FinallyClauseExit (BlockContext bc)
138                 {
139                         bc.Report.Error (157, loc, "Control cannot leave the body of a finally clause");
140                 }
141         }
142
143         public sealed class EmptyStatement : Statement
144         {
145                 public EmptyStatement (Location loc)
146                 {
147                         this.loc = loc;
148                 }
149
150                 public override bool Resolve (BlockContext ec)
151                 {
152                         return true;
153                 }
154
155                 public override void Emit (EmitContext ec)
156                 {
157                 }
158
159                 protected override void DoEmit (EmitContext ec)
160                 {
161                         throw new NotSupportedException ();
162                 }
163
164                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
165                 {
166                         return false;
167                 }
168
169                 protected override void CloneTo (CloneContext clonectx, Statement target)
170                 {
171                         // nothing needed.
172                 }
173                 
174                 public override object Accept (StructuralVisitor visitor)
175                 {
176                         return visitor.Visit (this);
177                 }
178         }
179
180         public class If : Statement {
181                 Expression expr;
182                 public Statement TrueStatement;
183                 public Statement FalseStatement;
184
185                 bool true_returns, false_returns;
186
187                 public If (Expression bool_expr, Statement true_statement, Location l)
188                         : this (bool_expr, true_statement, null, l)
189                 {
190                 }
191
192                 public If (Expression bool_expr,
193                            Statement true_statement,
194                            Statement false_statement,
195                            Location l)
196                 {
197                         this.expr = bool_expr;
198                         TrueStatement = true_statement;
199                         FalseStatement = false_statement;
200                         loc = l;
201                 }
202
203                 public Expression Expr {
204                         get {
205                                 return this.expr;
206                         }
207                 }
208                 
209                 public override bool Resolve (BlockContext ec)
210                 {
211                         expr = expr.Resolve (ec);
212
213                         var ok = TrueStatement.Resolve (ec);
214
215                         if (FalseStatement != null) {
216                                 ok &= FalseStatement.Resolve (ec);
217                         }
218
219                         return ok;
220                 }
221                 
222                 protected override void DoEmit (EmitContext ec)
223                 {
224                         Label false_target = ec.DefineLabel ();
225                         Label end;
226
227                         //
228                         // If we're a boolean constant, Resolve() already
229                         // eliminated dead code for us.
230                         //
231                         Constant c = expr as Constant;
232                         if (c != null){
233                                 c.EmitSideEffect (ec);
234
235                                 if (!c.IsDefaultValue)
236                                         TrueStatement.Emit (ec);
237                                 else if (FalseStatement != null)
238                                         FalseStatement.Emit (ec);
239
240                                 return;
241                         }                       
242                         
243                         expr.EmitBranchable (ec, false_target, false);
244                         
245                         TrueStatement.Emit (ec);
246
247                         if (FalseStatement != null){
248                                 bool branch_emitted = false;
249                                 
250                                 end = ec.DefineLabel ();
251                                 if (!true_returns){
252                                         ec.Emit (OpCodes.Br, end);
253                                         branch_emitted = true;
254                                 }
255
256                                 ec.MarkLabel (false_target);
257                                 FalseStatement.Emit (ec);
258
259                                 if (branch_emitted)
260                                         ec.MarkLabel (end);
261                         } else {
262                                 ec.MarkLabel (false_target);
263                         }
264                 }
265
266                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
267                 {
268                         expr.FlowAnalysisConditional (fc);
269
270                         var da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
271
272                         fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
273                         var labels = fc.CopyLabelStack ();
274
275                         var res = TrueStatement.FlowAnalysis (fc);
276
277                         fc.SetLabelStack (labels);
278
279                         if (FalseStatement == null) {
280
281                                 var c = expr as Constant;
282                                 if (c != null && !c.IsDefaultValue)
283                                         return true_returns;
284
285                                 if (true_returns)
286                                         fc.DefiniteAssignment = da_false;
287                                 else
288                                         fc.DefiniteAssignment &= da_false;
289  
290                                 return false;
291                         }
292
293                         if (true_returns) {
294                                 fc.DefiniteAssignment = da_false;
295
296                                 res = FalseStatement.FlowAnalysis (fc);
297                                 fc.SetLabelStack (labels);
298                                 return res;
299                         }
300
301                         var da_true = fc.DefiniteAssignment;
302
303                         fc.DefiniteAssignment = da_false;
304
305                         res &= FalseStatement.FlowAnalysis (fc);
306
307                         fc.SetLabelStack (labels);
308
309                         if (!TrueStatement.IsUnreachable) {
310                                 if (false_returns || FalseStatement.IsUnreachable)
311                                         fc.DefiniteAssignment = da_true;
312                                 else
313                                         fc.DefiniteAssignment &= da_true;
314                         }
315
316                         return res;
317                 }
318
319                 public override Reachability MarkReachable (Reachability rc)
320                 {
321                         if (rc.IsUnreachable)
322                                 return rc;
323
324                         base.MarkReachable (rc);
325
326                         var c = expr as Constant;
327                         if (c != null) {
328                                 bool take = !c.IsDefaultValue;
329                                 if (take) {
330                                         rc = TrueStatement.MarkReachable (rc);
331                                 } else {
332                                         if (FalseStatement != null)
333                                                 rc = FalseStatement.MarkReachable (rc);
334                                 }
335
336                                 return rc;
337                         }
338
339                         var true_rc = TrueStatement.MarkReachable (rc);
340                         true_returns = true_rc.IsUnreachable;
341         
342                         if (FalseStatement == null)
343                                 return rc;
344
345                         var false_rc = FalseStatement.MarkReachable (rc);
346                         false_returns = false_rc.IsUnreachable;
347
348                         return true_rc & false_rc;
349                 }
350
351                 protected override void CloneTo (CloneContext clonectx, Statement t)
352                 {
353                         If target = (If) t;
354
355                         target.expr = expr.Clone (clonectx);
356                         target.TrueStatement = TrueStatement.Clone (clonectx);
357                         if (FalseStatement != null)
358                                 target.FalseStatement = FalseStatement.Clone (clonectx);
359                 }
360                 
361                 public override object Accept (StructuralVisitor visitor)
362                 {
363                         return visitor.Visit (this);
364                 }
365         }
366
367         public class Do : LoopStatement
368         {
369                 public Expression expr;
370                 bool iterator_reachable, end_reachable;
371
372                 public Do (Statement statement, BooleanExpression bool_expr, Location doLocation, Location whileLocation)
373                         : base (statement)
374                 {
375                         expr = bool_expr;
376                         loc = doLocation;
377                         WhileLocation = whileLocation;
378                 }
379
380                 public Location WhileLocation {
381                         get; private set;
382                 }
383
384                 public override bool Resolve (BlockContext bc)
385                 {
386                         var ok = base.Resolve (bc);
387
388                         expr = expr.Resolve (bc);
389
390                         return ok;
391                 }
392                 
393                 protected override void DoEmit (EmitContext ec)
394                 {
395                         Label loop = ec.DefineLabel ();
396                         Label old_begin = ec.LoopBegin;
397                         Label old_end = ec.LoopEnd;
398                         
399                         ec.LoopBegin = ec.DefineLabel ();
400                         ec.LoopEnd = ec.DefineLabel ();
401                                 
402                         ec.MarkLabel (loop);
403                         Statement.Emit (ec);
404                         ec.MarkLabel (ec.LoopBegin);
405
406                         // Mark start of while condition
407                         ec.Mark (WhileLocation);
408
409                         //
410                         // Dead code elimination
411                         //
412                         if (expr is Constant) {
413                                 bool res = !((Constant) expr).IsDefaultValue;
414
415                                 expr.EmitSideEffect (ec);
416                                 if (res)
417                                         ec.Emit (OpCodes.Br, loop);
418                         } else {
419                                 expr.EmitBranchable (ec, loop, true);
420                         }
421                         
422                         ec.MarkLabel (ec.LoopEnd);
423
424                         ec.LoopBegin = old_begin;
425                         ec.LoopEnd = old_end;
426                 }
427
428                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
429                 {
430                         var res = Statement.FlowAnalysis (fc);
431
432                         expr.FlowAnalysisConditional (fc);
433
434                         fc.DefiniteAssignment = fc.DefiniteAssignmentOnFalse;
435
436                         if (res && !iterator_reachable)
437                                 return !end_reachable;
438
439                         if (!end_reachable) {
440                                 var c = expr as Constant;
441                                 if (c != null && !c.IsDefaultValue)
442                                         return true;
443                         }
444
445                         return false;
446                 }
447                 
448                 public override Reachability MarkReachable (Reachability rc)
449                 {
450                         base.MarkReachable (rc);
451                         
452                         var body_rc = Statement.MarkReachable (rc);
453
454                         if (body_rc.IsUnreachable && !iterator_reachable) {
455                                 expr = new UnreachableExpression (expr);
456                                 return end_reachable ? rc : Reachability.CreateUnreachable ();
457                         }
458
459                         if (!end_reachable) {
460                                 var c = expr as Constant;
461                                 if (c != null && !c.IsDefaultValue)
462                                         return Reachability.CreateUnreachable ();
463                         }
464
465                         return rc;
466                 }
467
468                 protected override void CloneTo (CloneContext clonectx, Statement t)
469                 {
470                         Do target = (Do) t;
471
472                         target.Statement = Statement.Clone (clonectx);
473                         target.expr = expr.Clone (clonectx);
474                 }
475                 
476                 public override object Accept (StructuralVisitor visitor)
477                 {
478                         return visitor.Visit (this);
479                 }
480
481                 public override void SetEndReachable ()
482                 {
483                         end_reachable = true;
484                 }
485
486                 public override void SetIteratorReachable ()
487                 {
488                         iterator_reachable = true;
489                 }
490         }
491
492         public class While : LoopStatement
493         {
494                 public Expression expr;
495                 bool empty, infinite, end_reachable;
496                 List<DefiniteAssignmentBitSet> end_reachable_das;
497
498                 public While (BooleanExpression bool_expr, Statement statement, Location l)
499                         : base (statement)
500                 {
501                         this.expr = bool_expr;
502                         loc = l;
503                 }
504
505                 public override bool Resolve (BlockContext bc)
506                 {
507                         bool ok = true;
508
509                         expr = expr.Resolve (bc);
510                         if (expr == null)
511                                 ok = false;
512
513                         var c = expr as Constant;
514                         if (c != null) {
515                                 empty = c.IsDefaultValue;
516                                 infinite = !empty;
517                         }
518
519                         ok &= base.Resolve (bc);
520                         return ok;
521                 }
522                 
523                 protected override void DoEmit (EmitContext ec)
524                 {
525                         if (empty) {
526                                 expr.EmitSideEffect (ec);
527                                 return;
528                         }
529
530                         Label old_begin = ec.LoopBegin;
531                         Label old_end = ec.LoopEnd;
532                         
533                         ec.LoopBegin = ec.DefineLabel ();
534                         ec.LoopEnd = ec.DefineLabel ();
535
536                         //
537                         // Inform whether we are infinite or not
538                         //
539                         if (expr is Constant) {
540                                 // expr is 'true', since the 'empty' case above handles the 'false' case
541                                 ec.MarkLabel (ec.LoopBegin);
542
543                                 if (ec.EmitAccurateDebugInfo)
544                                         ec.Emit (OpCodes.Nop);
545
546                                 expr.EmitSideEffect (ec);
547                                 Statement.Emit (ec);
548                                 ec.Emit (OpCodes.Br, ec.LoopBegin);
549                                         
550                                 //
551                                 // Inform that we are infinite (ie, `we return'), only
552                                 // if we do not `break' inside the code.
553                                 //
554                                 ec.MarkLabel (ec.LoopEnd);
555                         } else {
556                                 Label while_loop = ec.DefineLabel ();
557
558                                 ec.Emit (OpCodes.Br, ec.LoopBegin);
559                                 ec.MarkLabel (while_loop);
560
561                                 Statement.Emit (ec);
562                         
563                                 ec.MarkLabel (ec.LoopBegin);
564
565                                 ec.Mark (loc);
566                                 expr.EmitBranchable (ec, while_loop, true);
567                                 
568                                 ec.MarkLabel (ec.LoopEnd);
569                         }       
570
571                         ec.LoopBegin = old_begin;
572                         ec.LoopEnd = old_end;
573                 }
574
575                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
576                 {
577                         expr.FlowAnalysisConditional (fc);
578
579                         fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
580                         var da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
581
582                         Statement.FlowAnalysis (fc);
583
584                         //
585                         // Special case infinite while with breaks
586                         //
587                         if (end_reachable_das != null) {
588                                 da_false = DefiniteAssignmentBitSet.And (end_reachable_das);
589                                 end_reachable_das = null;
590                         }
591
592                         fc.DefiniteAssignment = da_false;
593
594                         if (infinite && !end_reachable)
595                                 return true;
596
597                         return false;
598                 }
599
600                 public override Reachability MarkReachable (Reachability rc)
601                 {
602                         if (rc.IsUnreachable)
603                                 return rc;
604
605                         base.MarkReachable (rc);
606
607                         //
608                         // Special case unreachable while body
609                         //
610                         if (empty) {
611                                 Statement.MarkReachable (Reachability.CreateUnreachable ());
612                                 return rc;
613                         }
614
615                         Statement.MarkReachable (rc);
616
617                         //
618                         // When infinite while end is unreachable via break anything what follows is unreachable too
619                         //
620                         if (infinite && !end_reachable)
621                                 return Reachability.CreateUnreachable ();
622
623                         return rc;
624                 }
625
626                 protected override void CloneTo (CloneContext clonectx, Statement t)
627                 {
628                         While target = (While) t;
629
630                         target.expr = expr.Clone (clonectx);
631                         target.Statement = Statement.Clone (clonectx);
632                 }
633                 
634                 public override object Accept (StructuralVisitor visitor)
635                 {
636                         return visitor.Visit (this);
637                 }
638
639                 public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
640                 {
641                         if (!infinite)
642                                 return;
643
644                         if (end_reachable_das == null)
645                                 end_reachable_das = new List<DefiniteAssignmentBitSet> ();
646
647                         end_reachable_das.Add (fc.DefiniteAssignment);
648                 }
649
650                 public override void SetEndReachable ()
651                 {
652                         end_reachable = true;
653                 }
654         }
655
656         public class For : LoopStatement
657         {
658                 bool infinite, empty, iterator_reachable, end_reachable;
659                 List<DefiniteAssignmentBitSet> end_reachable_das;
660                 
661                 public For (Location l)
662                         : base (null)
663                 {
664                         loc = l;
665                 }
666
667                 public Statement Initializer {
668                         get; set;
669                 }
670
671                 public Expression Condition {
672                         get; set;
673                 }
674
675                 public Statement Iterator {
676                         get; set;
677                 }
678
679                 public override bool Resolve (BlockContext bc)
680                 {
681                         Initializer.Resolve (bc);
682
683                         if (Condition != null) {
684                                 Condition = Condition.Resolve (bc);
685                                 var condition_constant = Condition as Constant;
686                                 if (condition_constant != null) {
687                                         if (condition_constant.IsDefaultValue) {
688                                                 empty = true;
689                                         } else {
690                                                 infinite = true;
691                                         }
692                                 }
693                         } else {
694                                 infinite = true;
695                         }
696
697                         return base.Resolve (bc) && Iterator.Resolve (bc);
698                 }
699
700                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
701                 {
702                         Initializer.FlowAnalysis (fc);
703
704                         DefiniteAssignmentBitSet da_false;
705                         if (Condition != null) {
706                                 Condition.FlowAnalysisConditional (fc);
707                                 fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
708                                 da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
709                         } else {
710                                 da_false = fc.BranchDefiniteAssignment ();
711                         }
712
713                         Statement.FlowAnalysis (fc);
714
715                         Iterator.FlowAnalysis (fc);
716
717                         //
718                         // Special case infinite for with breaks
719                         //
720                         if (end_reachable_das != null) {
721                                 da_false = DefiniteAssignmentBitSet.And (end_reachable_das);
722                                 end_reachable_das = null;
723                         }
724
725                         fc.DefiniteAssignment = da_false;
726
727                         if (infinite && !end_reachable)
728                                 return true;
729
730                         return false;
731                 }
732
733                 public override Reachability MarkReachable (Reachability rc)
734                 {
735                         base.MarkReachable (rc);
736
737                         Initializer.MarkReachable (rc);
738
739                         var body_rc = Statement.MarkReachable (rc);
740                         if (!body_rc.IsUnreachable || iterator_reachable) {
741                                 Iterator.MarkReachable (rc);
742                         }
743
744                         //
745                         // When infinite for end is unreachable via break anything what follows is unreachable too
746                         //
747                         if (infinite && !end_reachable) {
748                                 return Reachability.CreateUnreachable ();
749                         }
750
751                         return rc;
752                 }
753
754                 protected override void DoEmit (EmitContext ec)
755                 {
756                         if (Initializer != null)
757                                 Initializer.Emit (ec);
758
759                         if (empty) {
760                                 Condition.EmitSideEffect (ec);
761                                 return;
762                         }
763
764                         Label old_begin = ec.LoopBegin;
765                         Label old_end = ec.LoopEnd;
766                         Label loop = ec.DefineLabel ();
767                         Label test = ec.DefineLabel ();
768
769                         ec.LoopBegin = ec.DefineLabel ();
770                         ec.LoopEnd = ec.DefineLabel ();
771
772                         ec.Emit (OpCodes.Br, test);
773                         ec.MarkLabel (loop);
774                         Statement.Emit (ec);
775
776                         ec.MarkLabel (ec.LoopBegin);
777                         Iterator.Emit (ec);
778
779                         ec.MarkLabel (test);
780                         //
781                         // If test is null, there is no test, and we are just
782                         // an infinite loop
783                         //
784                         if (Condition != null) {
785                                 ec.Mark (Condition.Location);
786
787                                 //
788                                 // The Resolve code already catches the case for
789                                 // Test == Constant (false) so we know that
790                                 // this is true
791                                 //
792                                 if (Condition is Constant) {
793                                         Condition.EmitSideEffect (ec);
794                                         ec.Emit (OpCodes.Br, loop);
795                                 } else {
796                                         Condition.EmitBranchable (ec, loop, true);
797                                 }
798                                 
799                         } else
800                                 ec.Emit (OpCodes.Br, loop);
801                         ec.MarkLabel (ec.LoopEnd);
802
803                         ec.LoopBegin = old_begin;
804                         ec.LoopEnd = old_end;
805                 }
806
807                 protected override void CloneTo (CloneContext clonectx, Statement t)
808                 {
809                         For target = (For) t;
810
811                         if (Initializer != null)
812                                 target.Initializer = Initializer.Clone (clonectx);
813                         if (Condition != null)
814                                 target.Condition = Condition.Clone (clonectx);
815                         if (Iterator != null)
816                                 target.Iterator = Iterator.Clone (clonectx);
817                         target.Statement = Statement.Clone (clonectx);
818                 }
819
820                 public override object Accept (StructuralVisitor visitor)
821                 {
822                         return visitor.Visit (this);
823                 }
824
825                 public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
826                 {
827                         if (!infinite)
828                                 return;
829
830                         if (end_reachable_das == null)
831                                 end_reachable_das = new List<DefiniteAssignmentBitSet> ();
832
833                         end_reachable_das.Add (fc.DefiniteAssignment);
834                 }
835
836                 public override void SetEndReachable ()
837                 {
838                         end_reachable = true;
839                 }
840
841                 public override void SetIteratorReachable ()
842                 {
843                         iterator_reachable = true;
844                 }
845         }
846
847         public abstract class LoopStatement : Statement
848         {
849                 protected LoopStatement (Statement statement)
850                 {
851                         Statement = statement;
852                 }
853
854                 public Statement Statement { get; set; }
855
856                 public override bool Resolve (BlockContext bc)
857                 {
858                         var prev_loop = bc.EnclosingLoop;
859                         var prev_los = bc.EnclosingLoopOrSwitch;
860                         bc.EnclosingLoopOrSwitch = bc.EnclosingLoop = this;
861                         var ok = Statement.Resolve (bc);
862                         bc.EnclosingLoopOrSwitch = prev_los;
863                         bc.EnclosingLoop = prev_loop;
864
865                         return ok;
866                 }
867
868                 //
869                 // Needed by possibly infinite loops statements (for, while) and switch statment
870                 //
871                 public virtual void AddEndDefiniteAssignment (FlowAnalysisContext fc)
872                 {
873                 }
874
875                 public virtual void SetEndReachable ()
876                 {
877                 }
878
879                 public virtual void SetIteratorReachable ()
880                 {
881                 }
882         }
883         
884         public class StatementExpression : Statement
885         {
886                 ExpressionStatement expr;
887                 
888                 public StatementExpression (ExpressionStatement expr)
889                 {
890                         this.expr = expr;
891                         loc = expr.StartLocation;
892                 }
893
894                 public StatementExpression (ExpressionStatement expr, Location loc)
895                 {
896                         this.expr = expr;
897                         this.loc = loc;
898                 }
899
900                 public ExpressionStatement Expr {
901                         get {
902                                 return this.expr;
903                         }
904                 }
905                 
906                 protected override void CloneTo (CloneContext clonectx, Statement t)
907                 {
908                         StatementExpression target = (StatementExpression) t;
909                         target.expr = (ExpressionStatement) expr.Clone (clonectx);
910                 }
911                 
912                 protected override void DoEmit (EmitContext ec)
913                 {
914                         expr.EmitStatement (ec);
915                 }
916
917                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
918                 {
919                         expr.FlowAnalysis (fc);
920                         return false;
921                 }
922
923                 public override Reachability MarkReachable (Reachability rc)
924                 {
925                         base.MarkReachable (rc);
926                         expr.MarkReachable (rc);
927                         return rc;
928                 }
929
930                 public override bool Resolve (BlockContext ec)
931                 {
932                         expr = expr.ResolveStatement (ec);
933                         return expr != null;
934                 }
935                 
936                 public override object Accept (StructuralVisitor visitor)
937                 {
938                         return visitor.Visit (this);
939                 }
940         }
941
942         public class StatementErrorExpression : Statement
943         {
944                 Expression expr;
945
946                 public StatementErrorExpression (Expression expr)
947                 {
948                         this.expr = expr;
949                         this.loc = expr.StartLocation;
950                 }
951
952                 public Expression Expr {
953                         get {
954                                 return expr;
955                         }
956                 }
957
958                 public override bool Resolve (BlockContext bc)
959                 {
960                         expr.Error_InvalidExpressionStatement (bc);
961                         return true;
962                 }
963
964                 protected override void DoEmit (EmitContext ec)
965                 {
966                         throw new NotSupportedException ();
967                 }
968
969                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
970                 {
971                         return false;
972                 }
973
974                 protected override void CloneTo (CloneContext clonectx, Statement target)
975                 {
976                         var t = (StatementErrorExpression) target;
977
978                         t.expr = expr.Clone (clonectx);
979                 }
980                 
981                 public override object Accept (StructuralVisitor visitor)
982                 {
983                         return visitor.Visit (this);
984                 }
985         }
986
987         //
988         // Simple version of statement list not requiring a block
989         //
990         public class StatementList : Statement
991         {
992                 List<Statement> statements;
993
994                 public StatementList (Statement first, Statement second)
995                 {
996                         statements = new List<Statement> { first, second };
997                 }
998
999                 #region Properties
1000                 public IList<Statement> Statements {
1001                         get {
1002                                 return statements;
1003                         }
1004                 }
1005                 #endregion
1006
1007                 public void Add (Statement statement)
1008                 {
1009                         statements.Add (statement);
1010                 }
1011
1012                 public override bool Resolve (BlockContext ec)
1013                 {
1014                         foreach (var s in statements)
1015                                 s.Resolve (ec);
1016
1017                         return true;
1018                 }
1019
1020                 protected override void DoEmit (EmitContext ec)
1021                 {
1022                         foreach (var s in statements)
1023                                 s.Emit (ec);
1024                 }
1025
1026                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1027                 {
1028                         foreach (var s in statements)
1029                                 s.FlowAnalysis (fc);
1030
1031                         return false;
1032                 }
1033
1034                 public override Reachability MarkReachable (Reachability rc)
1035                 {
1036                         base.MarkReachable (rc);
1037
1038                         Reachability res = rc;
1039                         foreach (var s in statements)
1040                                 res = s.MarkReachable (rc);
1041
1042                         return res;
1043                 }
1044
1045                 protected override void CloneTo (CloneContext clonectx, Statement target)
1046                 {
1047                         StatementList t = (StatementList) target;
1048
1049                         t.statements = new List<Statement> (statements.Count);
1050                         foreach (Statement s in statements)
1051                                 t.statements.Add (s.Clone (clonectx));
1052                 }
1053                 
1054                 public override object Accept (StructuralVisitor visitor)
1055                 {
1056                         return visitor.Visit (this);
1057                 }
1058         }
1059
1060         //
1061         // For statements which require special handling when inside try or catch block
1062         //
1063         public abstract class ExitStatement : Statement
1064         {
1065                 protected bool unwind_protect;
1066
1067                 protected abstract bool DoResolve (BlockContext bc);
1068                 protected abstract bool IsLocalExit { get; }
1069
1070                 public override bool Resolve (BlockContext bc)
1071                 {
1072                         var res = DoResolve (bc);
1073
1074                         if (!IsLocalExit) {
1075                                 //
1076                                 // We are inside finally scope but is it the scope we are exiting
1077                                 //
1078                                 if (bc.HasSet (ResolveContext.Options.FinallyScope)) {
1079
1080                                         for (var b = bc.CurrentBlock; b != null; b = b.Parent) {
1081                                                 if (b.IsFinallyBlock) {
1082                                                         Error_FinallyClauseExit (bc);
1083                                                         break;
1084                                                 }
1085
1086                                                 if (b is ParametersBlock)
1087                                                         break;
1088                                         }
1089                                 }
1090                         }
1091
1092                         unwind_protect = bc.HasAny (ResolveContext.Options.TryScope | ResolveContext.Options.CatchScope);
1093                         return res;
1094                 }
1095
1096                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1097                 {
1098                         if (IsLocalExit)
1099                                 return true;
1100
1101                         if (fc.TryFinally != null) {
1102                             fc.TryFinally.RegisterForControlExitCheck (new DefiniteAssignmentBitSet (fc.DefiniteAssignment));
1103                         } else {
1104                             fc.ParametersBlock.CheckControlExit (fc);
1105                         }
1106
1107                         return true;
1108                 }
1109         }
1110
1111         /// <summary>
1112         ///   Implements the return statement
1113         /// </summary>
1114         public class Return : ExitStatement
1115         {
1116                 Expression expr;
1117
1118                 public Return (Expression expr, Location l)
1119                 {
1120                         this.expr = expr;
1121                         loc = l;
1122                 }
1123
1124                 #region Properties
1125
1126                 public Expression Expr {
1127                         get {
1128                                 return expr;
1129                         }
1130                         protected set {
1131                                 expr = value;
1132                         }
1133                 }
1134
1135                 protected override bool IsLocalExit {
1136                         get {
1137                                 return false;
1138                         }
1139                 }
1140
1141                 #endregion
1142
1143                 protected override bool DoResolve (BlockContext ec)
1144                 {
1145                         var block_return_type = ec.ReturnType;
1146
1147                         if (expr == null) {
1148                                 if (block_return_type.Kind == MemberKind.Void || block_return_type == InternalType.ErrorType)
1149                                         return true;
1150
1151                                 //
1152                                 // Return must not be followed by an expression when
1153                                 // the method return type is Task
1154                                 //
1155                                 if (ec.CurrentAnonymousMethod is AsyncInitializer) {
1156                                         var storey = (AsyncTaskStorey) ec.CurrentAnonymousMethod.Storey;
1157                                         if (storey.ReturnType == ec.Module.PredefinedTypes.Task.TypeSpec) {
1158                                                 //
1159                                                 // Extra trick not to emit ret/leave inside awaiter body
1160                                                 //
1161                                                 expr = EmptyExpression.Null;
1162                                                 return true;
1163                                         }
1164
1165                                         if (storey.ReturnType.IsGenericTask)
1166                                                 block_return_type = storey.ReturnType.TypeArguments[0];
1167                                 }
1168
1169                                 if (ec.CurrentIterator != null) {
1170                                         Error_ReturnFromIterator (ec);
1171                                 } else if (block_return_type != InternalType.ErrorType) {
1172                                         ec.Report.Error (126, loc,
1173                                                 "An object of a type convertible to `{0}' is required for the return statement",
1174                                                 block_return_type.GetSignatureForError ());
1175                                 }
1176
1177                                 return false;
1178                         }
1179
1180                         expr = expr.Resolve (ec);
1181
1182                         AnonymousExpression am = ec.CurrentAnonymousMethod;
1183                         if (am == null) {
1184                                 if (block_return_type.Kind == MemberKind.Void) {
1185                                         ec.Report.Error (127, loc,
1186                                                 "`{0}': A return keyword must not be followed by any expression when method returns void",
1187                                                 ec.GetSignatureForError ());
1188
1189                                         return false;
1190                                 }
1191                         } else {
1192                                 if (am.IsIterator) {
1193                                         Error_ReturnFromIterator (ec);
1194                                         return false;
1195                                 }
1196
1197                                 var async_block = am as AsyncInitializer;
1198                                 if (async_block != null) {
1199                                         if (expr != null) {
1200                                                 var storey = (AsyncTaskStorey) am.Storey;
1201                                                 var async_type = storey.ReturnType;
1202
1203                                                 if (async_type == null && async_block.ReturnTypeInference != null) {
1204                                                         if (expr.Type.Kind == MemberKind.Void && !(this is ContextualReturn))
1205                                                                 ec.Report.Error (4029, loc, "Cannot return an expression of type `void'");
1206                                                         else
1207                                                                 async_block.ReturnTypeInference.AddCommonTypeBoundAsync (expr.Type);
1208                                                         return true;
1209                                                 }
1210
1211                                                 if (async_type.Kind == MemberKind.Void) {
1212                                                         ec.Report.Error (8030, loc,
1213                                                                 "Anonymous function or lambda expression converted to a void returning delegate cannot return a value");
1214                                                         return false;
1215                                                 }
1216
1217                                                 if (!async_type.IsGenericTask) {
1218                                                         if (this is ContextualReturn)
1219                                                                 return true;
1220
1221                                                         if (async_block.DelegateType != null) {
1222                                                                 ec.Report.Error (8031, loc,
1223                                                                         "Async lambda expression or anonymous method converted to a `Task' cannot return a value. Consider returning `Task<T>'");
1224                                                         } else {
1225                                                                 ec.Report.Error (1997, loc,
1226                                                                         "`{0}': A return keyword must not be followed by an expression when async method returns `Task'. Consider using `Task<T>' return type",
1227                                                                         ec.GetSignatureForError ());
1228                                                         }
1229                                                         return false;
1230                                                 }
1231
1232                                                 //
1233                                                 // The return type is actually Task<T> type argument
1234                                                 //
1235                                                 if (expr.Type == async_type && async_type.TypeArguments [0] != ec.Module.PredefinedTypes.Task.TypeSpec) {
1236                                                         ec.Report.Error (4016, loc,
1237                                                                 "`{0}': The return expression type of async method must be `{1}' rather than `Task<{1}>'",
1238                                                                 ec.GetSignatureForError (), async_type.TypeArguments[0].GetSignatureForError ());
1239                                                 } else {
1240                                                         block_return_type = async_type.TypeArguments[0];
1241                                                 }
1242                                         }
1243                                 } else {
1244                                         if (block_return_type.Kind == MemberKind.Void) {
1245                                                 ec.Report.Error (8030, loc,
1246                                                         "Anonymous function or lambda expression converted to a void returning delegate cannot return a value");
1247                                                 return false;
1248                                         }
1249
1250                                         var l = am as AnonymousMethodBody;
1251                                         if (l != null && expr != null) {
1252                                                 if (l.ReturnTypeInference != null) {
1253                                                         l.ReturnTypeInference.AddCommonTypeBound (expr.Type);
1254                                                         return true;
1255                                                 }
1256
1257                                                 //
1258                                                 // Try to optimize simple lambda. Only when optimizations are enabled not to cause
1259                                                 // unexpected debugging experience
1260                                                 //
1261                                                 if (this is ContextualReturn && !ec.IsInProbingMode && ec.Module.Compiler.Settings.Optimize) {
1262                                                         l.DirectMethodGroupConversion = expr.CanReduceLambda (l);
1263                                                 }
1264                                         }
1265                                 }
1266                         }
1267
1268                         if (expr == null)
1269                                 return false;
1270
1271                         if (expr.Type != block_return_type && expr.Type != InternalType.ErrorType) {
1272                                 expr = Convert.ImplicitConversionRequired (ec, expr, block_return_type, loc);
1273
1274                                 if (expr == null) {
1275                                         if (am != null && block_return_type == ec.ReturnType) {
1276                                                 ec.Report.Error (1662, loc,
1277                                                         "Cannot convert `{0}' to delegate type `{1}' because some of the return types in the block are not implicitly convertible to the delegate return type",
1278                                                         am.ContainerType, am.GetSignatureForError ());
1279                                         }
1280                                         return false;
1281                                 }
1282                         }
1283
1284                         return true;                    
1285                 }
1286                 
1287                 protected override void DoEmit (EmitContext ec)
1288                 {
1289                         if (expr != null) {
1290
1291                                 var async_body = ec.CurrentAnonymousMethod as AsyncInitializer;
1292                                 if (async_body != null) {
1293                                         var storey = (AsyncTaskStorey)async_body.Storey;
1294                                         Label exit_label = async_body.BodyEnd;
1295
1296                                         //
1297                                         // It's null for await without async
1298                                         //
1299                                         if (storey.HoistedReturnValue != null) {
1300                                                 //
1301                                                 // Special case hoisted return value (happens in try/finally scenario)
1302                                                 //
1303                                                 if (ec.TryFinallyUnwind != null) {
1304                                                         exit_label = TryFinally.EmitRedirectedReturn (ec, async_body);
1305                                                 }
1306
1307                                                 var async_return = (IAssignMethod)storey.HoistedReturnValue;
1308                                                 async_return.EmitAssign (ec, expr, false, false);
1309                                                 ec.EmitEpilogue ();
1310                                         } else {
1311                                                 expr.Emit (ec);
1312
1313                                                 if (ec.TryFinallyUnwind != null)
1314                                                         exit_label = TryFinally.EmitRedirectedReturn (ec, async_body);
1315                                         }
1316
1317                                         ec.Emit (OpCodes.Leave, exit_label);
1318                                         return;
1319                                 }
1320
1321                                 expr.Emit (ec);
1322                                 ec.EmitEpilogue ();
1323
1324                                 if (unwind_protect || ec.EmitAccurateDebugInfo)
1325                                         ec.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
1326                         }
1327
1328                         if (unwind_protect) {
1329                                 ec.Emit (OpCodes.Leave, ec.CreateReturnLabel ());
1330                         } else if (ec.EmitAccurateDebugInfo) {
1331                                 ec.Emit (OpCodes.Br, ec.CreateReturnLabel ());
1332                         } else {
1333                                 ec.Emit (OpCodes.Ret);
1334                         }
1335                 }
1336
1337                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1338                 {
1339                         if (expr != null)
1340                                 expr.FlowAnalysis (fc);
1341
1342                         base.DoFlowAnalysis (fc);
1343                         return true;
1344                 }
1345
1346                 void Error_ReturnFromIterator (ResolveContext rc)
1347                 {
1348                         rc.Report.Error (1622, loc,
1349                                 "Cannot return a value from iterators. Use the yield return statement to return a value, or yield break to end the iteration");
1350                 }
1351
1352                 public override Reachability MarkReachable (Reachability rc)
1353                 {
1354                         base.MarkReachable (rc);
1355                         return Reachability.CreateUnreachable ();
1356                 }
1357
1358                 protected override void CloneTo (CloneContext clonectx, Statement t)
1359                 {
1360                         Return target = (Return) t;
1361                         // It's null for simple return;
1362                         if (expr != null)
1363                                 target.expr = expr.Clone (clonectx);
1364                 }
1365
1366                 public override object Accept (StructuralVisitor visitor)
1367                 {
1368                         return visitor.Visit (this);
1369                 }
1370         }
1371
1372         public class Goto : ExitStatement
1373         {
1374                 string target;
1375                 LabeledStatement label;
1376                 TryFinally try_finally;
1377
1378                 public Goto (string label, Location l)
1379                 {
1380                         loc = l;
1381                         target = label;
1382                 }
1383
1384                 public string Target {
1385                         get { return target; }
1386                 }
1387
1388                 protected override bool IsLocalExit {
1389                         get {
1390                                 return true;
1391                         }
1392                 }
1393
1394                 protected override bool DoResolve (BlockContext bc)
1395                 {
1396                         label = bc.CurrentBlock.LookupLabel (target);
1397                         if (label == null) {
1398                                 Error_UnknownLabel (bc, target, loc);
1399                                 return false;
1400                         }
1401
1402                         try_finally = bc.CurrentTryBlock as TryFinally;
1403
1404                         CheckExitBoundaries (bc, label.Block);
1405
1406                         return true;
1407                 }
1408
1409                 public static void Error_UnknownLabel (BlockContext bc, string label, Location loc)
1410                 {
1411                         bc.Report.Error (159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
1412                                 label);
1413                 }
1414
1415                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1416                 {
1417                         // Goto to unreachable label
1418                         if (label == null)
1419                                 return true;
1420
1421                         if (fc.AddReachedLabel (label))
1422                                 return true;
1423
1424                         label.Block.ScanGotoJump (label, fc);
1425                         return true;
1426                 }
1427
1428                 public override Reachability MarkReachable (Reachability rc)
1429                 {
1430                         if (rc.IsUnreachable)
1431                                 return rc;
1432
1433                         base.MarkReachable (rc);
1434
1435                         if (try_finally != null) {
1436                                 if (try_finally.FinallyBlock.HasReachableClosingBrace) {
1437                                         label.AddGotoReference (rc);
1438                                 } else {
1439                                         label = null;
1440                                 }
1441                         } else {
1442                                 label.AddGotoReference (rc);
1443                         }
1444
1445                         return Reachability.CreateUnreachable ();
1446                 }
1447
1448                 protected override void CloneTo (CloneContext clonectx, Statement target)
1449                 {
1450                         // Nothing to clone
1451                 }
1452
1453                 protected override void DoEmit (EmitContext ec)
1454                 {
1455                         // This should only happen for goto from try block to unrechable label
1456                         if (label == null)
1457                                 return;
1458
1459                         Label l = label.LabelTarget (ec);
1460
1461                         if (ec.TryFinallyUnwind != null && IsLeavingFinally (label.Block)) {
1462                                 var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
1463                                 l = TryFinally.EmitRedirectedJump (ec, async_body, l, label.Block);
1464                         }
1465
1466                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
1467                 }
1468
1469                 bool IsLeavingFinally (Block labelBlock)
1470                 {
1471                         var b = try_finally.Statement as Block;
1472                         while (b != null) {
1473                                 if (b == labelBlock)
1474                                         return true;
1475
1476                                 b = b.Parent;
1477                         }
1478
1479                         return false;
1480                 }
1481                 
1482                 public override object Accept (StructuralVisitor visitor)
1483                 {
1484                         return visitor.Visit (this);
1485                 }
1486         }
1487
1488         public class LabeledStatement : Statement {
1489                 string name;
1490                 bool defined;
1491                 bool referenced;
1492                 Label label;
1493                 Block block;
1494                 
1495                 public LabeledStatement (string name, Block block, Location l)
1496                 {
1497                         this.name = name;
1498                         this.block = block;
1499                         this.loc = l;
1500                 }
1501
1502                 public Label LabelTarget (EmitContext ec)
1503                 {
1504                         if (defined)
1505                                 return label;
1506
1507                         label = ec.DefineLabel ();
1508                         defined = true;
1509                         return label;
1510                 }
1511
1512                 public Block Block {
1513                         get {
1514                                 return block;
1515                         }
1516                 }
1517
1518                 public string Name {
1519                         get { return name; }
1520                 }
1521
1522                 protected override void CloneTo (CloneContext clonectx, Statement target)
1523                 {
1524                         var t = (LabeledStatement) target;
1525
1526                         t.block = clonectx.RemapBlockCopy (block);
1527                 }
1528
1529                 public override bool Resolve (BlockContext bc)
1530                 {
1531                         return true;
1532                 }
1533
1534                 protected override void DoEmit (EmitContext ec)
1535                 {
1536                         LabelTarget (ec);
1537                         ec.MarkLabel (label);
1538                 }
1539
1540                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1541                 {
1542                         if (!referenced) {
1543                                 fc.Report.Warning (164, 2, loc, "This label has not been referenced");
1544                         }
1545
1546                         return false;
1547                 }
1548
1549                 public override Reachability MarkReachable (Reachability rc)
1550                 {
1551                         base.MarkReachable (rc);
1552
1553                         if (referenced)
1554                                 rc = new Reachability ();
1555
1556                         return rc;
1557                 }
1558
1559                 public void AddGotoReference (Reachability rc)
1560                 {
1561                         if (referenced)
1562                                 return;
1563
1564                         referenced = true;
1565                         MarkReachable (rc);
1566
1567                         block.ScanGotoJump (this);
1568                 }
1569
1570                 public override object Accept (StructuralVisitor visitor)
1571                 {
1572                         return visitor.Visit (this);
1573                 }
1574         }
1575         
1576
1577         /// <summary>
1578         ///   `goto default' statement
1579         /// </summary>
1580         public class GotoDefault : SwitchGoto
1581         {               
1582                 public GotoDefault (Location l)
1583                         : base (l)
1584                 {
1585                 }
1586
1587                 public override bool Resolve (BlockContext bc)
1588                 {
1589                         if (bc.Switch == null) {
1590                                 Error_GotoCaseRequiresSwitchBlock (bc);
1591                                 return false;
1592                         }
1593
1594                         bc.Switch.RegisterGotoCase (null, null);
1595                         base.Resolve (bc);
1596
1597                         return true;
1598                 }
1599
1600                 protected override void DoEmit (EmitContext ec)
1601                 {
1602                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.Switch.DefaultLabel.GetILLabel (ec));
1603                 }
1604
1605                 public override Reachability MarkReachable (Reachability rc)
1606                 {
1607                         if (!rc.IsUnreachable) {
1608                                 var label = switch_statement.DefaultLabel;
1609                                 if (label.IsUnreachable) {
1610                                         label.MarkReachable (rc);
1611                                         switch_statement.Block.ScanGotoJump (label);
1612                                 }
1613                         }
1614
1615                         return base.MarkReachable (rc);
1616                 }
1617
1618                 public override object Accept (StructuralVisitor visitor)
1619                 {
1620                         return visitor.Visit (this);
1621                 }
1622         }
1623
1624         /// <summary>
1625         ///   `goto case' statement
1626         /// </summary>
1627         public class GotoCase : SwitchGoto
1628         {
1629                 Expression expr;
1630                 
1631                 public GotoCase (Expression e, Location l)
1632                         : base (l)
1633                 {
1634                         expr = e;
1635                 }
1636
1637                 public Expression Expr {
1638                         get {
1639                                 return expr;
1640                         }
1641                 }
1642
1643                 public SwitchLabel Label { get; set; }
1644
1645                 public override bool Resolve (BlockContext ec)
1646                 {
1647                         if (ec.Switch == null) {
1648                                 Error_GotoCaseRequiresSwitchBlock (ec);
1649                                 return false;
1650                         }
1651
1652                         Constant c = expr.ResolveLabelConstant (ec);
1653                         if (c == null) {
1654                                 return false;
1655                         }
1656
1657                         Constant res;
1658                         if (ec.Switch.IsNullable && c is NullLiteral) {
1659                                 res = c;
1660                         } else {
1661                                 TypeSpec type = ec.Switch.SwitchType;
1662                                 res = c.Reduce (ec, type);
1663                                 if (res == null) {
1664                                         c.Error_ValueCannotBeConverted (ec, type, true);
1665                                         return false;
1666                                 }
1667
1668                                 if (!Convert.ImplicitStandardConversionExists (c, type))
1669                                         ec.Report.Warning (469, 2, loc,
1670                                                 "The `goto case' value is not implicitly convertible to type `{0}'",
1671                                                 type.GetSignatureForError ());
1672
1673                         }
1674
1675                         ec.Switch.RegisterGotoCase (this, res);
1676                         base.Resolve (ec);
1677                         expr = res;
1678
1679                         return true;
1680                 }
1681
1682                 protected override void DoEmit (EmitContext ec)
1683                 {
1684                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, Label.GetILLabel (ec));
1685                 }
1686
1687                 protected override void CloneTo (CloneContext clonectx, Statement t)
1688                 {
1689                         GotoCase target = (GotoCase) t;
1690
1691                         target.expr = expr.Clone (clonectx);
1692                 }
1693
1694                 public override Reachability MarkReachable (Reachability rc)
1695                 {
1696                         if (!rc.IsUnreachable) {
1697                                 var label = switch_statement.FindLabel ((Constant) expr);
1698                                 if (label.IsUnreachable) {
1699                                         label.MarkReachable (rc);
1700                                         switch_statement.Block.ScanGotoJump (label);
1701                                 }
1702                         }
1703
1704                         return base.MarkReachable (rc);
1705                 }
1706                 
1707                 public override object Accept (StructuralVisitor visitor)
1708                 {
1709                         return visitor.Visit (this);
1710                 }
1711         }
1712
1713         public abstract class SwitchGoto : Statement
1714         {
1715                 protected bool unwind_protect;
1716                 protected Switch switch_statement;
1717
1718                 protected SwitchGoto (Location loc)
1719                 {
1720                         this.loc = loc;
1721                 }
1722
1723                 protected override void CloneTo (CloneContext clonectx, Statement target)
1724                 {
1725                         // Nothing to clone
1726                 }
1727
1728                 public override bool Resolve (BlockContext bc)
1729                 {
1730                         CheckExitBoundaries (bc, bc.Switch.Block);
1731
1732                         unwind_protect = bc.HasAny (ResolveContext.Options.TryScope | ResolveContext.Options.CatchScope);
1733                         switch_statement = bc.Switch;
1734
1735                         return true;
1736                 }
1737
1738                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1739                 {
1740                         return true;
1741                 }
1742
1743                 public override Reachability MarkReachable (Reachability rc)
1744                 {
1745                         base.MarkReachable (rc);
1746                         return Reachability.CreateUnreachable ();
1747                 }
1748
1749                 protected void Error_GotoCaseRequiresSwitchBlock (BlockContext bc)
1750                 {
1751                         bc.Report.Error (153, loc, "A goto case is only valid inside a switch statement");
1752                 }
1753         }
1754         
1755         public class Throw : Statement {
1756                 Expression expr;
1757                 
1758                 public Throw (Expression expr, Location l)
1759                 {
1760                         this.expr = expr;
1761                         loc = l;
1762                 }
1763
1764                 public Expression Expr {
1765                         get {
1766                                 return this.expr;
1767                         }
1768                 }
1769
1770                 public override bool Resolve (BlockContext ec)
1771                 {
1772                         if (expr == null) {
1773                                 if (!ec.HasSet (ResolveContext.Options.CatchScope)) {
1774                                         ec.Report.Error (156, loc, "A throw statement with no arguments is not allowed outside of a catch clause");
1775                                 } else if (ec.HasSet (ResolveContext.Options.FinallyScope)) {
1776                                         for (var b = ec.CurrentBlock; b != null && !b.IsCatchBlock; b = b.Parent) {
1777                                                 if (b.IsFinallyBlock) {
1778                                                         ec.Report.Error (724, loc,
1779                                                                 "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1780                                                         break;
1781                                                 }
1782                                         }
1783                                 }
1784
1785                                 return true;
1786                         }
1787
1788                         expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
1789
1790                         if (expr == null)
1791                                 return false;
1792
1793                         var et = ec.BuiltinTypes.Exception;
1794                         if (Convert.ImplicitConversionExists (ec, expr, et))
1795                                 expr = Convert.ImplicitConversion (ec, expr, et, loc);
1796                         else
1797                                 ec.Report.Error (155, expr.Location, "The type caught or thrown must be derived from System.Exception");
1798
1799                         return true;
1800                 }
1801                         
1802                 protected override void DoEmit (EmitContext ec)
1803                 {
1804                         if (expr == null) {
1805                                 var atv = ec.AsyncThrowVariable;
1806                                 if (atv != null) {
1807                                         if (atv.HoistedVariant != null) {
1808                                                 atv.HoistedVariant.Emit (ec);
1809                                         } else {
1810                                                 atv.Emit (ec);
1811                                         }
1812
1813                                         ec.Emit (OpCodes.Throw);
1814                                 } else {
1815                                         ec.Emit (OpCodes.Rethrow);
1816                                 }
1817                         } else {
1818                                 expr.Emit (ec);
1819
1820                                 ec.Emit (OpCodes.Throw);
1821                         }
1822                 }
1823
1824                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1825                 {
1826                         if (expr != null)
1827                                 expr.FlowAnalysis (fc);
1828
1829                         return true;
1830                 }
1831
1832                 public override Reachability MarkReachable (Reachability rc)
1833                 {
1834                         base.MarkReachable (rc);
1835                         return Reachability.CreateUnreachable ();
1836                 }
1837
1838                 protected override void CloneTo (CloneContext clonectx, Statement t)
1839                 {
1840                         Throw target = (Throw) t;
1841
1842                         if (expr != null)
1843                                 target.expr = expr.Clone (clonectx);
1844                 }
1845                 
1846                 public override object Accept (StructuralVisitor visitor)
1847                 {
1848                         return visitor.Visit (this);
1849                 }
1850         }
1851
1852         public class Break : LocalExitStatement
1853         {               
1854                 public Break (Location l)
1855                         : base (l)
1856                 {
1857                 }
1858                 
1859                 public override object Accept (StructuralVisitor visitor)
1860                 {
1861                         return visitor.Visit (this);
1862                 }
1863
1864                 protected override void DoEmit (EmitContext ec)
1865                 {
1866                         var l = ec.LoopEnd;
1867
1868                         if (ec.TryFinallyUnwind != null) {
1869                                 var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
1870                                 l = TryFinally.EmitRedirectedJump (ec, async_body, l, enclosing_loop.Statement as Block);
1871                         }
1872
1873                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
1874                 }
1875
1876                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1877                 {
1878                         enclosing_loop.AddEndDefiniteAssignment (fc);
1879                         return true;
1880                 }
1881
1882                 protected override bool DoResolve (BlockContext bc)
1883                 {
1884                         enclosing_loop = bc.EnclosingLoopOrSwitch;
1885                         return base.DoResolve (bc);
1886                 }
1887
1888                 public override Reachability MarkReachable (Reachability rc)
1889                 {
1890                         base.MarkReachable (rc);
1891
1892                         if (!rc.IsUnreachable)
1893                                 enclosing_loop.SetEndReachable ();
1894
1895                         return Reachability.CreateUnreachable ();
1896                 }
1897         }
1898
1899         public class Continue : LocalExitStatement
1900         {               
1901                 public Continue (Location l)
1902                         : base (l)
1903                 {
1904                 }
1905
1906                 public override object Accept (StructuralVisitor visitor)
1907                 {
1908                         return visitor.Visit (this);
1909                 }
1910
1911
1912                 protected override void DoEmit (EmitContext ec)
1913                 {
1914                         var l = ec.LoopBegin;
1915
1916                         if (ec.TryFinallyUnwind != null) {
1917                                 var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
1918                                 l = TryFinally.EmitRedirectedJump (ec, async_body, l, enclosing_loop.Statement as Block);
1919                         }
1920
1921                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
1922                 }
1923
1924                 protected override bool DoResolve (BlockContext bc)
1925                 {
1926                         enclosing_loop = bc.EnclosingLoop;
1927                         return base.DoResolve (bc);
1928                 }
1929
1930                 public override Reachability MarkReachable (Reachability rc)
1931                 {
1932                         base.MarkReachable (rc);
1933
1934                         if (!rc.IsUnreachable)
1935                                 enclosing_loop.SetIteratorReachable ();
1936
1937                         return Reachability.CreateUnreachable ();
1938                 }
1939         }
1940
1941         public abstract class LocalExitStatement : ExitStatement
1942         {
1943                 protected LoopStatement enclosing_loop;
1944
1945                 protected LocalExitStatement (Location loc)
1946                 {
1947                         this.loc = loc;
1948                 }
1949
1950                 protected override bool IsLocalExit {
1951                         get {
1952                                 return true;
1953                         }
1954                 }
1955
1956                 protected override void CloneTo (CloneContext clonectx, Statement t)
1957                 {
1958                         // nothing needed.
1959                 }
1960
1961                 protected override bool DoResolve (BlockContext bc)
1962                 {
1963                         if (enclosing_loop == null) {
1964                                 bc.Report.Error (139, loc, "No enclosing loop out of which to break or continue");
1965                                 return false;
1966                         }
1967
1968                         var block = enclosing_loop.Statement as Block;
1969
1970                         // Don't need to do extra checks for simple statements loops
1971                         if (block != null) {
1972                                 CheckExitBoundaries (bc, block);
1973                         }
1974
1975                         return true;
1976                 }
1977         }
1978
1979         public interface ILocalVariable
1980         {
1981                 void Emit (EmitContext ec);
1982                 void EmitAssign (EmitContext ec);
1983                 void EmitAddressOf (EmitContext ec);
1984         }
1985
1986         public interface INamedBlockVariable
1987         {
1988                 Block Block { get; }
1989                 Expression CreateReferenceExpression (ResolveContext rc, Location loc);
1990                 bool IsDeclared { get; }
1991                 bool IsParameter { get; }
1992                 Location Location { get; }
1993         }
1994
1995         public class BlockVariableDeclarator
1996         {
1997                 LocalVariable li;
1998                 Expression initializer;
1999
2000                 public BlockVariableDeclarator (LocalVariable li, Expression initializer)
2001                 {
2002                         if (li.Type != null)
2003                                 throw new ArgumentException ("Expected null variable type");
2004
2005                         this.li = li;
2006                         this.initializer = initializer;
2007                 }
2008
2009                 #region Properties
2010
2011                 public LocalVariable Variable {
2012                         get {
2013                                 return li;
2014                         }
2015                 }
2016
2017                 public Expression Initializer {
2018                         get {
2019                                 return initializer;
2020                         }
2021                         set {
2022                                 initializer = value;
2023                         }
2024                 }
2025
2026                 #endregion
2027
2028                 public virtual BlockVariableDeclarator Clone (CloneContext cloneCtx)
2029                 {
2030                         var t = (BlockVariableDeclarator) MemberwiseClone ();
2031                         if (initializer != null)
2032                                 t.initializer = initializer.Clone (cloneCtx);
2033
2034                         return t;
2035                 }
2036         }
2037
2038         public class BlockVariable : Statement
2039         {
2040                 Expression initializer;
2041                 protected FullNamedExpression type_expr;
2042                 protected LocalVariable li;
2043                 protected List<BlockVariableDeclarator> declarators;
2044                 TypeSpec type;
2045
2046                 public BlockVariable (FullNamedExpression type, LocalVariable li)
2047                 {
2048                         this.type_expr = type;
2049                         this.li = li;
2050                         this.loc = type_expr.Location;
2051                 }
2052
2053                 protected BlockVariable (LocalVariable li)
2054                 {
2055                         this.li = li;
2056                 }
2057
2058                 #region Properties
2059
2060                 public List<BlockVariableDeclarator> Declarators {
2061                         get {
2062                                 return declarators;
2063                         }
2064                 }
2065
2066                 public Expression Initializer {
2067                         get {
2068                                 return initializer;
2069                         }
2070                         set {
2071                                 initializer = value;
2072                         }
2073                 }
2074
2075                 public FullNamedExpression TypeExpression {
2076                         get {
2077                                 return type_expr;
2078                         }
2079                 }
2080
2081                 public LocalVariable Variable {
2082                         get {
2083                                 return li;
2084                         }
2085                 }
2086
2087                 #endregion
2088
2089                 public void AddDeclarator (BlockVariableDeclarator decl)
2090                 {
2091                         if (declarators == null)
2092                                 declarators = new List<BlockVariableDeclarator> ();
2093
2094                         declarators.Add (decl);
2095                 }
2096
2097                 static void CreateEvaluatorVariable (BlockContext bc, LocalVariable li)
2098                 {
2099                         if (bc.Report.Errors != 0)
2100                                 return;
2101
2102                         var container = bc.CurrentMemberDefinition.Parent.PartialContainer;
2103
2104                         Field f = new Field (container, new TypeExpression (li.Type, li.Location), Modifiers.PUBLIC | Modifiers.STATIC,
2105                                 new MemberName (li.Name, li.Location), null);
2106
2107                         container.AddField (f);
2108                         f.Define ();
2109
2110                         li.HoistedVariant = new HoistedEvaluatorVariable (f);
2111                         li.SetIsUsed ();
2112                 }
2113
2114                 public override bool Resolve (BlockContext bc)
2115                 {
2116                         return Resolve (bc, true);
2117                 }
2118
2119                 public bool Resolve (BlockContext bc, bool resolveDeclaratorInitializers)
2120                 {
2121                         if (type == null && !li.IsCompilerGenerated) {
2122                                 var vexpr = type_expr as VarExpr;
2123
2124                                 //
2125                                 // C# 3.0 introduced contextual keywords (var) which behaves like a type if type with
2126                                 // same name exists or as a keyword when no type was found
2127                                 //
2128                                 if (vexpr != null && !vexpr.IsPossibleType (bc)) {
2129                                         if (bc.Module.Compiler.Settings.Version < LanguageVersion.V_3)
2130                                                 bc.Report.FeatureIsNotAvailable (bc.Module.Compiler, loc, "implicitly typed local variable");
2131
2132                                         if (li.IsFixed) {
2133                                                 bc.Report.Error (821, loc, "A fixed statement cannot use an implicitly typed local variable");
2134                                                 return false;
2135                                         }
2136
2137                                         if (li.IsConstant) {
2138                                                 bc.Report.Error (822, loc, "An implicitly typed local variable cannot be a constant");
2139                                                 return false;
2140                                         }
2141
2142                                         if (Initializer == null) {
2143                                                 bc.Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
2144                                                 return false;
2145                                         }
2146
2147                                         if (declarators != null) {
2148                                                 bc.Report.Error (819, loc, "An implicitly typed local variable declaration cannot include multiple declarators");
2149                                                 declarators = null;
2150                                         }
2151
2152                                         Initializer = Initializer.Resolve (bc);
2153                                         if (Initializer != null) {
2154                                                 ((VarExpr) type_expr).InferType (bc, Initializer);
2155                                                 type = type_expr.Type;
2156                                         } else {
2157                                                 // Set error type to indicate the var was placed correctly but could
2158                                                 // not be infered
2159                                                 //
2160                                                 // var a = missing ();
2161                                                 //
2162                                                 type = InternalType.ErrorType;
2163                                         }
2164                                 }
2165
2166                                 if (type == null) {
2167                                         type = type_expr.ResolveAsType (bc);
2168                                         if (type == null)
2169                                                 return false;
2170
2171                                         if (li.IsConstant && !type.IsConstantCompatible) {
2172                                                 Const.Error_InvalidConstantType (type, loc, bc.Report);
2173                                         }
2174                                 }
2175
2176                                 if (type.IsStatic)
2177                                         FieldBase.Error_VariableOfStaticClass (loc, li.Name, type, bc.Report);
2178
2179                                 li.Type = type;
2180                         }
2181
2182                         bool eval_global = bc.Module.Compiler.Settings.StatementMode && bc.CurrentBlock is ToplevelBlock;
2183                         if (eval_global) {
2184                                 CreateEvaluatorVariable (bc, li);
2185                         } else if (type != InternalType.ErrorType) {
2186                                 li.PrepareAssignmentAnalysis (bc);
2187                         }
2188
2189                         if (initializer != null) {
2190                                 initializer = ResolveInitializer (bc, li, initializer);
2191                                 // li.Variable.DefinitelyAssigned 
2192                         }
2193
2194                         if (declarators != null) {
2195                                 foreach (var d in declarators) {
2196                                         d.Variable.Type = li.Type;
2197                                         if (eval_global) {
2198                                                 CreateEvaluatorVariable (bc, d.Variable);
2199                                         } else if (type != InternalType.ErrorType) {
2200                                                 d.Variable.PrepareAssignmentAnalysis (bc);
2201                                         }
2202
2203                                         if (d.Initializer != null && resolveDeclaratorInitializers) {
2204                                                 d.Initializer = ResolveInitializer (bc, d.Variable, d.Initializer);
2205                                                 // d.Variable.DefinitelyAssigned 
2206                                         } 
2207                                 }
2208                         }
2209
2210                         return true;
2211                 }
2212
2213                 protected virtual Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
2214                 {
2215                         var a = new SimpleAssign (li.CreateReferenceExpression (bc, li.Location), initializer, li.Location);
2216                         return a.ResolveStatement (bc);
2217                 }
2218
2219                 protected override void DoEmit (EmitContext ec)
2220                 {
2221                         li.CreateBuilder (ec);
2222
2223                         if (Initializer != null && !IsUnreachable)
2224                                 ((ExpressionStatement) Initializer).EmitStatement (ec);
2225
2226                         if (declarators != null) {
2227                                 foreach (var d in declarators) {
2228                                         d.Variable.CreateBuilder (ec);
2229                                         if (d.Initializer != null && !IsUnreachable) {
2230                                                 ec.Mark (d.Variable.Location);
2231                                                 ((ExpressionStatement) d.Initializer).EmitStatement (ec);
2232                                         }
2233                                 }
2234                         }
2235                 }
2236
2237                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
2238                 {
2239                         if (Initializer != null)
2240                                 Initializer.FlowAnalysis (fc);
2241
2242                         if (declarators != null) {
2243                                 foreach (var d in declarators) {
2244                                         if (d.Initializer != null)
2245                                                 d.Initializer.FlowAnalysis (fc);
2246                                 }
2247                         }
2248
2249                         return false;
2250                 }
2251
2252                 public override Reachability MarkReachable (Reachability rc)
2253                 {
2254                         var init = initializer as ExpressionStatement;
2255                         if (init != null)
2256                                 init.MarkReachable (rc);
2257
2258                         return base.MarkReachable (rc);
2259                 }
2260
2261                 protected override void CloneTo (CloneContext clonectx, Statement target)
2262                 {
2263                         BlockVariable t = (BlockVariable) target;
2264
2265                         if (type_expr != null)
2266                                 t.type_expr = (FullNamedExpression) type_expr.Clone (clonectx);
2267
2268                         if (initializer != null)
2269                                 t.initializer = initializer.Clone (clonectx);
2270
2271                         if (declarators != null) {
2272                                 t.declarators = null;
2273                                 foreach (var d in declarators)
2274                                         t.AddDeclarator (d.Clone (clonectx));
2275                         }
2276                 }
2277
2278                 public override object Accept (StructuralVisitor visitor)
2279                 {
2280                         return visitor.Visit (this);
2281                 }
2282         }
2283
2284         public class BlockConstant : BlockVariable
2285         {
2286                 public BlockConstant (FullNamedExpression type, LocalVariable li)
2287                         : base (type, li)
2288                 {
2289                 }
2290
2291                 public override void Emit (EmitContext ec)
2292                 {
2293                         if (!Variable.IsUsed)
2294                                 ec.Report.Warning (219, 3, loc, "The constant `{0}' is never used", Variable.Name);
2295                         
2296                         // Nothing to emit, not even sequence point
2297                 }
2298
2299                 protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
2300                 {
2301                         initializer = initializer.Resolve (bc);
2302                         if (initializer == null)
2303                                 return null;
2304
2305                         var c = initializer as Constant;
2306                         if (c == null) {
2307                                 initializer.Error_ExpressionMustBeConstant (bc, initializer.Location, li.Name);
2308                                 return null;
2309                         }
2310
2311                         c = c.ConvertImplicitly (li.Type);
2312                         if (c == null) {
2313                                 if (TypeSpec.IsReferenceType (li.Type))
2314                                         initializer.Error_ConstantCanBeInitializedWithNullOnly (bc, li.Type, initializer.Location, li.Name);
2315                                 else
2316                                         initializer.Error_ValueCannotBeConverted (bc, li.Type, false);
2317
2318                                 return null;
2319                         }
2320
2321                         li.ConstantValue = c;
2322                         return initializer;
2323                 }
2324                 
2325                 public override object Accept (StructuralVisitor visitor)
2326                 {
2327                         return visitor.Visit (this);
2328                 }
2329         }
2330
2331         //
2332         // The information about a user-perceived local variable
2333         //
2334         public sealed class LocalVariable : INamedBlockVariable, ILocalVariable
2335         {
2336                 [Flags]
2337                 public enum Flags
2338                 {
2339                         Used = 1,
2340                         IsThis = 1 << 1,
2341                         AddressTaken = 1 << 2,
2342                         CompilerGenerated = 1 << 3,
2343                         Constant = 1 << 4,
2344                         ForeachVariable = 1 << 5,
2345                         FixedVariable = 1 << 6,
2346                         UsingVariable = 1 << 7,
2347                         IsLocked = 1 << 8,
2348                         SymbolFileHidden = 1 << 9,
2349
2350                         ReadonlyMask = ForeachVariable | FixedVariable | UsingVariable
2351                 }
2352
2353                 TypeSpec type;
2354                 readonly string name;
2355                 readonly Location loc;
2356                 readonly Block block;
2357                 Flags flags;
2358                 Constant const_value;
2359
2360                 public VariableInfo VariableInfo;
2361                 HoistedVariable hoisted_variant;
2362
2363                 LocalBuilder builder;
2364
2365                 public LocalVariable (Block block, string name, Location loc)
2366                 {
2367                         this.block = block;
2368                         this.name = name;
2369                         this.loc = loc;
2370                 }
2371
2372                 public LocalVariable (Block block, string name, Flags flags, Location loc)
2373                         : this (block, name, loc)
2374                 {
2375                         this.flags = flags;
2376                 }
2377
2378                 //
2379                 // Used by variable declarators
2380                 //
2381                 public LocalVariable (LocalVariable li, string name, Location loc)
2382                         : this (li.block, name, li.flags, loc)
2383                 {
2384                 }
2385
2386                 #region Properties
2387
2388                 public bool AddressTaken {
2389                         get {
2390                                 return (flags & Flags.AddressTaken) != 0;
2391                         }
2392                 }
2393
2394                 public Block Block {
2395                         get {
2396                                 return block;
2397                         }
2398                 }
2399
2400                 public Constant ConstantValue {
2401                         get {
2402                                 return const_value;
2403                         }
2404                         set {
2405                                 const_value = value;
2406                         }
2407                 }
2408
2409                 //
2410                 // Hoisted local variable variant
2411                 //
2412                 public HoistedVariable HoistedVariant {
2413                         get {
2414                                 return hoisted_variant;
2415                         }
2416                         set {
2417                                 hoisted_variant = value;
2418                         }
2419                 }
2420
2421                 public bool IsDeclared {
2422                         get {
2423                                 return type != null;
2424                         }
2425                 }
2426
2427                 public bool IsCompilerGenerated {
2428                         get {
2429                                 return (flags & Flags.CompilerGenerated) != 0;
2430                         }
2431                 }
2432
2433                 public bool IsConstant {
2434                         get {
2435                                 return (flags & Flags.Constant) != 0;
2436                         }
2437                 }
2438
2439                 public bool IsLocked {
2440                         get {
2441                                 return (flags & Flags.IsLocked) != 0;
2442                         }
2443                         set {
2444                                 flags = value ? flags | Flags.IsLocked : flags & ~Flags.IsLocked;
2445                         }
2446                 }
2447
2448                 public bool IsThis {
2449                         get {
2450                                 return (flags & Flags.IsThis) != 0;
2451                         }
2452                 }
2453
2454                 public bool IsUsed {
2455                         get {
2456                                 return (flags & Flags.Used) != 0;
2457                         }
2458                 }
2459
2460                 public bool IsFixed {
2461                         get {
2462                                 return (flags & Flags.FixedVariable) != 0;
2463                         }
2464                         set {
2465                                 flags = value ? flags | Flags.FixedVariable : flags & ~Flags.FixedVariable;
2466                         }
2467                 }
2468
2469                 bool INamedBlockVariable.IsParameter {
2470                         get {
2471                                 return false;
2472                         }
2473                 }
2474
2475                 public bool IsReadonly {
2476                         get {
2477                                 return (flags & Flags.ReadonlyMask) != 0;
2478                         }
2479                 }
2480
2481                 public Location Location {
2482                         get {
2483                                 return loc;
2484                         }
2485                 }
2486
2487                 public string Name {
2488                         get {
2489                                 return name;
2490                         }
2491                 }
2492
2493                 public TypeSpec Type {
2494                     get {
2495                                 return type;
2496                         }
2497                     set {
2498                                 type = value;
2499                         }
2500                 }
2501
2502                 #endregion
2503
2504                 public void CreateBuilder (EmitContext ec)
2505                 {
2506                         if ((flags & Flags.Used) == 0) {
2507                                 if (VariableInfo == null) {
2508                                         // Missing flow analysis or wrong variable flags
2509                                         throw new InternalErrorException ("VariableInfo is null and the variable `{0}' is not used", name);
2510                                 }
2511
2512                                 if (VariableInfo.IsEverAssigned)
2513                                         ec.Report.Warning (219, 3, Location, "The variable `{0}' is assigned but its value is never used", Name);
2514                                 else
2515                                         ec.Report.Warning (168, 3, Location, "The variable `{0}' is declared but never used", Name);
2516                         }
2517
2518                         if (HoistedVariant != null)
2519                                 return;
2520
2521                         if (builder != null) {
2522                                 if ((flags & Flags.CompilerGenerated) != 0)
2523                                         return;
2524
2525                                 // To avoid Used warning duplicates
2526                                 throw new InternalErrorException ("Already created variable `{0}'", name);
2527                         }
2528
2529                         //
2530                         // All fixed variabled are pinned, a slot has to be alocated
2531                         //
2532                         builder = ec.DeclareLocal (Type, IsFixed);
2533                         if ((flags & Flags.SymbolFileHidden) == 0)
2534                                 ec.DefineLocalVariable (name, builder);
2535                 }
2536
2537                 public static LocalVariable CreateCompilerGenerated (TypeSpec type, Block block, Location loc, bool writeToSymbolFile = false)
2538                 {
2539                         LocalVariable li = new LocalVariable (block, GetCompilerGeneratedName (block), Flags.CompilerGenerated | Flags.Used, loc);
2540                         if (!writeToSymbolFile)
2541                                 li.flags |= Flags.SymbolFileHidden;
2542                         
2543                         li.Type = type;
2544                         return li;
2545                 }
2546
2547                 public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
2548                 {
2549                         if (IsConstant && const_value != null) {
2550                                 SetIsUsed ();
2551                                 return Constant.CreateConstantFromValue (Type, const_value.GetValue (), loc);
2552                         }
2553
2554                         return new LocalVariableReference (this, loc);
2555                 }
2556
2557                 public void Emit (EmitContext ec)
2558                 {
2559                         // TODO: Need something better for temporary variables
2560                         if ((flags & Flags.CompilerGenerated) != 0)
2561                                 CreateBuilder (ec);
2562
2563                         ec.Emit (OpCodes.Ldloc, builder);
2564                 }
2565
2566                 public void EmitAssign (EmitContext ec)
2567                 {
2568                         // TODO: Need something better for temporary variables
2569                         if ((flags & Flags.CompilerGenerated) != 0)
2570                                 CreateBuilder (ec);
2571
2572                         ec.Emit (OpCodes.Stloc, builder);
2573                 }
2574
2575                 public void EmitAddressOf (EmitContext ec)
2576                 {
2577                         // TODO: Need something better for temporary variables
2578                         if ((flags & Flags.CompilerGenerated) != 0)
2579                                 CreateBuilder (ec);
2580
2581                         ec.Emit (OpCodes.Ldloca, builder);
2582                 }
2583
2584                 public static string GetCompilerGeneratedName (Block block)
2585                 {
2586                         // HACK: Debugger depends on the name semantics
2587                         return "$locvar" + block.ParametersBlock.TemporaryLocalsCount++.ToString ("X");
2588                 }
2589
2590                 public string GetReadOnlyContext ()
2591                 {
2592                         switch (flags & Flags.ReadonlyMask) {
2593                         case Flags.FixedVariable:
2594                                 return "fixed variable";
2595                         case Flags.ForeachVariable:
2596                                 return "foreach iteration variable";
2597                         case Flags.UsingVariable:
2598                                 return "using variable";
2599                         }
2600
2601                         throw new InternalErrorException ("Variable is not readonly");
2602                 }
2603
2604                 public bool IsThisAssigned (FlowAnalysisContext fc, Block block)
2605                 {
2606                         if (VariableInfo == null)
2607                                 throw new Exception ();
2608
2609                         if (IsAssigned (fc))
2610                                 return true;
2611
2612                         return VariableInfo.IsFullyInitialized (fc, block.StartLocation);
2613                 }
2614
2615                 public bool IsAssigned (FlowAnalysisContext fc)
2616                 {
2617                         return fc.IsDefinitelyAssigned (VariableInfo);
2618                 }
2619
2620                 public void PrepareAssignmentAnalysis (BlockContext bc)
2621                 {
2622                         //
2623                         // No need to run assignment analysis for these guys
2624                         //
2625                         if ((flags & (Flags.Constant | Flags.ReadonlyMask | Flags.CompilerGenerated)) != 0)
2626                                 return;
2627
2628                         VariableInfo = VariableInfo.Create (bc, this);
2629                 }
2630
2631                 //
2632                 // Mark the variables as referenced in the user code
2633                 //
2634                 public void SetIsUsed ()
2635                 {
2636                         flags |= Flags.Used;
2637                 }
2638
2639                 public void SetHasAddressTaken ()
2640                 {
2641                         flags |= (Flags.AddressTaken | Flags.Used);
2642                 }
2643
2644                 public override string ToString ()
2645                 {
2646                         return string.Format ("LocalInfo ({0},{1},{2},{3})", name, type, VariableInfo, Location);
2647                 }
2648         }
2649
2650         /// <summary>
2651         ///   Block represents a C# block.
2652         /// </summary>
2653         ///
2654         /// <remarks>
2655         ///   This class is used in a number of places: either to represent
2656         ///   explicit blocks that the programmer places or implicit blocks.
2657         ///
2658         ///   Implicit blocks are used as labels or to introduce variable
2659         ///   declarations.
2660         ///
2661         ///   Top-level blocks derive from Block, and they are called ToplevelBlock
2662         ///   they contain extra information that is not necessary on normal blocks.
2663         /// </remarks>
2664         public class Block : Statement {
2665                 [Flags]
2666                 public enum Flags
2667                 {
2668                         Unchecked = 1,
2669                         ReachableEnd = 8,
2670                         Unsafe = 16,
2671                         HasCapturedVariable = 64,
2672                         HasCapturedThis = 1 << 7,
2673                         IsExpressionTree = 1 << 8,
2674                         CompilerGenerated = 1 << 9,
2675                         HasAsyncModifier = 1 << 10,
2676                         Resolved = 1 << 11,
2677                         YieldBlock = 1 << 12,
2678                         AwaitBlock = 1 << 13,
2679                         FinallyBlock = 1 << 14,
2680                         CatchBlock = 1 << 15,
2681                         HasReferenceToStoreyForInstanceLambdas = 1 << 16,
2682                         Iterator = 1 << 20,
2683                         NoFlowAnalysis = 1 << 21,
2684                         InitializationEmitted = 1 << 22
2685                 }
2686
2687                 public Block Parent;
2688                 public Location StartLocation;
2689                 public Location EndLocation;
2690
2691                 public ExplicitBlock Explicit;
2692                 public ParametersBlock ParametersBlock;
2693
2694                 protected Flags flags;
2695
2696                 //
2697                 // The statements in this block
2698                 //
2699                 protected List<Statement> statements;
2700
2701                 protected List<Statement> scope_initializers;
2702
2703                 int? resolving_init_idx;
2704
2705                 Block original;
2706
2707 #if DEBUG
2708                 static int id;
2709                 public int ID = id++;
2710
2711                 static int clone_id_counter;
2712                 int clone_id;
2713 #endif
2714
2715 //              int assignable_slots;
2716
2717                 public Block (Block parent, Location start, Location end)
2718                         : this (parent, 0, start, end)
2719                 {
2720                 }
2721
2722                 public Block (Block parent, Flags flags, Location start, Location end)
2723                 {
2724                         if (parent != null) {
2725                                 // the appropriate constructors will fixup these fields
2726                                 ParametersBlock = parent.ParametersBlock;
2727                                 Explicit = parent.Explicit;
2728                         }
2729                         
2730                         this.Parent = parent;
2731                         this.flags = flags;
2732                         this.StartLocation = start;
2733                         this.EndLocation = end;
2734                         this.loc = start;
2735                         statements = new List<Statement> (4);
2736
2737                         this.original = this;
2738                 }
2739
2740                 #region Properties
2741
2742                 public Block Original {
2743                         get {
2744                                 return original;
2745                         }
2746                         protected set {
2747                                 original = value;
2748                         }
2749                 }
2750
2751                 public bool IsCompilerGenerated {
2752                         get { return (flags & Flags.CompilerGenerated) != 0; }
2753                         set { flags = value ? flags | Flags.CompilerGenerated : flags & ~Flags.CompilerGenerated; }
2754                 }
2755
2756
2757                 public bool IsCatchBlock {
2758                         get {
2759                                 return (flags & Flags.CatchBlock) != 0;
2760                         }
2761                 }
2762
2763                 public bool IsFinallyBlock {
2764                         get {
2765                                 return (flags & Flags.FinallyBlock) != 0;
2766                         }
2767                 }
2768
2769                 public bool Unchecked {
2770                         get { return (flags & Flags.Unchecked) != 0; }
2771                         set { flags = value ? flags | Flags.Unchecked : flags & ~Flags.Unchecked; }
2772                 }
2773
2774                 public bool Unsafe {
2775                         get { return (flags & Flags.Unsafe) != 0; }
2776                         set { flags |= Flags.Unsafe; }
2777                 }
2778
2779                 public List<Statement> Statements {
2780                         get { return statements; }
2781                 }
2782
2783                 #endregion
2784
2785                 public void SetEndLocation (Location loc)
2786                 {
2787                         EndLocation = loc;
2788                 }
2789
2790                 public void AddLabel (LabeledStatement target)
2791                 {
2792                         ParametersBlock.TopBlock.AddLabel (target.Name, target);
2793                 }
2794
2795                 public void AddLocalName (LocalVariable li)
2796                 {
2797                         AddLocalName (li.Name, li);
2798                 }
2799
2800                 public void AddLocalName (string name, INamedBlockVariable li)
2801                 {
2802                         ParametersBlock.TopBlock.AddLocalName (name, li, false);
2803                 }
2804
2805                 public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason)
2806                 {
2807                         if (reason == null) {
2808                                 Error_AlreadyDeclared (name, variable);
2809                                 return;
2810                         }
2811
2812                         ParametersBlock.TopBlock.Report.Error (136, variable.Location,
2813                                 "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning " +
2814                                 "to `{0}', which is already used in a `{1}' scope to denote something else",
2815                                 name, reason);
2816                 }
2817
2818                 public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable)
2819                 {
2820                         var pi = variable as ParametersBlock.ParameterInfo;
2821                         if (pi != null) {
2822                                 pi.Parameter.Error_DuplicateName (ParametersBlock.TopBlock.Report);
2823                         } else {
2824                                 ParametersBlock.TopBlock.Report.Error (128, variable.Location,
2825                                         "A local variable named `{0}' is already defined in this scope", name);
2826                         }
2827                 }
2828                                         
2829                 public virtual void Error_AlreadyDeclaredTypeParameter (string name, Location loc)
2830                 {
2831                         ParametersBlock.TopBlock.Report.Error (412, loc,
2832                                 "The type parameter name `{0}' is the same as local variable or parameter name",
2833                                 name);
2834                 }
2835
2836                 //
2837                 // It should be used by expressions which require to
2838                 // register a statement during resolve process.
2839                 //
2840                 public void AddScopeStatement (Statement s)
2841                 {
2842                         if (scope_initializers == null)
2843                                 scope_initializers = new List<Statement> ();
2844
2845                         //
2846                         // Simple recursive helper, when resolve scope initializer another
2847                         // new scope initializer can be added, this ensures it's initialized
2848                         // before existing one. For now this can happen with expression trees
2849                         // in base ctor initializer only
2850                         //
2851                         if (resolving_init_idx.HasValue) {
2852                                 scope_initializers.Insert (resolving_init_idx.Value, s);
2853                                 ++resolving_init_idx;
2854                         } else {
2855                                 scope_initializers.Add (s);
2856                         }
2857                 }
2858
2859                 public void InsertStatement (int index, Statement s)
2860                 {
2861                         statements.Insert (index, s);
2862                 }
2863                 
2864                 public void AddStatement (Statement s)
2865                 {
2866                         statements.Add (s);
2867                 }
2868
2869                 public LabeledStatement LookupLabel (string name)
2870                 {
2871                         return ParametersBlock.GetLabel (name, this);
2872                 }
2873
2874                 public override Reachability MarkReachable (Reachability rc)
2875                 {
2876                         if (rc.IsUnreachable)
2877                                 return rc;
2878
2879                         MarkReachableScope (rc);
2880
2881                         foreach (var s in statements) {
2882                                 rc = s.MarkReachable (rc);
2883                                 if (rc.IsUnreachable) {
2884                                         if ((flags & Flags.ReachableEnd) != 0)
2885                                                 return new Reachability ();
2886
2887                                         return rc;
2888                                 }
2889                         }
2890
2891                         flags |= Flags.ReachableEnd;
2892
2893                         return rc;
2894                 }
2895
2896                 public void MarkReachableScope (Reachability rc)
2897                 {
2898                         base.MarkReachable (rc);
2899
2900                         if (scope_initializers != null) {
2901                                 foreach (var si in scope_initializers)
2902                                         si.MarkReachable (rc);
2903                         }
2904                 }
2905
2906                 public override bool Resolve (BlockContext bc)
2907                 {
2908                         if ((flags & Flags.Resolved) != 0)
2909                                 return true;
2910
2911                         Block prev_block = bc.CurrentBlock;
2912                         bc.CurrentBlock = this;
2913
2914                         //
2915                         // Compiler generated scope statements
2916                         //
2917                         if (scope_initializers != null) {
2918                                 for (resolving_init_idx = 0; resolving_init_idx < scope_initializers.Count; ++resolving_init_idx) {
2919                                         scope_initializers[resolving_init_idx.Value].Resolve (bc);
2920                                 }
2921
2922                                 resolving_init_idx = null;
2923                         }
2924
2925                         bool ok = true;
2926                         int statement_count = statements.Count;
2927                         for (int ix = 0; ix < statement_count; ix++){
2928                                 Statement s = statements [ix];
2929
2930                                 if (!s.Resolve (bc)) {
2931                                         ok = false;
2932                                         statements [ix] = new EmptyStatement (s.loc);
2933                                         continue;
2934                                 }
2935                         }
2936
2937                         bc.CurrentBlock = prev_block;
2938
2939                         flags |= Flags.Resolved;
2940                         return ok;
2941                 }
2942
2943                 protected override void DoEmit (EmitContext ec)
2944                 {
2945                         for (int ix = 0; ix < statements.Count; ix++){
2946                                 statements [ix].Emit (ec);
2947                         }
2948                 }
2949
2950                 public override void Emit (EmitContext ec)
2951                 {
2952                         if (scope_initializers != null)
2953                                 EmitScopeInitializers (ec);
2954
2955                         DoEmit (ec);
2956                 }
2957
2958                 protected void EmitScopeInitializers (EmitContext ec)
2959                 {
2960                         foreach (Statement s in scope_initializers)
2961                                 s.Emit (ec);
2962                 }
2963
2964                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
2965                 {
2966                         if (scope_initializers != null) {
2967                                 foreach (var si in scope_initializers)
2968                                         si.FlowAnalysis (fc);
2969                         }
2970
2971                         return DoFlowAnalysis (fc, 0);  
2972                 }
2973
2974                 bool DoFlowAnalysis (FlowAnalysisContext fc, int startIndex)
2975                 {
2976                         bool end_unreachable = !reachable;
2977                         bool goto_flow_analysis = startIndex != 0;
2978                         for (; startIndex < statements.Count; ++startIndex) {
2979                                 var s = statements[startIndex];
2980
2981                                 end_unreachable = s.FlowAnalysis (fc);
2982                                 if (s.IsUnreachable) {
2983                                         statements [startIndex] = RewriteUnreachableStatement (s);
2984                                         continue;
2985                                 }
2986
2987                                 //
2988                                 // Statement end reachability is needed mostly due to goto support. Consider
2989                                 //
2990                                 // if (cond) {
2991                                 //    goto X;
2992                                 // } else {
2993                                 //    goto Y;
2994                                 // }
2995                                 // X:
2996                                 //
2997                                 // X label is reachable only via goto not as another statement after if. We need
2998                                 // this for flow-analysis only to carry variable info correctly.
2999                                 //
3000                                 if (end_unreachable) {
3001                                         bool after_goto_case = goto_flow_analysis && s is GotoCase;
3002
3003                                         var f = s as TryFinally;
3004                                         if (f != null && !f.FinallyBlock.HasReachableClosingBrace) {
3005                                                 //
3006                                                 // Special case for try-finally with unreachable code after
3007                                                 // finally block. Try block has to include leave opcode but there is
3008                                                 // no label to leave to after unreachable finally block closing
3009                                                 // brace. This sentinel ensures there is always IL instruction to
3010                                                 // leave to even if we know it'll never be reached.
3011                                                 //
3012                                                 statements.Insert (startIndex + 1, new SentinelStatement ());
3013                                         } else {
3014                                                 for (++startIndex; startIndex < statements.Count; ++startIndex) {
3015                                                         s = statements [startIndex];
3016                                                         if (s is SwitchLabel) {
3017                                                                 if (!after_goto_case)
3018                                                                         s.FlowAnalysis (fc);
3019
3020                                                                 break;
3021                                                         }
3022
3023                                                         if (s.IsUnreachable) {
3024                                                                 s.FlowAnalysis (fc);
3025                                                                 statements [startIndex] = RewriteUnreachableStatement (s);
3026                                                         }
3027                                                 }
3028                                         }
3029
3030                                         //
3031                                         // Idea is to stop after goto case because goto case will always have at least same
3032                                         // variable assigned as switch case label. This saves a lot for complex goto case tests
3033                                         //
3034                                         if (after_goto_case)
3035                                                 break;
3036
3037                                         continue;
3038                                 }
3039
3040                                 var lb = s as LabeledStatement;
3041                                 if (lb != null && fc.AddReachedLabel (lb))
3042                                         break;
3043                         }
3044
3045                         //
3046                         // The condition should be true unless there is forward jumping goto
3047                         // 
3048                         // if (this is ExplicitBlock && end_unreachable != Explicit.HasReachableClosingBrace)
3049                         //      Debug.Fail ();
3050
3051                         return !Explicit.HasReachableClosingBrace;
3052                 }
3053
3054                 static Statement RewriteUnreachableStatement (Statement s)
3055                 {
3056                         // LAMESPEC: It's not clear whether declararion statement should be part of reachability
3057                         // analysis. Even csc report unreachable warning for it but it's actually used hence
3058                         // we try to emulate this behaviour
3059                         //
3060                         // Consider:
3061                         //      goto L;
3062                         //      int v;
3063                         // L:
3064                         //      v = 1;
3065
3066                         if (s is BlockVariable || s is EmptyStatement || s is SentinelStatement)
3067                                 return s;
3068
3069                         return new EmptyStatement (s.loc);
3070                 }
3071
3072                 public void ScanGotoJump (Statement label)
3073                 {
3074                         int i;
3075                         for (i = 0; i < statements.Count; ++i) {
3076                                 if (statements[i] == label)
3077                                         break;
3078                         }
3079
3080                         var rc = new Reachability ();
3081                         for (++i; i < statements.Count; ++i) {
3082                                 var s = statements[i];
3083                                 rc = s.MarkReachable (rc);
3084                                 if (rc.IsUnreachable)
3085                                         return;
3086                         }
3087
3088                         flags |= Flags.ReachableEnd;
3089                 }
3090
3091                 public void ScanGotoJump (Statement label, FlowAnalysisContext fc)
3092                 {
3093                         int i;
3094                         for (i = 0; i < statements.Count; ++i) {
3095                                 if (statements[i] == label)
3096                                         break;
3097                         }
3098
3099                         DoFlowAnalysis (fc, ++i);
3100                 }
3101
3102 #if DEBUG
3103                 public override string ToString ()
3104                 {
3105                         return String.Format ("{0}: ID={1} Clone={2} Location={3}", GetType (), ID, clone_id != 0, StartLocation);
3106                 }
3107 #endif
3108
3109                 protected override void CloneTo (CloneContext clonectx, Statement t)
3110                 {
3111                         Block target = (Block) t;
3112 #if DEBUG
3113                         target.clone_id = ++clone_id_counter;
3114 #endif
3115
3116                         clonectx.AddBlockMap (this, target);
3117                         if (original != this)
3118                                 clonectx.AddBlockMap (original, target);
3119
3120                         target.ParametersBlock = (ParametersBlock) (ParametersBlock == this ? target : clonectx.RemapBlockCopy (ParametersBlock));
3121                         target.Explicit = (ExplicitBlock) (Explicit == this ? target : clonectx.LookupBlock (Explicit));
3122
3123                         if (Parent != null)
3124                                 target.Parent = clonectx.RemapBlockCopy (Parent);
3125
3126                         target.statements = new List<Statement> (statements.Count);
3127                         foreach (Statement s in statements)
3128                                 target.statements.Add (s.Clone (clonectx));
3129                 }
3130
3131                 public override object Accept (StructuralVisitor visitor)
3132                 {
3133                         return visitor.Visit (this);
3134                 }
3135         }
3136
3137         public class ExplicitBlock : Block
3138         {
3139                 protected AnonymousMethodStorey am_storey;
3140                 int debug_scope_index;
3141
3142                 public ExplicitBlock (Block parent, Location start, Location end)
3143                         : this (parent, (Flags) 0, start, end)
3144                 {
3145                 }
3146
3147                 public ExplicitBlock (Block parent, Flags flags, Location start, Location end)
3148                         : base (parent, flags, start, end)
3149                 {
3150                         this.Explicit = this;
3151                 }
3152
3153                 #region Properties
3154
3155                 public AnonymousMethodStorey AnonymousMethodStorey {
3156                         get {
3157                                 return am_storey;
3158                         }
3159                 }
3160
3161                 public bool HasAwait {
3162                         get {
3163                                 return (flags & Flags.AwaitBlock) != 0;
3164                         }
3165                 }
3166
3167                 public bool HasCapturedThis {
3168                         set {
3169                                 flags = value ? flags | Flags.HasCapturedThis : flags & ~Flags.HasCapturedThis;
3170                         }
3171                         get {
3172                                 return (flags & Flags.HasCapturedThis) != 0;
3173                         }
3174                 }
3175
3176                 //
3177                 // Used to indicate that the block has reference to parent
3178                 // block and cannot be made static when defining anonymous method
3179                 //
3180                 public bool HasCapturedVariable {
3181                         set {
3182                                 flags = value ? flags | Flags.HasCapturedVariable : flags & ~Flags.HasCapturedVariable;
3183                         }
3184                         get {
3185                                 return (flags & Flags.HasCapturedVariable) != 0;
3186                         }
3187                 }
3188
3189                 public bool HasReachableClosingBrace {
3190                     get {
3191                         return (flags & Flags.ReachableEnd) != 0;
3192                     }
3193                         set {
3194                                 flags = value ? flags | Flags.ReachableEnd : flags & ~Flags.ReachableEnd;
3195                         }
3196                 }
3197
3198                 public bool HasYield {
3199                         get {
3200                                 return (flags & Flags.YieldBlock) != 0;
3201                         }
3202                 }
3203
3204                 #endregion
3205
3206                 //
3207                 // Creates anonymous method storey in current block
3208                 //
3209                 public AnonymousMethodStorey CreateAnonymousMethodStorey (ResolveContext ec)
3210                 {
3211                         //
3212                         // Return same story for iterator and async blocks unless we are
3213                         // in nested anonymous method
3214                         //
3215                         if (ec.CurrentAnonymousMethod is StateMachineInitializer && ParametersBlock.Original == ec.CurrentAnonymousMethod.Block.Original)
3216                                 return ec.CurrentAnonymousMethod.Storey;
3217
3218                         if (am_storey == null) {
3219                                 MemberBase mc = ec.MemberContext as MemberBase;
3220
3221                                 //
3222                                 // Creates anonymous method storey for this block
3223                                 //
3224                                 am_storey = new AnonymousMethodStorey (this, ec.CurrentMemberDefinition.Parent.PartialContainer, mc, ec.CurrentTypeParameters, "AnonStorey", MemberKind.Class);
3225                         }
3226
3227                         return am_storey;
3228                 }
3229
3230                 public void EmitScopeInitialization (EmitContext ec)
3231                 {
3232                         if ((flags & Flags.InitializationEmitted) != 0)
3233                                 return;
3234
3235                         if (am_storey != null) {
3236                                 DefineStoreyContainer (ec, am_storey);
3237                                 am_storey.EmitStoreyInstantiation (ec, this);
3238                         }
3239
3240                         if (scope_initializers != null)
3241                                 EmitScopeInitializers (ec);
3242
3243                         flags |= Flags.InitializationEmitted;
3244                 }
3245
3246                 public override void Emit (EmitContext ec)
3247                 {
3248                         if (Parent != null) {
3249                                 // TODO: It's needed only when scope has variable (normal or lifted)
3250                                 ec.BeginScope (GetDebugSymbolScopeIndex ());
3251                         }
3252
3253                         EmitScopeInitialization (ec);
3254
3255                         if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated && ec.Mark (StartLocation)) {
3256                                 ec.Emit (OpCodes.Nop);
3257                         }
3258
3259                         DoEmit (ec);
3260
3261                         if (Parent != null)
3262                                 ec.EndScope ();
3263
3264                         if (ec.EmitAccurateDebugInfo && HasReachableClosingBrace && !(this is ParametersBlock) &&
3265                                 !IsCompilerGenerated && ec.Mark (EndLocation)) {
3266                                 ec.Emit (OpCodes.Nop);
3267                         }
3268                 }
3269
3270                 protected void DefineStoreyContainer (EmitContext ec, AnonymousMethodStorey storey)
3271                 {
3272                         if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null) {
3273                                 storey.SetNestedStoryParent (ec.CurrentAnonymousMethod.Storey);
3274                                 storey.Mutator = ec.CurrentAnonymousMethod.Storey.Mutator;
3275                         }
3276
3277                         //
3278                         // Creates anonymous method storey
3279                         //
3280                         storey.CreateContainer ();
3281                         storey.DefineContainer ();
3282                         storey.ExpandBaseInterfaces ();
3283
3284                         if (Original.Explicit.HasCapturedThis && Original.ParametersBlock.TopBlock.ThisReferencesFromChildrenBlock != null) {
3285
3286                                 //
3287                                 // Only first storey in path will hold this reference. All children blocks will
3288                                 // reference it indirectly using $ref field
3289                                 //
3290                                 for (Block b = Original.Explicit; b != null; b = b.Parent) {
3291                                         if (b.Parent != null) {
3292                                                 var s = b.Parent.Explicit.AnonymousMethodStorey;
3293                                                 if (s != null) {
3294                                                         storey.HoistedThis = s.HoistedThis;
3295                                                         break;
3296                                                 }
3297                                         }
3298
3299                                         if (b.Explicit == b.Explicit.ParametersBlock && b.Explicit.ParametersBlock.StateMachine != null) {
3300                                                 if (storey.HoistedThis == null)
3301                                                         storey.HoistedThis = b.Explicit.ParametersBlock.StateMachine.HoistedThis;
3302
3303                                                 if (storey.HoistedThis != null)
3304                                                         break;
3305                                         }
3306                                 }
3307
3308                                 //
3309                                 // We are the first storey on path and 'this' has to be hoisted
3310                                 //
3311                                 if (storey.HoistedThis == null || !(storey.Parent is HoistedStoreyClass)) {
3312                                         foreach (ExplicitBlock ref_block in Original.ParametersBlock.TopBlock.ThisReferencesFromChildrenBlock) {
3313                                                 //
3314                                                 // ThisReferencesFromChildrenBlock holds all reference even if they
3315                                                 // are not on this path. It saves some memory otherwise it'd have to
3316                                                 // be in every explicit block. We run this check to see if the reference
3317                                                 // is valid for this storey
3318                                                 //
3319                                                 Block block_on_path = ref_block;
3320                                                 for (; block_on_path != null && block_on_path != Original; block_on_path = block_on_path.Parent);
3321
3322                                                 if (block_on_path == null)
3323                                                         continue;
3324
3325                                                 if (storey.HoistedThis == null) {
3326                                                         storey.AddCapturedThisField (ec, null);
3327                                                 }
3328
3329                                                 for (ExplicitBlock b = ref_block; b.AnonymousMethodStorey != storey; b = b.Parent.Explicit) {
3330                                                         ParametersBlock pb;
3331                                                         AnonymousMethodStorey b_storey = b.AnonymousMethodStorey;
3332
3333                                                         if (b_storey != null) {
3334                                                                 //
3335                                                                 // Don't add storey cross reference for `this' when the storey ends up not
3336                                                                 // beeing attached to any parent
3337                                                                 //
3338                                                                 if (b.ParametersBlock.StateMachine == null) {
3339                                                                         AnonymousMethodStorey s = null;
3340                                                                         for (Block ab = b.AnonymousMethodStorey.OriginalSourceBlock.Parent; ab != null; ab = ab.Parent) {
3341                                                                                 s = ab.Explicit.AnonymousMethodStorey;
3342                                                                                 if (s != null)
3343                                                                                         break;
3344                                                                         }
3345
3346                                                                         // Needs to be in sync with AnonymousMethodBody::DoCreateMethodHost
3347                                                                         if (s == null) {
3348                                                                                 var parent = storey == null || storey.Kind == MemberKind.Struct ? null : storey;
3349                                                                                 b.AnonymousMethodStorey.AddCapturedThisField (ec, parent);
3350                                                                                 break;
3351                                                                         }
3352
3353                                                                 }
3354
3355                                                                 //
3356                                                                 // Stop propagation inside same top block
3357                                                                 //
3358                                                                 if (b.ParametersBlock == ParametersBlock.Original) {
3359                                                                         b_storey.AddParentStoreyReference (ec, storey);
3360 //                                                                      b_storey.HoistedThis = storey.HoistedThis;
3361                                                                         break;
3362                                                                 }
3363
3364                                                                 b = pb = b.ParametersBlock;
3365                                                         } else {
3366                                                                 pb = b as ParametersBlock;
3367                                                         }
3368
3369                                                         if (pb != null && pb.StateMachine != null) {
3370                                                                 if (pb.StateMachine == storey)
3371                                                                         break;
3372
3373                                                                 //
3374                                                                 // If we are state machine with no parent. We can hook into parent without additional
3375                                                                 // reference and capture this directly
3376                                                                 //
3377                                                                 ExplicitBlock parent_storey_block = pb;
3378                                                                 while (parent_storey_block.Parent != null) {
3379                                                                         parent_storey_block = parent_storey_block.Parent.Explicit;
3380                                                                         if (parent_storey_block.AnonymousMethodStorey != null) {
3381                                                                                 break;
3382                                                                         }
3383                                                                 }
3384
3385                                                                 if (parent_storey_block.AnonymousMethodStorey == null) {
3386                                                                         if (pb.StateMachine.HoistedThis == null) {
3387                                                                                 pb.StateMachine.AddCapturedThisField (ec, null);
3388                                                                                 b.HasCapturedThis = true;
3389                                                                         }
3390
3391                                                                         continue;
3392                                                                 }
3393
3394                                                                 var parent_this_block = pb;
3395                                                                 while (parent_this_block.Parent != null) {
3396                                                                         parent_this_block = parent_this_block.Parent.ParametersBlock;
3397                                                                         if (parent_this_block.StateMachine != null && parent_this_block.StateMachine.HoistedThis != null) {
3398                                                                                 break;
3399                                                                         }
3400                                                                 }
3401
3402                                                                 //
3403                                                                 // Add reference to closest storey which holds captured this
3404                                                                 //
3405                                                                 pb.StateMachine.AddParentStoreyReference (ec, parent_this_block.StateMachine ?? storey);
3406                                                         }
3407
3408                                                         //
3409                                                         // Add parent storey reference only when this is not captured directly
3410                                                         //
3411                                                         if (b_storey != null) {
3412                                                                 b_storey.AddParentStoreyReference (ec, storey);
3413                                                                 b_storey.HoistedThis = storey.HoistedThis;
3414                                                         }
3415                                                 }
3416                                         }
3417                                 }
3418                         }
3419
3420                         var ref_blocks = storey.ReferencesFromChildrenBlock;
3421                         if (ref_blocks != null) {
3422                                 foreach (ExplicitBlock ref_block in ref_blocks) {
3423                                         for (ExplicitBlock b = ref_block; b.AnonymousMethodStorey != storey; b = b.Parent.Explicit) {
3424                                                 if (b.AnonymousMethodStorey != null) {
3425                                                         b.AnonymousMethodStorey.AddParentStoreyReference (ec, storey);
3426
3427                                                         //
3428                                                         // Stop propagation inside same top block
3429                                                         //
3430                                                         if (b.ParametersBlock == ParametersBlock.Original)
3431                                                                 break;
3432
3433                                                         b = b.ParametersBlock;
3434                                                 }
3435
3436                                                 var pb = b as ParametersBlock;
3437                                                 if (pb != null && pb.StateMachine != null) {
3438                                                         if (pb.StateMachine == storey)
3439                                                                 break;
3440
3441                                                         pb.StateMachine.AddParentStoreyReference (ec, storey);
3442                                                 }
3443
3444                                                 b.HasCapturedVariable = true;
3445                                         }
3446                                 }
3447                         }
3448
3449                         storey.Define ();
3450                         storey.PrepareEmit ();
3451                         storey.Parent.PartialContainer.AddCompilerGeneratedClass (storey);
3452                 }
3453
3454                 public int GetDebugSymbolScopeIndex ()
3455                 {
3456                         if (debug_scope_index == 0)
3457                                 debug_scope_index = ++ParametersBlock.debug_scope_index;
3458
3459                         return debug_scope_index;
3460                 }
3461
3462                 public void RegisterAsyncAwait ()
3463                 {
3464                         var block = this;
3465                         while ((block.flags & Flags.AwaitBlock) == 0) {
3466                                 block.flags |= Flags.AwaitBlock;
3467
3468                                 if (block is ParametersBlock)
3469                                         return;
3470
3471                                 block = block.Parent.Explicit;
3472                         }
3473                 }
3474
3475                 public void RegisterIteratorYield ()
3476                 {
3477                         ParametersBlock.TopBlock.IsIterator = true;
3478
3479                         var block = this;
3480                         while ((block.flags & Flags.YieldBlock) == 0) {
3481                                 block.flags |= Flags.YieldBlock;
3482
3483                                 if (block.Parent == null)
3484                                         return;
3485
3486                                 block = block.Parent.Explicit;
3487                         }
3488                 }
3489
3490                 public void SetCatchBlock ()
3491                 {
3492                         flags |= Flags.CatchBlock;
3493                 }
3494
3495                 public void SetFinallyBlock ()
3496                 {
3497                         flags |= Flags.FinallyBlock;
3498                 }
3499
3500                 public void WrapIntoDestructor (TryFinally tf, ExplicitBlock tryBlock)
3501                 {
3502                         tryBlock.statements = statements;
3503                         statements = new List<Statement> (1);
3504                         statements.Add (tf);
3505                 }
3506         }
3507
3508         //
3509         // ParametersBlock was introduced to support anonymous methods
3510         // and lambda expressions
3511         // 
3512         public class ParametersBlock : ExplicitBlock
3513         {
3514                 public class ParameterInfo : INamedBlockVariable
3515                 {
3516                         readonly ParametersBlock block;
3517                         readonly int index;
3518                         public VariableInfo VariableInfo;
3519                         bool is_locked;
3520
3521                         public ParameterInfo (ParametersBlock block, int index)
3522                         {
3523                                 this.block = block;
3524                                 this.index = index;
3525                         }
3526
3527                         #region Properties
3528
3529                         public ParametersBlock Block {
3530                                 get {
3531                                         return block;
3532                                 }
3533                         }
3534
3535                         Block INamedBlockVariable.Block {
3536                                 get {
3537                                         return block;
3538                                 }
3539                         }
3540
3541                         public bool IsDeclared {
3542                                 get {
3543                                         return true;
3544                                 }
3545                         }
3546
3547                         public bool IsParameter {
3548                                 get {
3549                                         return true;
3550                                 }
3551                         }
3552
3553                         public bool IsLocked {
3554                                 get {
3555                                         return is_locked;
3556                                 }
3557                                 set {
3558                                         is_locked = value;
3559                                 }
3560                         }
3561
3562                         public Location Location {
3563                                 get {
3564                                         return Parameter.Location;
3565                                 }
3566                         }
3567
3568                         public Parameter Parameter {
3569                                 get {
3570                                         return block.Parameters [index];
3571                                 }
3572                         }
3573
3574                         public TypeSpec ParameterType {
3575                                 get {
3576                                         return Parameter.Type;
3577                                 }
3578                         }
3579
3580                         #endregion
3581
3582                         public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
3583                         {
3584                                 return new ParameterReference (this, loc);
3585                         }
3586                 }
3587
3588                 // 
3589                 // Block is converted into an expression
3590                 //
3591                 sealed class BlockScopeExpression : Expression
3592                 {
3593                         Expression child;
3594                         readonly ParametersBlock block;
3595
3596                         public BlockScopeExpression (Expression child, ParametersBlock block)
3597                         {
3598                                 this.child = child;
3599                                 this.block = block;
3600                         }
3601
3602                         public override bool ContainsEmitWithAwait ()
3603                         {
3604                                 return child.ContainsEmitWithAwait ();
3605                         }
3606
3607                         public override Expression CreateExpressionTree (ResolveContext ec)
3608                         {
3609                                 throw new NotSupportedException ();
3610                         }
3611
3612                         protected override Expression DoResolve (ResolveContext ec)
3613                         {
3614                                 if (child == null)
3615                                         return null;
3616
3617                                 child = child.Resolve (ec);
3618                                 if (child == null)
3619                                         return null;
3620
3621                                 eclass = child.eclass;
3622                                 type = child.Type;
3623                                 return this;
3624                         }
3625
3626                         public override void Emit (EmitContext ec)
3627                         {
3628                                 block.EmitScopeInitializers (ec);
3629                                 child.Emit (ec);
3630                         }
3631                 }
3632
3633                 protected ParametersCompiled parameters;
3634                 protected ParameterInfo[] parameter_info;
3635                 protected bool resolved;
3636                 protected ToplevelBlock top_block;
3637                 protected StateMachine state_machine;
3638                 protected Dictionary<string, object> labels;
3639
3640                 public ParametersBlock (Block parent, ParametersCompiled parameters, Location start, Flags flags = 0)
3641                         : base (parent, 0, start, start)
3642                 {
3643                         if (parameters == null)
3644                                 throw new ArgumentNullException ("parameters");
3645
3646                         this.parameters = parameters;
3647                         ParametersBlock = this;
3648
3649                         this.flags |= flags | (parent.ParametersBlock.flags & (Flags.YieldBlock | Flags.AwaitBlock));
3650
3651                         this.top_block = parent.ParametersBlock.top_block;
3652                         ProcessParameters ();
3653                 }
3654
3655                 protected ParametersBlock (ParametersCompiled parameters, Location start)
3656                         : base (null, 0, start, start)
3657                 {
3658                         if (parameters == null)
3659                                 throw new ArgumentNullException ("parameters");
3660
3661                         this.parameters = parameters;
3662                         ParametersBlock = this;
3663                 }
3664
3665                 //
3666                 // It's supposed to be used by method body implementation of anonymous methods
3667                 //
3668                 protected ParametersBlock (ParametersBlock source, ParametersCompiled parameters)
3669                         : base (null, 0, source.StartLocation, source.EndLocation)
3670                 {
3671                         this.parameters = parameters;
3672                         this.statements = source.statements;
3673                         this.scope_initializers = source.scope_initializers;
3674
3675                         this.resolved = true;
3676                         this.reachable = source.reachable;
3677                         this.am_storey = source.am_storey;
3678                         this.state_machine = source.state_machine;
3679                         this.flags = source.flags & Flags.ReachableEnd;
3680
3681                         ParametersBlock = this;
3682
3683                         //
3684                         // Overwrite original for comparison purposes when linking cross references
3685                         // between anonymous methods
3686                         //
3687                         Original = source.Original;
3688                 }
3689
3690                 #region Properties
3691
3692                 public bool HasReferenceToStoreyForInstanceLambdas {
3693                         get {
3694                                 return (flags & Flags.HasReferenceToStoreyForInstanceLambdas) != 0;
3695                         }
3696                         set {
3697                                 flags = value ? flags | Flags.HasReferenceToStoreyForInstanceLambdas : flags & ~Flags.HasReferenceToStoreyForInstanceLambdas;
3698                         }
3699                 }
3700
3701                 public bool IsAsync {
3702                         get {
3703                                 return (flags & Flags.HasAsyncModifier) != 0;
3704                         }
3705                         set {
3706                                 flags = value ? flags | Flags.HasAsyncModifier : flags & ~Flags.HasAsyncModifier;
3707                         }
3708                 }
3709
3710                 //
3711                 // Block has been converted to expression tree
3712                 //
3713                 public bool IsExpressionTree {
3714                         get {
3715                                 return (flags & Flags.IsExpressionTree) != 0;
3716                         }
3717                 }
3718
3719                 //
3720                 // The parameters for the block.
3721                 //
3722                 public ParametersCompiled Parameters {
3723                         get {
3724                                 return parameters;
3725                         }
3726                 }
3727
3728                 public StateMachine StateMachine {
3729                         get {
3730                                 return state_machine;
3731                         }
3732                 }
3733
3734                 public ToplevelBlock TopBlock {
3735                         get {
3736                                 return top_block;
3737                         }
3738                         set {
3739                                 top_block = value;
3740                         }
3741                 }
3742
3743                 public bool Resolved {
3744                         get {
3745                                 return (flags & Flags.Resolved) != 0;
3746                         }
3747                 }
3748
3749                 public int TemporaryLocalsCount { get; set; }
3750
3751                 #endregion
3752
3753                 //
3754                 // Checks whether all `out' parameters have been assigned.
3755                 //
3756                 public void CheckControlExit (FlowAnalysisContext fc)
3757                 {
3758                         CheckControlExit (fc, fc.DefiniteAssignment);
3759                 }
3760
3761                 public virtual void CheckControlExit (FlowAnalysisContext fc, DefiniteAssignmentBitSet dat)
3762                 {
3763                         if (parameter_info == null)
3764                                 return;
3765
3766                         foreach (var p in parameter_info) {
3767                                 if (p.VariableInfo == null)
3768                                         continue;
3769
3770                                 if (p.VariableInfo.IsAssigned (dat))
3771                                         continue;
3772
3773                                 fc.Report.Error (177, p.Location,
3774                                         "The out parameter `{0}' must be assigned to before control leaves the current method",
3775                                         p.Parameter.Name);
3776                         }                                       
3777                 }
3778
3779                 protected override void CloneTo (CloneContext clonectx, Statement t)
3780                 {
3781                         base.CloneTo (clonectx, t);
3782
3783                         var target = (ParametersBlock) t;
3784
3785                         //
3786                         // Clone label statements as well as they contain block reference
3787                         //
3788                         var pb = this;
3789                         while (true) {
3790                                 if (pb.labels != null) {
3791                                         target.labels = new Dictionary<string, object> ();
3792
3793                                         foreach (var entry in pb.labels) {
3794                                                 var list = entry.Value as List<LabeledStatement>;
3795
3796                                                 if (list != null) {
3797                                                         var list_clone = new List<LabeledStatement> ();
3798                                                         foreach (var lentry in list) {
3799                                                                 list_clone.Add (RemapLabeledStatement (lentry, clonectx.RemapBlockCopy (lentry.Block)));
3800                                                         }
3801
3802                                                         target.labels.Add (entry.Key, list_clone);
3803                                                 } else {
3804                                                         var labeled = (LabeledStatement) entry.Value;
3805                                                         target.labels.Add (entry.Key, RemapLabeledStatement (labeled, clonectx.RemapBlockCopy (labeled.Block)));
3806                                                 }
3807                                         }
3808
3809                                         break;
3810                                 }
3811
3812                                 if (pb.Parent == null)
3813                                         break;
3814
3815                                 pb = pb.Parent.ParametersBlock;
3816                         }
3817                 }
3818
3819                 public override Expression CreateExpressionTree (ResolveContext ec)
3820                 {
3821                         if (statements.Count == 1) {
3822                                 Expression expr = statements[0].CreateExpressionTree (ec);
3823                                 if (scope_initializers != null)
3824                                         expr = new BlockScopeExpression (expr, this);
3825
3826                                 return expr;
3827                         }
3828
3829                         return base.CreateExpressionTree (ec);
3830                 }
3831
3832                 public override void Emit (EmitContext ec)
3833                 {
3834                         if (state_machine != null && state_machine.OriginalSourceBlock != this) {
3835                                 DefineStoreyContainer (ec, state_machine);
3836                                 state_machine.EmitStoreyInstantiation (ec, this);
3837                         }
3838
3839                         base.Emit (ec);
3840                 }
3841
3842                 public void EmitEmbedded (EmitContext ec)
3843                 {
3844                         if (state_machine != null && state_machine.OriginalSourceBlock != this) {
3845                                 DefineStoreyContainer (ec, state_machine);
3846                                 state_machine.EmitStoreyInstantiation (ec, this);
3847                         }
3848
3849                         base.Emit (ec);
3850                 }
3851
3852                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
3853                 {
3854                         var res = base.DoFlowAnalysis (fc);
3855
3856                         if (HasReachableClosingBrace)
3857                                 CheckControlExit (fc);
3858
3859                         return res;
3860                 }
3861
3862                 public LabeledStatement GetLabel (string name, Block block)
3863                 {
3864                         //
3865                         // Cloned parameters blocks can have their own cloned version of top-level labels
3866                         //
3867                         if (labels == null) {
3868                                 if (Parent != null)
3869                                         return Parent.ParametersBlock.GetLabel (name, block);
3870
3871                                 return null;
3872                         }
3873
3874                         object value;
3875                         if (!labels.TryGetValue (name, out value)) {
3876                                 return null;
3877                         }
3878
3879                         var label = value as LabeledStatement;
3880                         Block b = block;
3881                         if (label != null) {
3882                                 if (IsLabelVisible (label, b))
3883                                         return label;
3884
3885                         } else {
3886                                 List<LabeledStatement> list = (List<LabeledStatement>) value;
3887                                 for (int i = 0; i < list.Count; ++i) {
3888                                         label = list[i];
3889                                         if (IsLabelVisible (label, b))
3890                                                 return label;
3891                                 }
3892                         }
3893
3894                         return null;
3895                 }
3896
3897                 static bool IsLabelVisible (LabeledStatement label, Block b)
3898                 {
3899                         do {
3900                                 if (label.Block == b)
3901                                         return true;
3902                                 b = b.Parent;
3903                         } while (b != null);
3904
3905                         return false;
3906                 }
3907
3908                 public ParameterInfo GetParameterInfo (Parameter p)
3909                 {
3910                         for (int i = 0; i < parameters.Count; ++i) {
3911                                 if (parameters[i] == p)
3912                                         return parameter_info[i];
3913                         }
3914
3915                         throw new ArgumentException ("Invalid parameter");
3916                 }
3917
3918                 public ParameterReference GetParameterReference (int index, Location loc)
3919                 {
3920                         return new ParameterReference (parameter_info[index], loc);
3921                 }
3922
3923                 public Statement PerformClone (ref HashSet<LocalVariable> undeclaredVariables)
3924                 {
3925                         undeclaredVariables = TopBlock.GetUndeclaredVariables ();
3926
3927                         CloneContext clonectx = new CloneContext ();
3928                         return Clone (clonectx);
3929                 }
3930
3931                 protected void ProcessParameters ()
3932                 {
3933                         if (parameters.Count == 0)
3934                                 return;
3935
3936                         parameter_info = new ParameterInfo[parameters.Count];
3937                         for (int i = 0; i < parameter_info.Length; ++i) {
3938                                 var p = parameters.FixedParameters[i];
3939                                 if (p == null)
3940                                         continue;
3941
3942                                 // TODO: Should use Parameter only and more block there
3943                                 parameter_info[i] = new ParameterInfo (this, i);
3944                                 if (p.Name != null)
3945                                         AddLocalName (p.Name, parameter_info[i]);
3946                         }
3947                 }
3948
3949                 LabeledStatement RemapLabeledStatement (LabeledStatement stmt, Block dst)
3950                 {
3951                         var src = stmt.Block;
3952
3953                         //
3954                         // Cannot remap label block if the label was not yet cloned which
3955                         // can happen in case of anonymous method inside anoynymous method
3956                         // with a label. But in this case we don't care because goto cannot
3957                         // jump of out anonymous method
3958                         //
3959                         if (src.ParametersBlock != this)
3960                                 return stmt;
3961
3962                         var src_stmts = src.Statements;
3963                         for (int i = 0; i < src_stmts.Count; ++i) {
3964                                 if (src_stmts[i] == stmt)
3965                                         return (LabeledStatement) dst.Statements[i];
3966                         }
3967
3968                         throw new InternalErrorException ("Should never be reached");
3969                 }
3970
3971                 public override bool Resolve (BlockContext bc)
3972                 {
3973                         // TODO: if ((flags & Flags.Resolved) != 0)
3974
3975                         if (resolved)
3976                                 return true;
3977
3978                         resolved = true;
3979
3980                         if (bc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
3981                                 flags |= Flags.IsExpressionTree;
3982
3983                         try {
3984                                 PrepareAssignmentAnalysis (bc);
3985
3986                                 if (!base.Resolve (bc))
3987                                         return false;
3988
3989                         } catch (Exception e) {
3990                                 if (e is CompletionResult || bc.Report.IsDisabled || e is FatalException || bc.Report.Printer is NullReportPrinter || bc.Module.Compiler.Settings.BreakOnInternalError)
3991                                         throw;
3992
3993                                 if (bc.CurrentBlock != null) {
3994                                         bc.Report.Error (584, bc.CurrentBlock.StartLocation, "Internal compiler error: {0}", e.Message);
3995                                 } else {
3996                                         bc.Report.Error (587, "Internal compiler error: {0}", e.Message);
3997                                 }
3998                         }
3999
4000                         //
4001                         // If an asynchronous body of F is either an expression classified as nothing, or a 
4002                         // statement block where no return statements have expressions, the inferred return type is Task
4003                         //
4004                         if (IsAsync) {
4005                                 var am = bc.CurrentAnonymousMethod as AnonymousMethodBody;
4006                                 if (am != null && am.ReturnTypeInference != null && !am.ReturnTypeInference.HasBounds (0)) {
4007                                         am.ReturnTypeInference = null;
4008                                         am.ReturnType = bc.Module.PredefinedTypes.Task.TypeSpec;
4009                                         return true;
4010                                 }
4011                         }
4012
4013                         return true;
4014                 }
4015
4016                 void PrepareAssignmentAnalysis (BlockContext bc)
4017                 {
4018                         for (int i = 0; i < parameters.Count; ++i) {
4019                                 var par = parameters.FixedParameters[i];
4020
4021                                 if ((par.ModFlags & Parameter.Modifier.OUT) == 0)
4022                                         continue;
4023
4024                                 parameter_info [i].VariableInfo = VariableInfo.Create (bc, (Parameter) par);
4025                         }
4026                 }
4027
4028                 public ToplevelBlock ConvertToIterator (IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
4029                 {
4030                         var iterator = new Iterator (this, method, host, iterator_type, is_enumerable);
4031                         var stateMachine = new IteratorStorey (iterator);
4032
4033                         state_machine = stateMachine;
4034                         iterator.SetStateMachine (stateMachine);
4035
4036                         var tlb = new ToplevelBlock (host.Compiler, Parameters, Location.Null, Flags.CompilerGenerated);
4037                         tlb.Original = this;
4038                         tlb.state_machine = stateMachine;
4039                         tlb.AddStatement (new Return (iterator, iterator.Location));
4040                         return tlb;
4041                 }
4042
4043                 public ParametersBlock ConvertToAsyncTask (IMemberContext context, TypeDefinition host, ParametersCompiled parameters, TypeSpec returnType, TypeSpec delegateType, Location loc)
4044                 {
4045                         for (int i = 0; i < parameters.Count; i++) {
4046                                 Parameter p = parameters[i];
4047                                 Parameter.Modifier mod = p.ModFlags;
4048                                 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
4049                                         host.Compiler.Report.Error (1988, p.Location,
4050                                                 "Async methods cannot have ref or out parameters");
4051                                         return this;
4052                                 }
4053
4054                                 if (p is ArglistParameter) {
4055                                         host.Compiler.Report.Error (4006, p.Location,
4056                                                 "__arglist is not allowed in parameter list of async methods");
4057                                         return this;
4058                                 }
4059
4060                                 if (parameters.Types[i].IsPointer) {
4061                                         host.Compiler.Report.Error (4005, p.Location,
4062                                                 "Async methods cannot have unsafe parameters");
4063                                         return this;
4064                                 }
4065                         }
4066
4067                         if (!HasAwait) {
4068                                 host.Compiler.Report.Warning (1998, 1, loc,
4069                                         "Async block lacks `await' operator and will run synchronously");
4070                         }
4071
4072                         var block_type = host.Module.Compiler.BuiltinTypes.Void;
4073                         var initializer = new AsyncInitializer (this, host, block_type);
4074                         initializer.Type = block_type;
4075                         initializer.DelegateType = delegateType;
4076
4077                         var stateMachine = new AsyncTaskStorey (this, context, initializer, returnType);
4078
4079                         state_machine = stateMachine;
4080                         initializer.SetStateMachine (stateMachine);
4081
4082                         const Flags flags = Flags.CompilerGenerated;
4083
4084                         var b = this is ToplevelBlock ?
4085                                 new ToplevelBlock (host.Compiler, Parameters, Location.Null, flags) :
4086                                 new ParametersBlock (Parent, parameters, Location.Null, flags | Flags.HasAsyncModifier);
4087
4088                         b.Original = this;
4089                         b.state_machine = stateMachine;
4090                         b.AddStatement (new AsyncInitializerStatement (initializer));
4091                         return b;
4092                 }
4093         }
4094
4095         //
4096         //
4097         //
4098         public class ToplevelBlock : ParametersBlock
4099         {
4100                 LocalVariable this_variable;
4101                 CompilerContext compiler;
4102                 Dictionary<string, object> names;
4103
4104                 List<ExplicitBlock> this_references;
4105
4106                 public ToplevelBlock (CompilerContext ctx, Location loc)
4107                         : this (ctx, ParametersCompiled.EmptyReadOnlyParameters, loc)
4108                 {
4109                 }
4110
4111                 public ToplevelBlock (CompilerContext ctx, ParametersCompiled parameters, Location start, Flags flags = 0)
4112                         : base (parameters, start)
4113                 {
4114                         this.compiler = ctx;
4115                         this.flags = flags;
4116                         top_block = this;
4117
4118                         ProcessParameters ();
4119                 }
4120
4121                 //
4122                 // Recreates a top level block from parameters block. Used for
4123                 // compiler generated methods where the original block comes from
4124                 // explicit child block. This works for already resolved blocks
4125                 // only to ensure we resolve them in the correct flow order
4126                 //
4127                 public ToplevelBlock (ParametersBlock source, ParametersCompiled parameters)
4128                         : base (source, parameters)
4129                 {
4130                         this.compiler = source.TopBlock.compiler;
4131                         top_block = this;
4132                 }
4133
4134                 public bool IsIterator {
4135                         get {
4136                                 return (flags & Flags.Iterator) != 0;
4137                         }
4138                         set {
4139                                 flags = value ? flags | Flags.Iterator : flags & ~Flags.Iterator;
4140                         }
4141                 }
4142
4143                 public Report Report {
4144                         get {
4145                                 return compiler.Report;
4146                         }
4147                 }
4148
4149                 //
4150                 // Used by anonymous blocks to track references of `this' variable
4151                 //
4152                 public List<ExplicitBlock> ThisReferencesFromChildrenBlock {
4153                         get {
4154                                 return this_references;
4155                         }
4156                 }
4157
4158                 //
4159                 // Returns the "this" instance variable of this block.
4160                 // See AddThisVariable() for more information.
4161                 //
4162                 public LocalVariable ThisVariable {
4163                         get {
4164                                 return this_variable;
4165                         }
4166                 }
4167
4168                 public void AddLocalName (string name, INamedBlockVariable li, bool ignoreChildrenBlocks)
4169                 {
4170                         if (names == null)
4171                                 names = new Dictionary<string, object> ();
4172
4173                         object value;
4174                         if (!names.TryGetValue (name, out value)) {
4175                                 names.Add (name, li);
4176                                 return;
4177                         }
4178
4179                         INamedBlockVariable existing = value as INamedBlockVariable;
4180                         List<INamedBlockVariable> existing_list;
4181                         if (existing != null) {
4182                                 existing_list = new List<INamedBlockVariable> ();
4183                                 existing_list.Add (existing);
4184                                 names[name] = existing_list;
4185                         } else {
4186                                 existing_list = (List<INamedBlockVariable>) value;
4187                         }
4188
4189                         //
4190                         // A collision checking between local names
4191                         //
4192                         var variable_block = li.Block.Explicit;
4193                         for (int i = 0; i < existing_list.Count; ++i) {
4194                                 existing = existing_list[i];
4195                                 Block b = existing.Block.Explicit;
4196
4197                                 // Collision at same level
4198                                 if (variable_block == b) {
4199                                         li.Block.Error_AlreadyDeclared (name, li);
4200                                         break;
4201                                 }
4202
4203                                 // Collision with parent
4204                                 Block parent = variable_block;
4205                                 while ((parent = parent.Parent) != null) {
4206                                         if (parent == b) {
4207                                                 li.Block.Error_AlreadyDeclared (name, li, "parent or current");
4208                                                 i = existing_list.Count;
4209                                                 break;
4210                                         }
4211                                 }
4212
4213                                 if (!ignoreChildrenBlocks && variable_block.Parent != b.Parent) {
4214                                         // Collision with children
4215                                         while ((b = b.Parent) != null) {
4216                                                 if (variable_block == b) {
4217                                                         li.Block.Error_AlreadyDeclared (name, li, "child");
4218                                                         i = existing_list.Count;
4219                                                         break;
4220                                                 }
4221                                         }
4222                                 }
4223                         }
4224
4225                         existing_list.Add (li);
4226                 }
4227
4228                 public void AddLabel (string name, LabeledStatement label)
4229                 {
4230                         if (labels == null)
4231                                 labels = new Dictionary<string, object> ();
4232
4233                         object value;
4234                         if (!labels.TryGetValue (name, out value)) {
4235                                 labels.Add (name, label);
4236                                 return;
4237                         }
4238
4239                         LabeledStatement existing = value as LabeledStatement;
4240                         List<LabeledStatement> existing_list;
4241                         if (existing != null) {
4242                                 existing_list = new List<LabeledStatement> ();
4243                                 existing_list.Add (existing);
4244                                 labels[name] = existing_list;
4245                         } else {
4246                                 existing_list = (List<LabeledStatement>) value;
4247                         }
4248
4249                         //
4250                         // A collision checking between labels
4251                         //
4252                         for (int i = 0; i < existing_list.Count; ++i) {
4253                                 existing = existing_list[i];
4254                                 Block b = existing.Block;
4255
4256                                 // Collision at same level
4257                                 if (label.Block == b) {
4258                                         Report.SymbolRelatedToPreviousError (existing.loc, name);
4259                                         Report.Error (140, label.loc, "The label `{0}' is a duplicate", name);
4260                                         break;
4261                                 }
4262
4263                                 // Collision with parent
4264                                 b = label.Block;
4265                                 while ((b = b.Parent) != null) {
4266                                         if (existing.Block == b) {
4267                                                 Report.Error (158, label.loc,
4268                                                         "The label `{0}' shadows another label by the same name in a contained scope", name);
4269                                                 i = existing_list.Count;
4270                                                 break;
4271                                         }
4272                                 }
4273
4274                                 // Collision with with children
4275                                 b = existing.Block;
4276                                 while ((b = b.Parent) != null) {
4277                                         if (label.Block == b) {
4278                                                 Report.Error (158, label.loc,
4279                                                         "The label `{0}' shadows another label by the same name in a contained scope", name);
4280                                                 i = existing_list.Count;
4281                                                 break;
4282                                         }
4283                                 }
4284                         }
4285
4286                         existing_list.Add (label);
4287                 }
4288
4289                 public void AddThisReferenceFromChildrenBlock (ExplicitBlock block)
4290                 {
4291                         if (this_references == null)
4292                                 this_references = new List<ExplicitBlock> ();
4293
4294                         if (!this_references.Contains (block))
4295                                 this_references.Add (block);
4296                 }
4297
4298                 public void RemoveThisReferenceFromChildrenBlock (ExplicitBlock block)
4299                 {
4300                         this_references.Remove (block);
4301                 }
4302
4303                 //
4304                 // Creates an arguments set from all parameters, useful for method proxy calls
4305                 //
4306                 public Arguments GetAllParametersArguments ()
4307                 {
4308                         int count = parameters.Count;
4309                         Arguments args = new Arguments (count);
4310                         for (int i = 0; i < count; ++i) {
4311                                 var pi = parameter_info[i];
4312                                 var arg_expr = GetParameterReference (i, pi.Location);
4313
4314                                 Argument.AType atype_modifier;
4315                                 switch (pi.Parameter.ParameterModifier & Parameter.Modifier.RefOutMask) {
4316                                 case Parameter.Modifier.REF:
4317                                         atype_modifier = Argument.AType.Ref;
4318                                         break;
4319                                 case Parameter.Modifier.OUT:
4320                                         atype_modifier = Argument.AType.Out;
4321                                         break;
4322                                 default:
4323                                         atype_modifier = 0;
4324                                         break;
4325                                 }
4326
4327                                 args.Add (new Argument (arg_expr, atype_modifier));
4328                         }
4329
4330                         return args;
4331                 }
4332
4333                 //
4334                 // Lookup inside a block, the returned value can represent 3 states
4335                 //
4336                 // true+variable: A local name was found and it's valid
4337                 // false+variable: A local name was found in a child block only
4338                 // false+null: No local name was found
4339                 //
4340                 public bool GetLocalName (string name, Block block, ref INamedBlockVariable variable)
4341                 {
4342                         if (names == null)
4343                                 return false;
4344
4345                         object value;
4346                         if (!names.TryGetValue (name, out value))
4347                                 return false;
4348
4349                         variable = value as INamedBlockVariable;
4350                         Block b = block;
4351                         if (variable != null) {
4352                                 do {
4353                                         if (variable.Block == b.Original)
4354                                                 return true;
4355
4356                                         b = b.Parent;
4357                                 } while (b != null);
4358
4359                                 b = variable.Block;
4360                                 do {
4361                                         if (block == b)
4362                                                 return false;
4363
4364                                         b = b.Parent;
4365                                 } while (b != null);
4366                         } else {
4367                                 List<INamedBlockVariable> list = (List<INamedBlockVariable>) value;
4368                                 for (int i = 0; i < list.Count; ++i) {
4369                                         variable = list[i];
4370                                         do {
4371                                                 if (variable.Block == b.Original)
4372                                                         return true;
4373
4374                                                 b = b.Parent;
4375                                         } while (b != null);
4376
4377                                         b = variable.Block;
4378                                         do {
4379                                                 if (block == b)
4380                                                         return false;
4381
4382                                                 b = b.Parent;
4383                                         } while (b != null);
4384
4385                                         b = block;
4386                                 }
4387                         }
4388
4389                         variable = null;
4390                         return false;
4391                 }
4392
4393                 public void IncludeBlock (ParametersBlock pb, ToplevelBlock block)
4394                 {
4395                         if (block.names != null) {
4396                                 foreach (var n in block.names) {
4397                                         var variable = n.Value as INamedBlockVariable;
4398                                         if (variable != null) {
4399                                                 if (variable.Block.ParametersBlock == pb)
4400                                                         AddLocalName (n.Key, variable, false);
4401                                                 continue;
4402                                         }
4403
4404                                         foreach (var v in (List<INamedBlockVariable>) n.Value)
4405                                                 if (v.Block.ParametersBlock == pb)
4406                                                         AddLocalName (n.Key, v, false);
4407                                 }
4408                         }
4409                 }
4410
4411                 // <summary>
4412                 //   This is used by non-static `struct' constructors which do not have an
4413                 //   initializer - in this case, the constructor must initialize all of the
4414                 //   struct's fields.  To do this, we add a "this" variable and use the flow
4415                 //   analysis code to ensure that it's been fully initialized before control
4416                 //   leaves the constructor.
4417                 // </summary>
4418                 public void AddThisVariable (BlockContext bc)
4419                 {
4420                         if (this_variable != null)
4421                                 throw new InternalErrorException (StartLocation.ToString ());
4422
4423                         this_variable = new LocalVariable (this, "this", LocalVariable.Flags.IsThis | LocalVariable.Flags.Used, StartLocation);
4424                         this_variable.Type = bc.CurrentType;
4425                         this_variable.PrepareAssignmentAnalysis (bc);
4426                 }
4427
4428                 public override void CheckControlExit (FlowAnalysisContext fc, DefiniteAssignmentBitSet dat)
4429                 {
4430                         //
4431                         // If we're a non-static struct constructor which doesn't have an
4432                         // initializer, then we must initialize all of the struct's fields.
4433                         //
4434                         if (this_variable != null)
4435                                 this_variable.IsThisAssigned (fc, this);
4436
4437                         base.CheckControlExit (fc, dat);
4438                 }
4439
4440                 public HashSet<LocalVariable> GetUndeclaredVariables ()
4441                 {
4442                         if (names == null)
4443                                 return null;
4444
4445                         HashSet<LocalVariable> variables = null;
4446
4447                         foreach (var entry in names) {
4448                                 var complex = entry.Value as List<INamedBlockVariable>;
4449                                 if (complex != null) {
4450                                         foreach (var centry in complex) {
4451                                                 if (IsUndeclaredVariable (centry)) {
4452                                                         if (variables == null)
4453                                                                 variables = new HashSet<LocalVariable> ();
4454
4455                                                         variables.Add ((LocalVariable) centry);
4456                                                 }
4457                                         }
4458                                 } else if (IsUndeclaredVariable ((INamedBlockVariable)entry.Value)) {
4459                                         if (variables == null)
4460                                                 variables = new HashSet<LocalVariable> ();
4461
4462                                         variables.Add ((LocalVariable)entry.Value);                                     
4463                                 }
4464                         }
4465
4466                         return variables;
4467                 }
4468
4469                 static bool IsUndeclaredVariable (INamedBlockVariable namedBlockVariable)
4470                 {
4471                         var lv = namedBlockVariable as LocalVariable;
4472                         return lv != null && !lv.IsDeclared;
4473                 }
4474
4475                 public void SetUndeclaredVariables (HashSet<LocalVariable> undeclaredVariables)
4476                 {
4477                         if (names == null)
4478                                 return;
4479                         
4480                         foreach (var entry in names) {
4481                                 var complex = entry.Value as List<INamedBlockVariable>;
4482                                 if (complex != null) {
4483                                         foreach (var centry in complex) {
4484                                                 var lv = centry as LocalVariable;
4485                                                 if (lv != null && undeclaredVariables.Contains (lv)) {
4486                                                         lv.Type = null;
4487                                                 }
4488                                         }
4489                                 } else {
4490                                         var lv = entry.Value as LocalVariable;
4491                                         if (lv != null && undeclaredVariables.Contains (lv))
4492                                                 lv.Type = null;
4493                                 }
4494                         }
4495                 }
4496
4497                 public override void Emit (EmitContext ec)
4498                 {
4499                         if (Report.Errors > 0)
4500                                 return;
4501
4502                         try {
4503                         if (IsCompilerGenerated) {
4504                                 using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
4505                                         base.Emit (ec);
4506                                 }
4507                         } else {
4508                                 base.Emit (ec);
4509                         }
4510
4511                         //
4512                         // If `HasReturnLabel' is set, then we already emitted a
4513                         // jump to the end of the method, so we must emit a `ret'
4514                         // there.
4515                         //
4516                         // Unfortunately, System.Reflection.Emit automatically emits
4517                         // a leave to the end of a finally block.  This is a problem
4518                         // if no code is following the try/finally block since we may
4519                         // jump to a point after the end of the method.
4520                         // As a workaround, we're always creating a return label in
4521                         // this case.
4522                         //
4523                         if (ec.HasReturnLabel || HasReachableClosingBrace) {
4524                                 if (ec.HasReturnLabel)
4525                                         ec.MarkLabel (ec.ReturnLabel);
4526
4527                                 if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated)
4528                                         ec.Mark (EndLocation);
4529
4530                                 if (ec.ReturnType.Kind != MemberKind.Void)
4531                                         ec.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4532
4533                                 ec.Emit (OpCodes.Ret);
4534                         }
4535
4536                         } catch (Exception e) {
4537                                 throw new InternalErrorException (e, StartLocation);
4538                         }
4539                 }
4540
4541                 public bool Resolve (BlockContext bc, IMethodData md)
4542                 {
4543                         if (resolved)
4544                                 return true;
4545
4546                         var errors = bc.Report.Errors;
4547
4548                         base.Resolve (bc);
4549
4550                         if (bc.Report.Errors > errors)
4551                                 return false;
4552
4553                         MarkReachable (new Reachability ());
4554
4555                         if (HasReachableClosingBrace && bc.ReturnType.Kind != MemberKind.Void) {
4556                                 // TODO: var md = bc.CurrentMemberDefinition;
4557                                 bc.Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
4558                         }
4559
4560                         if ((flags & Flags.NoFlowAnalysis) != 0)
4561                                 return true;
4562
4563                         var fc = new FlowAnalysisContext (bc.Module.Compiler, this, bc.AssignmentInfoOffset);
4564                         try {
4565                                 FlowAnalysis (fc);
4566                         } catch (Exception e) {
4567                                 throw new InternalErrorException (e, StartLocation);
4568                         }
4569
4570                         return true;
4571                 }
4572         }
4573         
4574         public class SwitchLabel : Statement
4575         {
4576                 Constant converted;
4577                 Expression label;
4578
4579                 Label? il_label;
4580
4581                 //
4582                 // if expr == null, then it is the default case.
4583                 //
4584                 public SwitchLabel (Expression expr, Location l)
4585                 {
4586                         label = expr;
4587                         loc = l;
4588                 }
4589
4590                 public bool IsDefault {
4591                         get {
4592                                 return label == null;
4593                         }
4594                 }
4595
4596                 public Expression Label {
4597                         get {
4598                                 return label;
4599                         }
4600                 }
4601
4602                 public Location Location {
4603                         get {
4604                                 return loc;
4605                         }
4606                 }
4607
4608                 public Constant Converted {
4609                         get {
4610                                 return converted;
4611                         }
4612                         set {
4613                                 converted = value; 
4614                         }
4615                 }
4616
4617                 public bool PatternMatching { get; set; }
4618
4619                 public bool SectionStart { get; set; }
4620
4621                 public Label GetILLabel (EmitContext ec)
4622                 {
4623                         if (il_label == null){
4624                                 il_label = ec.DefineLabel ();
4625                         }
4626
4627                         return il_label.Value;
4628                 }
4629
4630                 protected override void DoEmit (EmitContext ec)
4631                 {
4632                         ec.MarkLabel (GetILLabel (ec));
4633                 }
4634
4635                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
4636                 {
4637                         if (!SectionStart)
4638                                 return false;
4639
4640                         fc.BranchDefiniteAssignment (fc.SwitchInitialDefinitiveAssignment);
4641                         return false;
4642                 }
4643
4644                 public override bool Resolve (BlockContext bc)
4645                 {
4646                         if (ResolveAndReduce (bc))
4647                                 bc.Switch.RegisterLabel (bc, this);
4648
4649                         return true;
4650                 }
4651
4652                 //
4653                 // Resolves the expression, reduces it to a literal if possible
4654                 // and then converts it to the requested type.
4655                 //
4656                 bool ResolveAndReduce (BlockContext bc)
4657                 {
4658                         if (IsDefault)
4659                                 return true;
4660
4661                         var switch_statement = bc.Switch;
4662
4663                         if (PatternMatching) {
4664                                 label = new Is (switch_statement.ExpressionValue, label, loc).Resolve (bc);
4665                                 return label != null;
4666                         }
4667
4668                         var c = label.ResolveLabelConstant (bc);
4669                         if (c == null)
4670                                 return false;
4671
4672                         if (switch_statement.IsNullable && c is NullLiteral) {
4673                                 converted = c;
4674                                 return true;
4675                         }
4676
4677                         if (switch_statement.IsPatternMatching) {
4678                                 label = new Is (switch_statement.ExpressionValue, label, loc).Resolve (bc);
4679                                 return true;
4680                         }
4681
4682                         converted = c.ImplicitConversionRequired (bc, switch_statement.SwitchType);
4683                         return converted != null;
4684                 }
4685
4686                 public void Error_AlreadyOccurs (ResolveContext ec, SwitchLabel collision_with)
4687                 {
4688                         ec.Report.SymbolRelatedToPreviousError (collision_with.loc, null);
4689                         ec.Report.Error (152, loc, "The label `{0}' already occurs in this switch statement", GetSignatureForError ());
4690                 }
4691
4692                 protected override void CloneTo (CloneContext clonectx, Statement target)
4693                 {
4694                         var t = (SwitchLabel) target;
4695                         if (label != null)
4696                                 t.label = label.Clone (clonectx);
4697                 }
4698
4699                 public override object Accept (StructuralVisitor visitor)
4700                 {
4701                         return visitor.Visit (this);
4702                 }
4703
4704                 public string GetSignatureForError ()
4705                 {
4706                         string label;
4707                         if (converted == null)
4708                                 label = "default";
4709                         else
4710                                 label = converted.GetValueAsLiteral ();
4711
4712                         return string.Format ("case {0}:", label);
4713                 }
4714         }
4715
4716         public class Switch : LoopStatement
4717         {
4718                 // structure used to hold blocks of keys while calculating table switch
4719                 sealed class LabelsRange : IComparable<LabelsRange>
4720                 {
4721                         public readonly long min;
4722                         public long max;
4723                         public readonly List<long> label_values;
4724
4725                         public LabelsRange (long value)
4726                         {
4727                                 min = max = value;
4728                                 label_values = new List<long> ();
4729                                 label_values.Add (value);
4730                         }
4731
4732                         public LabelsRange (long min, long max, ICollection<long> values)
4733                         {
4734                                 this.min = min;
4735                                 this.max = max;
4736                                 this.label_values = new List<long> (values);
4737                         }
4738
4739                         public long Range {
4740                                 get {
4741                                         return max - min + 1;
4742                                 }
4743                         }
4744
4745                         public bool AddValue (long value)
4746                         {
4747                                 var gap = value - min + 1;
4748                                 // Ensure the range has > 50% occupancy
4749                                 if (gap > 2 * (label_values.Count + 1) || gap <= 0)
4750                                         return false;
4751
4752                                 max = value;
4753                                 label_values.Add (value);
4754                                 return true;
4755                         }
4756
4757                         public int CompareTo (LabelsRange other)
4758                         {
4759                                 int nLength = label_values.Count;
4760                                 int nLengthOther = other.label_values.Count;
4761                                 if (nLengthOther == nLength)
4762                                         return (int) (other.min - min);
4763
4764                                 return nLength - nLengthOther;
4765                         }
4766                 }
4767
4768                 sealed class DispatchStatement : Statement
4769                 {
4770                         readonly Switch body;
4771
4772                         public DispatchStatement (Switch body)
4773                         {
4774                                 this.body = body;
4775                         }
4776
4777                         protected override void CloneTo (CloneContext clonectx, Statement target)
4778                         {
4779                                 throw new NotImplementedException ();
4780                         }
4781
4782                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
4783                         {
4784                                 return false;
4785                         }
4786
4787                         protected override void DoEmit (EmitContext ec)
4788                         {
4789                                 body.EmitDispatch (ec);
4790                         }
4791                 }
4792
4793                 class MissingBreak : Statement
4794                 {
4795                         readonly SwitchLabel label;
4796
4797                         public MissingBreak (SwitchLabel sl)
4798                         {
4799                                 this.label = sl;
4800                                 this.loc = sl.loc;
4801                         }
4802
4803                         public bool FallOut { get; set; }
4804
4805                         protected override void DoEmit (EmitContext ec)
4806                         {
4807                         }
4808
4809                         protected override void CloneTo (CloneContext clonectx, Statement target)
4810                         {
4811                         }
4812
4813                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
4814                         {
4815                                 if (FallOut) {
4816                                         fc.Report.Error (8070, loc, "Control cannot fall out of switch statement through final case label `{0}'",
4817                                                 label.GetSignatureForError ());
4818                                 } else {
4819                                         fc.Report.Error (163, loc, "Control cannot fall through from one case label `{0}' to another",
4820                                                 label.GetSignatureForError ());
4821                                 }
4822                                 return true;
4823                         }
4824                 }
4825
4826                 public Expression Expr;
4827
4828                 //
4829                 // Mapping of all labels to their SwitchLabels
4830                 //
4831                 Dictionary<long, SwitchLabel> labels;
4832                 Dictionary<string, SwitchLabel> string_labels;
4833                 List<SwitchLabel> case_labels;
4834
4835                 List<Tuple<GotoCase, Constant>> goto_cases;
4836                 List<DefiniteAssignmentBitSet> end_reachable_das;
4837
4838                 /// <summary>
4839                 ///   The governing switch type
4840                 /// </summary>
4841                 public TypeSpec SwitchType;
4842
4843                 Expression new_expr;
4844
4845                 SwitchLabel case_null;
4846                 SwitchLabel case_default;
4847
4848                 Label defaultLabel, nullLabel;
4849                 VariableReference value;
4850                 ExpressionStatement string_dictionary;
4851                 FieldExpr switch_cache_field;
4852                 ExplicitBlock block;
4853                 bool end_reachable;
4854
4855                 //
4856                 // Nullable Types support
4857                 //
4858                 Nullable.Unwrap unwrap;
4859
4860                 public Switch (Expression e, ExplicitBlock block, Location l)
4861                         : base (block)
4862                 {
4863                         Expr = e;
4864                         this.block = block;
4865                         loc = l;
4866                 }
4867
4868                 public SwitchLabel ActiveLabel { get; set; }
4869
4870                 public ExplicitBlock Block {
4871                         get {
4872                                 return block;
4873                         }
4874                 }
4875
4876                 public SwitchLabel DefaultLabel {
4877                         get {
4878                                 return case_default;
4879                         }
4880                 }
4881
4882                 public bool IsNullable {
4883                         get {
4884                                 return unwrap != null;
4885                         }
4886                 }
4887
4888                 public bool IsPatternMatching {
4889                         get {
4890                                 return new_expr == null && SwitchType != null;
4891                         }
4892                 }
4893
4894                 public List<SwitchLabel> RegisteredLabels {
4895                         get {
4896                                 return case_labels;
4897                         }
4898                 }
4899
4900                 public VariableReference ExpressionValue {
4901                         get {
4902                                 return value;
4903                         }
4904                 }
4905
4906                 //
4907                 // Determines the governing type for a switch.  The returned
4908                 // expression might be the expression from the switch, or an
4909                 // expression that includes any potential conversions to
4910                 //
4911                 static Expression SwitchGoverningType (ResolveContext rc, Expression expr, bool unwrapExpr)
4912                 {
4913                         switch (expr.Type.BuiltinType) {
4914                         case BuiltinTypeSpec.Type.Byte:
4915                         case BuiltinTypeSpec.Type.SByte:
4916                         case BuiltinTypeSpec.Type.UShort:
4917                         case BuiltinTypeSpec.Type.Short:
4918                         case BuiltinTypeSpec.Type.UInt:
4919                         case BuiltinTypeSpec.Type.Int:
4920                         case BuiltinTypeSpec.Type.ULong:
4921                         case BuiltinTypeSpec.Type.Long:
4922                         case BuiltinTypeSpec.Type.Char:
4923                         case BuiltinTypeSpec.Type.String:
4924                         case BuiltinTypeSpec.Type.Bool:
4925                                 return expr;
4926                         }
4927
4928                         if (expr.Type.IsEnum)
4929                                 return expr;
4930
4931                         //
4932                         // Try to find a *user* defined implicit conversion.
4933                         //
4934                         // If there is no implicit conversion, or if there are multiple
4935                         // conversions, we have to report an error
4936                         //
4937                         Expression converted = null;
4938                         foreach (TypeSpec tt in rc.Module.PredefinedTypes.SwitchUserTypes) {
4939
4940                                 if (!unwrapExpr && tt.IsNullableType && expr.Type.IsNullableType)
4941                                         break;
4942
4943                                 var restr = Convert.UserConversionRestriction.ImplicitOnly |
4944                                         Convert.UserConversionRestriction.ProbingOnly;
4945
4946                                 if (unwrapExpr)
4947                                         restr |= Convert.UserConversionRestriction.NullableSourceOnly;
4948
4949                                 var e = Convert.UserDefinedConversion (rc, expr, tt, restr, Location.Null);
4950                                 if (e == null)
4951                                         continue;
4952
4953                                 //
4954                                 // Ignore over-worked ImplicitUserConversions that do
4955                                 // an implicit conversion in addition to the user conversion.
4956                                 // 
4957                                 var uc = e as UserCast;
4958                                 if (uc == null)
4959                                         continue;
4960
4961                                 if (converted != null){
4962 //                                      rc.Report.ExtraInformation (loc, "(Ambiguous implicit user defined conversion in previous ");
4963                                         return null;
4964                                 }
4965
4966                                 converted = e;
4967                         }
4968                         return converted;
4969                 }
4970
4971                 public static TypeSpec[] CreateSwitchUserTypes (ModuleContainer module, TypeSpec nullable)
4972                 {
4973                         var types = module.Compiler.BuiltinTypes;
4974
4975                         // LAMESPEC: For some reason it does not contain bool which looks like csc bug
4976                         TypeSpec[] stypes = new[] {
4977                                 types.SByte,
4978                                 types.Byte,
4979                                 types.Short,
4980                                 types.UShort,
4981                                 types.Int,
4982                                 types.UInt,
4983                                 types.Long,
4984                                 types.ULong,
4985                                 types.Char,
4986                                 types.String
4987                         };
4988
4989                         if (nullable != null) {
4990
4991                                 Array.Resize (ref stypes, stypes.Length + 9);
4992
4993                                 for (int i = 0; i < 9; ++i) {
4994                                         stypes [10 + i] = nullable.MakeGenericType (module, new [] { stypes [i] });
4995                                 }
4996                         }
4997
4998                         return stypes;
4999                 }
5000
5001                 public void RegisterLabel (BlockContext rc, SwitchLabel sl)
5002                 {
5003                         case_labels.Add (sl);
5004
5005                         if (sl.IsDefault) {
5006                                 if (case_default != null) {
5007                                         sl.Error_AlreadyOccurs (rc, case_default);
5008                                 } else {
5009                                         case_default = sl;
5010                                 }
5011
5012                                 return;
5013                         }
5014
5015                         if (sl.Converted == null)
5016                                 return;
5017
5018                         try {
5019                                 if (string_labels != null) {
5020                                         string string_value = sl.Converted.GetValue () as string;
5021                                         if (string_value == null)
5022                                                 case_null = sl;
5023                                         else
5024                                                 string_labels.Add (string_value, sl);
5025                                 } else {
5026                                         if (sl.Converted.IsNull) {
5027                                                 case_null = sl;
5028                                         } else {
5029                                                 labels.Add (sl.Converted.GetValueAsLong (), sl);
5030                                         }
5031                                 }
5032                         } catch (ArgumentException) {
5033                                 if (string_labels != null)
5034                                         sl.Error_AlreadyOccurs (rc, string_labels[(string) sl.Converted.GetValue ()]);
5035                                 else
5036                                         sl.Error_AlreadyOccurs (rc, labels[sl.Converted.GetValueAsLong ()]);
5037                         }
5038                 }
5039                 
5040                 //
5041                 // This method emits code for a lookup-based switch statement (non-string)
5042                 // Basically it groups the cases into blocks that are at least half full,
5043                 // and then spits out individual lookup opcodes for each block.
5044                 // It emits the longest blocks first, and short blocks are just
5045                 // handled with direct compares.
5046                 //
5047                 void EmitTableSwitch (EmitContext ec, Expression val)
5048                 {
5049                         if (labels != null && labels.Count > 0) {
5050                                 List<LabelsRange> ranges;
5051                                 if (string_labels != null) {
5052                                         // We have done all hard work for string already
5053                                         // setup single range only
5054                                         ranges = new List<LabelsRange> (1);
5055                                         ranges.Add (new LabelsRange (0, labels.Count - 1, labels.Keys));
5056                                 } else {
5057                                         var element_keys = new long[labels.Count];
5058                                         labels.Keys.CopyTo (element_keys, 0);
5059                                         Array.Sort (element_keys);
5060
5061                                         //
5062                                         // Build possible ranges of switch labes to reduce number
5063                                         // of comparisons
5064                                         //
5065                                         ranges = new List<LabelsRange> (element_keys.Length);
5066                                         var range = new LabelsRange (element_keys[0]);
5067                                         ranges.Add (range);
5068                                         for (int i = 1; i < element_keys.Length; ++i) {
5069                                                 var l = element_keys[i];
5070                                                 if (range.AddValue (l))
5071                                                         continue;
5072
5073                                                 range = new LabelsRange (l);
5074                                                 ranges.Add (range);
5075                                         }
5076
5077                                         // sort the blocks so we can tackle the largest ones first
5078                                         ranges.Sort ();
5079                                 }
5080
5081                                 Label lbl_default = defaultLabel;
5082                                 TypeSpec compare_type = SwitchType.IsEnum ? EnumSpec.GetUnderlyingType (SwitchType) : SwitchType;
5083
5084                                 for (int range_index = ranges.Count - 1; range_index >= 0; --range_index) {
5085                                         LabelsRange kb = ranges[range_index];
5086                                         lbl_default = (range_index == 0) ? defaultLabel : ec.DefineLabel ();
5087
5088                                         // Optimize small ranges using simple equality check
5089                                         if (kb.Range <= 2) {
5090                                                 foreach (var key in kb.label_values) {
5091                                                         SwitchLabel sl = labels[key];
5092                                                         if (sl == case_default || sl == case_null)
5093                                                                 continue;
5094
5095                                                         if (sl.Converted.IsZeroInteger) {
5096                                                                 val.EmitBranchable (ec, sl.GetILLabel (ec), false);
5097                                                         } else {
5098                                                                 val.Emit (ec);
5099                                                                 sl.Converted.Emit (ec);
5100                                                                 ec.Emit (OpCodes.Beq, sl.GetILLabel (ec));
5101                                                         }
5102                                                 }
5103                                         } else {
5104                                                 // TODO: if all the keys in the block are the same and there are
5105                                                 //       no gaps/defaults then just use a range-check.
5106                                                 if (compare_type.BuiltinType == BuiltinTypeSpec.Type.Long || compare_type.BuiltinType == BuiltinTypeSpec.Type.ULong) {
5107                                                         // TODO: optimize constant/I4 cases
5108
5109                                                         // check block range (could be > 2^31)
5110                                                         val.Emit (ec);
5111                                                         ec.EmitLong (kb.min);
5112                                                         ec.Emit (OpCodes.Blt, lbl_default);
5113
5114                                                         val.Emit (ec);
5115                                                         ec.EmitLong (kb.max);
5116                                                         ec.Emit (OpCodes.Bgt, lbl_default);
5117
5118                                                         // normalize range
5119                                                         val.Emit (ec);
5120                                                         if (kb.min != 0) {
5121                                                                 ec.EmitLong (kb.min);
5122                                                                 ec.Emit (OpCodes.Sub);
5123                                                         }
5124
5125                                                         ec.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
5126                                                 } else {
5127                                                         // normalize range
5128                                                         val.Emit (ec);
5129                                                         int first = (int) kb.min;
5130                                                         if (first > 0) {
5131                                                                 ec.EmitInt (first);
5132                                                                 ec.Emit (OpCodes.Sub);
5133                                                         } else if (first < 0) {
5134                                                                 ec.EmitInt (-first);
5135                                                                 ec.Emit (OpCodes.Add);
5136                                                         }
5137                                                 }
5138
5139                                                 // first, build the list of labels for the switch
5140                                                 int iKey = 0;
5141                                                 long cJumps = kb.Range;
5142                                                 Label[] switch_labels = new Label[cJumps];
5143                                                 for (int iJump = 0; iJump < cJumps; iJump++) {
5144                                                         var key = kb.label_values[iKey];
5145                                                         if (key == kb.min + iJump) {
5146                                                                 switch_labels[iJump] = labels[key].GetILLabel (ec);
5147                                                                 iKey++;
5148                                                         } else {
5149                                                                 switch_labels[iJump] = lbl_default;
5150                                                         }
5151                                                 }
5152
5153                                                 // emit the switch opcode
5154                                                 ec.Emit (OpCodes.Switch, switch_labels);
5155                                         }
5156
5157                                         // mark the default for this block
5158                                         if (range_index != 0)
5159                                                 ec.MarkLabel (lbl_default);
5160                                 }
5161
5162                                 // the last default just goes to the end
5163                                 if (ranges.Count > 0)
5164                                         ec.Emit (OpCodes.Br, lbl_default);
5165                         }
5166                 }
5167                 
5168                 public SwitchLabel FindLabel (Constant value)
5169                 {
5170                         SwitchLabel sl = null;
5171
5172                         if (string_labels != null) {
5173                                 string s = value.GetValue () as string;
5174                                 if (s == null) {
5175                                         if (case_null != null)
5176                                                 sl = case_null;
5177                                         else if (case_default != null)
5178                                                 sl = case_default;
5179                                 } else {
5180                                         string_labels.TryGetValue (s, out sl);
5181                                 }
5182                         } else {
5183                                 if (value is NullLiteral) {
5184                                         sl = case_null;
5185                                 } else {
5186                                         labels.TryGetValue (value.GetValueAsLong (), out sl);
5187                                 }
5188                         }
5189
5190                         if (sl == null || sl.SectionStart)
5191                                 return sl;
5192
5193                         //
5194                         // Always return section start, it simplifies handling of switch labels
5195                         //
5196                         for (int idx = case_labels.IndexOf (sl); ; --idx) {
5197                                 var cs = case_labels [idx];
5198                                 if (cs.SectionStart)
5199                                         return cs;
5200                         }
5201                 }
5202
5203                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
5204                 {
5205                         Expr.FlowAnalysis (fc);
5206
5207                         var prev_switch = fc.SwitchInitialDefinitiveAssignment;
5208                         var InitialDefinitiveAssignment = fc.DefiniteAssignment;
5209                         fc.SwitchInitialDefinitiveAssignment = InitialDefinitiveAssignment;
5210
5211                         block.FlowAnalysis (fc);
5212
5213                         fc.SwitchInitialDefinitiveAssignment = prev_switch;
5214
5215                         if (end_reachable_das != null) {
5216                                 var sections_das = DefiniteAssignmentBitSet.And (end_reachable_das);
5217                                 InitialDefinitiveAssignment |= sections_das;
5218                                 end_reachable_das = null;
5219                         }
5220
5221                         fc.DefiniteAssignment = InitialDefinitiveAssignment;
5222
5223                         return case_default != null && !end_reachable;
5224                 }
5225
5226                 public override bool Resolve (BlockContext ec)
5227                 {
5228                         Expr = Expr.Resolve (ec);
5229                         if (Expr == null)
5230                                 return false;
5231
5232                         //
5233                         // LAMESPEC: User conversion from non-nullable governing type has a priority
5234                         //
5235                         new_expr = SwitchGoverningType (ec, Expr, false);
5236
5237                         if (new_expr == null) {
5238                                 if (Expr.Type.IsNullableType) {
5239                                         unwrap = Nullable.Unwrap.Create (Expr, false);
5240                                         if (unwrap == null)
5241                                                 return false;
5242
5243                                         //
5244                                         // Unwrap + user conversion using non-nullable type is not allowed but user operator
5245                                         // involving nullable Expr and nullable governing type is
5246                                         //
5247                                         new_expr = SwitchGoverningType (ec, unwrap, true);
5248                                 }
5249                         }
5250
5251                         Expression switch_expr;
5252                         if (new_expr == null) {
5253                                 if (ec.Module.Compiler.Settings.Version != LanguageVersion.Experimental) {
5254                                         if (Expr.Type != InternalType.ErrorType) {
5255                                                 ec.Report.Error (151, loc,
5256                                                         "A switch expression of type `{0}' cannot be converted to an integral type, bool, char, string, enum or nullable type",
5257                                                         Expr.Type.GetSignatureForError ());
5258                                         }
5259
5260                                         return false;
5261                                 }
5262
5263                                 switch_expr = Expr;
5264                                 SwitchType = Expr.Type;
5265                         } else {
5266                                 switch_expr = new_expr;
5267                                 SwitchType = new_expr.Type;
5268                                 if (SwitchType.IsNullableType) {
5269                                         new_expr = unwrap = Nullable.Unwrap.Create (new_expr, true);
5270                                         SwitchType = Nullable.NullableInfo.GetUnderlyingType (SwitchType);
5271                                 }
5272
5273                                 if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.Bool && ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
5274                                         ec.Report.FeatureIsNotAvailable (ec.Module.Compiler, loc, "switch expression of boolean type");
5275                                         return false;
5276                                 }
5277
5278                                 if (block.Statements.Count == 0)
5279                                         return true;
5280
5281                                 if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.String) {
5282                                         string_labels = new Dictionary<string, SwitchLabel> ();
5283                                 } else {
5284                                         labels = new Dictionary<long, SwitchLabel> ();
5285                                 }
5286                         }
5287
5288                         var constant = switch_expr as Constant;
5289
5290                         //
5291                         // Don't need extra variable for constant switch or switch with
5292                         // only default case
5293                         //
5294                         if (constant == null) {
5295                                 //
5296                                 // Store switch expression for comparison purposes
5297                                 //
5298                                 value = switch_expr as VariableReference;
5299                                 if (value == null && !HasOnlyDefaultSection ()) {
5300                                         var current_block = ec.CurrentBlock;
5301                                         ec.CurrentBlock = Block;
5302                                         // Create temporary variable inside switch scope
5303                                         value = TemporaryVariableReference.Create (SwitchType, ec.CurrentBlock, loc);
5304                                         value.Resolve (ec);
5305                                         ec.CurrentBlock = current_block;
5306                                 }
5307                         }
5308
5309                         case_labels = new List<SwitchLabel> ();
5310
5311                         Switch old_switch = ec.Switch;
5312                         ec.Switch = this;
5313                         var parent_los = ec.EnclosingLoopOrSwitch;
5314                         ec.EnclosingLoopOrSwitch = this;
5315
5316                         var ok = Statement.Resolve (ec);
5317
5318                         ec.EnclosingLoopOrSwitch = parent_los;
5319                         ec.Switch = old_switch;
5320
5321                         //
5322                         // Check if all goto cases are valid. Needs to be done after switch
5323                         // is resolved because goto can jump forward in the scope.
5324                         //
5325                         if (goto_cases != null) {
5326                                 foreach (var gc in goto_cases) {
5327                                         if (gc.Item1 == null) {
5328                                                 if (DefaultLabel == null) {
5329                                                         Goto.Error_UnknownLabel (ec, "default", loc);
5330                                                 }
5331
5332                                                 continue;
5333                                         }
5334
5335                                         var sl = FindLabel (gc.Item2);
5336                                         if (sl == null) {
5337                                                 Goto.Error_UnknownLabel (ec, "case " + gc.Item2.GetValueAsLiteral (), loc);
5338                                         } else {
5339                                                 gc.Item1.Label = sl;
5340                                         }
5341                                 }
5342                         }
5343
5344                         if (!ok)
5345                                 return false;
5346
5347                         if (constant == null && SwitchType.BuiltinType == BuiltinTypeSpec.Type.String && string_labels.Count > 6) {
5348                                 ResolveStringSwitchMap (ec);
5349                         }
5350
5351                         //
5352                         // Anonymous storey initialization has to happen before
5353                         // any generated switch dispatch
5354                         //
5355                         block.InsertStatement (0, new DispatchStatement (this));
5356
5357                         return true;
5358                 }
5359
5360                 bool HasOnlyDefaultSection ()
5361                 {
5362                         for (int i = 0; i < block.Statements.Count; ++i) {
5363                                 var s = block.Statements[i] as SwitchLabel;
5364
5365                                 if (s == null || s.IsDefault)
5366                                         continue;
5367
5368                                 return false;
5369                         }
5370
5371                         return true;
5372                 }
5373
5374                 public override Reachability MarkReachable (Reachability rc)
5375                 {
5376                         if (rc.IsUnreachable)
5377                                 return rc;
5378
5379                         base.MarkReachable (rc);
5380
5381                         block.MarkReachableScope (rc);
5382
5383                         if (block.Statements.Count == 0)
5384                                 return rc;
5385
5386                         SwitchLabel constant_label = null;
5387                         var constant = new_expr as Constant;
5388
5389                         if (constant != null) {
5390                                 constant_label = FindLabel (constant) ?? case_default;
5391                                 if (constant_label == null) {
5392                                         block.Statements.RemoveAt (0);
5393                                         return rc;
5394                                 }
5395                         }
5396
5397                         var section_rc = new Reachability ();
5398                         SwitchLabel prev_label = null;
5399
5400                         for (int i = 0; i < block.Statements.Count; ++i) {
5401                                 var s = block.Statements[i];
5402                                 var sl = s as SwitchLabel;
5403
5404                                 if (sl != null && sl.SectionStart) {
5405                                         //
5406                                         // Section is marked already via goto case
5407                                         //
5408                                         if (!sl.IsUnreachable) {
5409                                                 section_rc = new Reachability ();
5410                                                 continue;
5411                                         }
5412
5413                                         if (section_rc.IsUnreachable) {
5414                                                 //
5415                                                 // Common case. Previous label section end is unreachable as
5416                                                 // it ends with break, return, etc. For next section revert
5417                                                 // to reachable again unless we have constant switch block
5418                                                 //
5419                                                 section_rc = constant_label != null && constant_label != sl ?
5420                                                         Reachability.CreateUnreachable () :
5421                                                         new Reachability ();
5422                                         } else if (prev_label != null) {
5423                                                 //
5424                                                 // Error case as control cannot fall through from one case label
5425                                                 //
5426                                                 sl.SectionStart = false;
5427                                                 s = new MissingBreak (prev_label);
5428                                                 s.MarkReachable (rc);
5429                                                 block.Statements.Insert (i - 1, s);
5430                                                 ++i;
5431                                         } else if (constant_label != null && constant_label != sl) {
5432                                                 //
5433                                                 // Special case for the first unreachable label in constant
5434                                                 // switch block
5435                                                 //
5436                                                 section_rc = Reachability.CreateUnreachable ();
5437                                         }
5438
5439                                         prev_label = sl;
5440                                 }
5441
5442                                 section_rc = s.MarkReachable (section_rc);
5443                         }
5444
5445                         if (!section_rc.IsUnreachable && prev_label != null) {
5446                                 prev_label.SectionStart = false;
5447                                 var s = new MissingBreak (prev_label) {
5448                                         FallOut = true
5449                                 };
5450
5451                                 s.MarkReachable (rc);
5452                                 block.Statements.Add (s);
5453                         }
5454
5455                         //
5456                         // Reachability can affect parent only when all possible paths are handled but
5457                         // we still need to run reachability check on switch body to check for fall-through
5458                         //
5459                         if (case_default == null && constant_label == null)
5460                                 return rc;
5461
5462                         //
5463                         // We have at least one local exit from the switch
5464                         //
5465                         if (end_reachable)
5466                                 return rc;
5467
5468                         return Reachability.CreateUnreachable ();
5469                 }
5470
5471                 public void RegisterGotoCase (GotoCase gotoCase, Constant value)
5472                 {
5473                         if (goto_cases == null)
5474                                 goto_cases = new List<Tuple<GotoCase, Constant>> ();
5475
5476                         goto_cases.Add (Tuple.Create (gotoCase, value));
5477                 }
5478
5479                 //
5480                 // Converts string switch into string hashtable
5481                 //
5482                 void ResolveStringSwitchMap (ResolveContext ec)
5483                 {
5484                         FullNamedExpression string_dictionary_type;
5485                         if (ec.Module.PredefinedTypes.Dictionary.Define ()) {
5486                                 string_dictionary_type = new TypeExpression (
5487                                         ec.Module.PredefinedTypes.Dictionary.TypeSpec.MakeGenericType (ec,
5488                                                 new [] { ec.BuiltinTypes.String, ec.BuiltinTypes.Int }),
5489                                         loc);
5490                         } else if (ec.Module.PredefinedTypes.Hashtable.Define ()) {
5491                                 string_dictionary_type = new TypeExpression (ec.Module.PredefinedTypes.Hashtable.TypeSpec, loc);
5492                         } else {
5493                                 ec.Module.PredefinedTypes.Dictionary.Resolve ();
5494                                 return;
5495                         }
5496
5497                         var ctype = ec.CurrentMemberDefinition.Parent.PartialContainer;
5498                         Field field = new Field (ctype, string_dictionary_type,
5499                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
5500                                 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "switch$map", ec.Module.CounterSwitchTypes++), loc), null);
5501                         if (!field.Define ())
5502                                 return;
5503                         ctype.AddField (field);
5504
5505                         var init = new List<Expression> ();
5506                         int counter = -1;
5507                         labels = new Dictionary<long, SwitchLabel> (string_labels.Count);
5508                         string value = null;
5509
5510                         foreach (SwitchLabel sl in case_labels) {
5511
5512                                 if (sl.SectionStart)
5513                                         labels.Add (++counter, sl);
5514
5515                                 if (sl == case_default || sl == case_null)
5516                                         continue;
5517
5518                                 value = (string) sl.Converted.GetValue ();
5519                                 var init_args = new List<Expression> (2);
5520                                 init_args.Add (new StringLiteral (ec.BuiltinTypes, value, sl.Location));
5521
5522                                 sl.Converted = new IntConstant (ec.BuiltinTypes, counter, loc);
5523                                 init_args.Add (sl.Converted);
5524
5525                                 init.Add (new CollectionElementInitializer (init_args, loc));
5526                         }
5527         
5528                         Arguments args = new Arguments (1);
5529                         args.Add (new Argument (new IntConstant (ec.BuiltinTypes, init.Count, loc)));
5530                         Expression initializer = new NewInitialize (string_dictionary_type, args,
5531                                 new CollectionOrObjectInitializers (init, loc), loc);
5532
5533                         switch_cache_field = new FieldExpr (field, loc);
5534                         string_dictionary = new SimpleAssign (switch_cache_field, initializer.Resolve (ec));
5535                 }
5536
5537                 void DoEmitStringSwitch (EmitContext ec)
5538                 {
5539                         Label l_initialized = ec.DefineLabel ();
5540
5541                         //
5542                         // Skip initialization when value is null
5543                         //
5544                         value.EmitBranchable (ec, nullLabel, false);
5545
5546                         //
5547                         // Check if string dictionary is initialized and initialize
5548                         //
5549                         switch_cache_field.EmitBranchable (ec, l_initialized, true);
5550                         using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
5551                                 string_dictionary.EmitStatement (ec);
5552                         }
5553                         ec.MarkLabel (l_initialized);
5554
5555                         LocalTemporary string_switch_variable = new LocalTemporary (ec.BuiltinTypes.Int);
5556
5557                         ResolveContext rc = new ResolveContext (ec.MemberContext);
5558
5559                         if (switch_cache_field.Type.IsGeneric) {
5560                                 Arguments get_value_args = new Arguments (2);
5561                                 get_value_args.Add (new Argument (value));
5562                                 get_value_args.Add (new Argument (string_switch_variable, Argument.AType.Out));
5563                                 Expression get_item = new Invocation (new MemberAccess (switch_cache_field, "TryGetValue", loc), get_value_args).Resolve (rc);
5564                                 if (get_item == null)
5565                                         return;
5566
5567                                 //
5568                                 // A value was not found, go to default case
5569                                 //
5570                                 get_item.EmitBranchable (ec, defaultLabel, false);
5571                         } else {
5572                                 Arguments get_value_args = new Arguments (1);
5573                                 get_value_args.Add (new Argument (value));
5574
5575                                 Expression get_item = new ElementAccess (switch_cache_field, get_value_args, loc).Resolve (rc);
5576                                 if (get_item == null)
5577                                         return;
5578
5579                                 LocalTemporary get_item_object = new LocalTemporary (ec.BuiltinTypes.Object);
5580                                 get_item_object.EmitAssign (ec, get_item, true, false);
5581                                 ec.Emit (OpCodes.Brfalse, defaultLabel);
5582
5583                                 ExpressionStatement get_item_int = (ExpressionStatement) new SimpleAssign (string_switch_variable,
5584                                         new Cast (new TypeExpression (ec.BuiltinTypes.Int, loc), get_item_object, loc)).Resolve (rc);
5585
5586                                 get_item_int.EmitStatement (ec);
5587                                 get_item_object.Release (ec);
5588                         }
5589
5590                         EmitTableSwitch (ec, string_switch_variable);
5591                         string_switch_variable.Release (ec);
5592                 }
5593
5594                 //
5595                 // Emits switch using simple if/else comparison for small label count (4 + optional default)
5596                 //
5597                 void EmitShortSwitch (EmitContext ec)
5598                 {
5599                         MethodSpec equal_method = null;
5600                         if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.String) {
5601                                 equal_method = ec.Module.PredefinedMembers.StringEqual.Resolve (loc);
5602                         }
5603
5604                         if (equal_method != null) {
5605                                 value.EmitBranchable (ec, nullLabel, false);
5606                         }
5607
5608                         for (int i = 0; i < case_labels.Count; ++i) {
5609                                 var label = case_labels [i];
5610                                 if (label == case_default || label == case_null)
5611                                         continue;
5612
5613                                 var constant = label.Converted;
5614
5615                                 if (constant == null) {
5616                                         label.Label.EmitBranchable (ec, label.GetILLabel (ec), true);
5617                                         continue;
5618                                 }
5619
5620                                 if (equal_method != null) {
5621                                         value.Emit (ec);
5622                                         constant.Emit (ec);
5623
5624                                         var call = new CallEmitter ();
5625                                         call.EmitPredefined (ec, equal_method, new Arguments (0));
5626                                         ec.Emit (OpCodes.Brtrue, label.GetILLabel (ec));
5627                                         continue;
5628                                 }
5629
5630                                 if (constant.IsZeroInteger && constant.Type.BuiltinType != BuiltinTypeSpec.Type.Long && constant.Type.BuiltinType != BuiltinTypeSpec.Type.ULong) {
5631                                         value.EmitBranchable (ec, label.GetILLabel (ec), false);
5632                                         continue;
5633                                 }
5634
5635                                 value.Emit (ec);
5636                                 constant.Emit (ec);
5637                                 ec.Emit (OpCodes.Beq, label.GetILLabel (ec));
5638                         }
5639
5640                         ec.Emit (OpCodes.Br, defaultLabel);
5641                 }
5642
5643                 void EmitDispatch (EmitContext ec)
5644                 {
5645                         if (IsPatternMatching) {
5646                                 EmitShortSwitch (ec);
5647                                 return;
5648                         }
5649
5650                         if (value == null) {
5651                                 //
5652                                 // Constant switch, we've already done the work if there is only 1 label
5653                                 // referenced
5654                                 //
5655                                 int reachable = 0;
5656                                 foreach (var sl in case_labels) {
5657                                         if (sl.IsUnreachable)
5658                                                 continue;
5659
5660                                         if (reachable++ > 0) {
5661                                                 var constant = (Constant) new_expr;
5662                                                 var constant_label = FindLabel (constant) ?? case_default;
5663
5664                                                 ec.Emit (OpCodes.Br, constant_label.GetILLabel (ec));
5665                                                 break;
5666                                         }
5667                                 }
5668
5669                                 return;
5670                         }
5671
5672                         if (string_dictionary != null) {
5673                                 DoEmitStringSwitch (ec);
5674                         } else if (case_labels.Count < 4 || string_labels != null) {
5675                                 EmitShortSwitch (ec);
5676                         } else {
5677                                 EmitTableSwitch (ec, value);
5678                         }
5679                 }
5680
5681                 protected override void DoEmit (EmitContext ec)
5682                 {
5683                         //
5684                         // Setup the codegen context
5685                         //
5686                         Label old_end = ec.LoopEnd;
5687                         Switch old_switch = ec.Switch;
5688
5689                         ec.LoopEnd = ec.DefineLabel ();
5690                         ec.Switch = this;
5691
5692                         defaultLabel = case_default == null ? ec.LoopEnd : case_default.GetILLabel (ec);
5693                         nullLabel = case_null == null ? defaultLabel : case_null.GetILLabel (ec);
5694
5695                         if (value != null) {
5696                                 ec.Mark (loc);
5697
5698                                 var switch_expr = new_expr ?? Expr;
5699                                 if (IsNullable) {
5700                                         unwrap.EmitCheck (ec);
5701                                         ec.Emit (OpCodes.Brfalse, nullLabel);
5702                                         value.EmitAssign (ec, switch_expr, false, false);
5703                                 } else if (switch_expr != value) {
5704                                         value.EmitAssign (ec, switch_expr, false, false);
5705                                 }
5706
5707
5708                                 //
5709                                 // Next statement is compiler generated we don't need extra
5710                                 // nop when we can use the statement for sequence point
5711                                 //
5712                                 ec.Mark (block.StartLocation);
5713                                 block.IsCompilerGenerated = true;
5714                         } else {
5715                                 new_expr.EmitSideEffect (ec);
5716                         }
5717
5718                         block.Emit (ec);
5719
5720                         // Restore context state. 
5721                         ec.MarkLabel (ec.LoopEnd);
5722
5723                         //
5724                         // Restore the previous context
5725                         //
5726                         ec.LoopEnd = old_end;
5727                         ec.Switch = old_switch;
5728                 }
5729
5730                 protected override void CloneTo (CloneContext clonectx, Statement t)
5731                 {
5732                         Switch target = (Switch) t;
5733
5734                         target.Expr = Expr.Clone (clonectx);
5735                         target.Statement = target.block = (ExplicitBlock) block.Clone (clonectx);
5736                 }
5737                 
5738                 public override object Accept (StructuralVisitor visitor)
5739                 {
5740                         return visitor.Visit (this);
5741                 }
5742
5743                 public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
5744                 {
5745                         if (case_default == null && !(new_expr is Constant))
5746                                 return;
5747
5748                         if (end_reachable_das == null)
5749                                 end_reachable_das = new List<DefiniteAssignmentBitSet> ();
5750
5751                         end_reachable_das.Add (fc.DefiniteAssignment);
5752                 }
5753
5754                 public override void SetEndReachable ()
5755                 {
5756                         end_reachable = true;
5757                 }
5758         }
5759
5760         // A place where execution can restart in a state machine
5761         public abstract class ResumableStatement : Statement
5762         {
5763                 bool prepared;
5764                 protected Label resume_point;
5765
5766                 public Label PrepareForEmit (EmitContext ec)
5767                 {
5768                         if (!prepared) {
5769                                 prepared = true;
5770                                 resume_point = ec.DefineLabel ();
5771                         }
5772                         return resume_point;
5773                 }
5774
5775                 public virtual Label PrepareForDispose (EmitContext ec, Label end)
5776                 {
5777                         return end;
5778                 }
5779
5780                 public virtual void EmitForDispose (EmitContext ec, LocalBuilder pc, Label end, bool have_dispatcher)
5781                 {
5782                 }
5783         }
5784
5785         public abstract class TryFinallyBlock : ExceptionStatement
5786         {
5787                 protected Statement stmt;
5788                 Label dispose_try_block;
5789                 bool prepared_for_dispose, emitted_dispose;
5790                 Method finally_host;
5791
5792                 protected TryFinallyBlock (Statement stmt, Location loc)
5793                         : base (loc)
5794                 {
5795                         this.stmt = stmt;
5796                 }
5797
5798                 #region Properties
5799
5800                 public Statement Statement {
5801                         get {
5802                                 return stmt;
5803                         }
5804                 }
5805
5806                 #endregion
5807
5808                 protected abstract void EmitTryBody (EmitContext ec);
5809                 public abstract void EmitFinallyBody (EmitContext ec);
5810
5811                 public override Label PrepareForDispose (EmitContext ec, Label end)
5812                 {
5813                         if (!prepared_for_dispose) {
5814                                 prepared_for_dispose = true;
5815                                 dispose_try_block = ec.DefineLabel ();
5816                         }
5817                         return dispose_try_block;
5818                 }
5819
5820                 protected sealed override void DoEmit (EmitContext ec)
5821                 {
5822                         EmitTryBodyPrepare (ec);
5823                         EmitTryBody (ec);
5824
5825                         bool beginFinally = EmitBeginFinallyBlock (ec);
5826
5827                         Label start_finally = ec.DefineLabel ();
5828                         if (resume_points != null && beginFinally) {
5829                                 var state_machine = (StateMachineInitializer) ec.CurrentAnonymousMethod;
5830
5831                                 ec.Emit (OpCodes.Ldloc, state_machine.SkipFinally);
5832                                 ec.Emit (OpCodes.Brfalse_S, start_finally);
5833                                 ec.Emit (OpCodes.Endfinally);
5834                         }
5835
5836                         ec.MarkLabel (start_finally);
5837
5838                         if (finally_host != null) {
5839                                 finally_host.Define ();
5840                                 finally_host.PrepareEmit ();
5841                                 finally_host.Emit ();
5842
5843                                 // Now it's safe to add, to close it properly and emit sequence points
5844                                 finally_host.Parent.AddMember (finally_host);
5845
5846                                 var ce = new CallEmitter ();
5847                                 ce.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
5848                                 ce.EmitPredefined (ec, finally_host.Spec, new Arguments (0), true);
5849                         } else {
5850                                 EmitFinallyBody (ec);
5851                         }
5852
5853                         if (beginFinally)
5854                                 ec.EndExceptionBlock ();
5855                 }
5856
5857                 public override void EmitForDispose (EmitContext ec, LocalBuilder pc, Label end, bool have_dispatcher)
5858                 {
5859                         if (emitted_dispose)
5860                                 return;
5861
5862                         emitted_dispose = true;
5863
5864                         Label end_of_try = ec.DefineLabel ();
5865
5866                         // Ensure that the only way we can get into this code is through a dispatcher
5867                         if (have_dispatcher)
5868                                 ec.Emit (OpCodes.Br, end);
5869
5870                         ec.BeginExceptionBlock ();
5871
5872                         ec.MarkLabel (dispose_try_block);
5873
5874                         Label[] labels = null;
5875                         for (int i = 0; i < resume_points.Count; ++i) {
5876                                 ResumableStatement s = resume_points[i];
5877                                 Label ret = s.PrepareForDispose (ec, end_of_try);
5878                                 if (ret.Equals (end_of_try) && labels == null)
5879                                         continue;
5880                                 if (labels == null) {
5881                                         labels = new Label[resume_points.Count];
5882                                         for (int j = 0; j < i; ++j)
5883                                                 labels[j] = end_of_try;
5884                                 }
5885                                 labels[i] = ret;
5886                         }
5887
5888                         if (labels != null) {
5889                                 int j;
5890                                 for (j = 1; j < labels.Length; ++j)
5891                                         if (!labels[0].Equals (labels[j]))
5892                                                 break;
5893                                 bool emit_dispatcher = j < labels.Length;
5894
5895                                 if (emit_dispatcher) {
5896                                         ec.Emit (OpCodes.Ldloc, pc);
5897                                         ec.EmitInt (first_resume_pc);
5898                                         ec.Emit (OpCodes.Sub);
5899                                         ec.Emit (OpCodes.Switch, labels);
5900                                 }
5901
5902                                 foreach (ResumableStatement s in resume_points)
5903                                         s.EmitForDispose (ec, pc, end_of_try, emit_dispatcher);
5904                         }
5905
5906                         ec.MarkLabel (end_of_try);
5907
5908                         ec.BeginFinallyBlock ();
5909
5910                         if (finally_host != null) {
5911                                 var ce = new CallEmitter ();
5912                                 ce.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
5913                                 ce.EmitPredefined (ec, finally_host.Spec, new Arguments (0), true);
5914                         } else {
5915                                 EmitFinallyBody (ec);
5916                         }
5917
5918                         ec.EndExceptionBlock ();
5919                 }
5920
5921                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
5922                 {
5923                         var res = stmt.FlowAnalysis (fc);
5924                         parent_try_block = null;
5925                         return res;
5926                 }
5927
5928                 protected virtual bool EmitBeginFinallyBlock (EmitContext ec)
5929                 {
5930                         ec.BeginFinallyBlock ();
5931                         return true;
5932                 }
5933
5934                 public override Reachability MarkReachable (Reachability rc)
5935                 {
5936                         base.MarkReachable (rc);
5937                         return Statement.MarkReachable (rc);
5938                 }
5939
5940                 public override bool Resolve (BlockContext bc)
5941                 {
5942                         bool ok;
5943
5944                         parent_try_block = bc.CurrentTryBlock;
5945                         bc.CurrentTryBlock = this;
5946
5947                         if (stmt is TryCatch) {
5948                                 ok = stmt.Resolve (bc);
5949                         } else {
5950                                 using (bc.Set (ResolveContext.Options.TryScope)) {
5951                                         ok = stmt.Resolve (bc);
5952                                 }
5953                         }
5954
5955                         bc.CurrentTryBlock = parent_try_block;
5956
5957                         //
5958                         // Finally block inside iterator is called from MoveNext and
5959                         // Dispose methods that means we need to lift the block into
5960                         // newly created host method to emit the body only once. The
5961                         // original block then simply calls the newly generated method.
5962                         //
5963                         if (bc.CurrentIterator != null && !bc.IsInProbingMode) {
5964                                 var b = stmt as Block;
5965                                 if (b != null && b.Explicit.HasYield) {
5966                                         finally_host = bc.CurrentIterator.CreateFinallyHost (this);
5967                                 }
5968                         }
5969
5970                         return base.Resolve (bc) && ok;
5971                 }
5972         }
5973
5974         //
5975         // Base class for blocks using exception handling
5976         //
5977         public abstract class ExceptionStatement : ResumableStatement
5978         {
5979                 protected List<ResumableStatement> resume_points;
5980                 protected int first_resume_pc;
5981                 protected ExceptionStatement parent_try_block;
5982                 protected int first_catch_resume_pc = -1;
5983
5984                 protected ExceptionStatement (Location loc)
5985                 {
5986                         this.loc = loc;
5987                 }
5988
5989                 protected virtual void EmitTryBodyPrepare (EmitContext ec)
5990                 {
5991                         StateMachineInitializer state_machine = null;
5992                         if (resume_points != null) {
5993                                 state_machine = (StateMachineInitializer) ec.CurrentAnonymousMethod;
5994
5995                                 ec.EmitInt ((int) IteratorStorey.State.Running);
5996                                 ec.Emit (OpCodes.Stloc, state_machine.CurrentPC);
5997                         }
5998
5999                         //
6000                         // The resume points in catch section when this is try-catch-finally
6001                         //
6002                         if (IsRewrittenTryCatchFinally ()) {
6003                                 ec.BeginExceptionBlock ();
6004
6005                                 if (first_catch_resume_pc >= 0) {
6006
6007                                         ec.MarkLabel (resume_point);
6008
6009                                         // For normal control flow, we want to fall-through the Switch
6010                                         // So, we use CurrentPC rather than the $PC field, and initialize it to an outside value above
6011                                         ec.Emit (OpCodes.Ldloc, state_machine.CurrentPC);
6012                                         ec.EmitInt (first_resume_pc + first_catch_resume_pc);
6013                                         ec.Emit (OpCodes.Sub);
6014
6015                                         var labels = new Label [resume_points.Count - first_catch_resume_pc];
6016                                         for (int i = 0; i < labels.Length; ++i)
6017                                                 labels [i] = resume_points [i + first_catch_resume_pc].PrepareForEmit (ec);
6018                                         ec.Emit (OpCodes.Switch, labels);
6019                                 }
6020                         }
6021
6022                         ec.BeginExceptionBlock ();
6023
6024                         //
6025                         // The resume points for try section
6026                         //
6027                         if (resume_points != null && first_catch_resume_pc != 0) {
6028                                 if (first_catch_resume_pc < 0)
6029                                         ec.MarkLabel (resume_point);
6030
6031                                 // For normal control flow, we want to fall-through the Switch
6032                                 // So, we use CurrentPC rather than the $PC field, and initialize it to an outside value above
6033                                 ec.Emit (OpCodes.Ldloc, state_machine.CurrentPC);
6034                                 ec.EmitInt (first_resume_pc);
6035                                 ec.Emit (OpCodes.Sub);
6036
6037                                 var labels = new Label [first_catch_resume_pc > 0 ? first_catch_resume_pc : resume_points.Count];
6038                                 for (int i = 0; i < labels.Length; ++i)
6039                                         labels[i] = resume_points[i].PrepareForEmit (ec);
6040                                 ec.Emit (OpCodes.Switch, labels);
6041                         }
6042                 }
6043
6044                 bool IsRewrittenTryCatchFinally ()
6045                 {
6046                         var tf = this as TryFinally;
6047                         if (tf == null)
6048                                 return false;
6049
6050                         var tc = tf.Statement as TryCatch;
6051                         if (tc == null)
6052                                 return false;
6053
6054                         return tf.FinallyBlock.HasAwait || tc.HasClauseWithAwait;
6055                 }
6056
6057                 public int AddResumePoint (ResumableStatement stmt, int pc, StateMachineInitializer stateMachine, TryCatch catchBlock)
6058                 {
6059                         if (parent_try_block != null) {
6060                                 pc = parent_try_block.AddResumePoint (this, pc, stateMachine, catchBlock);
6061                         } else {
6062                                 pc = stateMachine.AddResumePoint (this);
6063                         }
6064
6065                         if (resume_points == null) {
6066                                 resume_points = new List<ResumableStatement> ();
6067                                 first_resume_pc = pc;
6068                         }
6069
6070                         if (pc != first_resume_pc + resume_points.Count)
6071                                 throw new InternalErrorException ("missed an intervening AddResumePoint?");
6072
6073                         var tf = this as TryFinally;
6074                         if (tf != null && tf.Statement == catchBlock && first_catch_resume_pc < 0) {
6075                                 first_catch_resume_pc = resume_points.Count;
6076                         }
6077
6078                         resume_points.Add (stmt);
6079                         return pc;
6080                 }
6081         }
6082
6083         public class Lock : TryFinallyBlock
6084         {
6085                 Expression expr;
6086                 TemporaryVariableReference expr_copy;
6087                 TemporaryVariableReference lock_taken;
6088                         
6089                 public Lock (Expression expr, Statement stmt, Location loc)
6090                         : base (stmt, loc)
6091                 {
6092                         this.expr = expr;
6093                 }
6094
6095                 public Expression Expr {
6096                         get {
6097                                 return this.expr;
6098                         }
6099                 }
6100
6101                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6102                 {
6103                         expr.FlowAnalysis (fc);
6104                         return base.DoFlowAnalysis (fc);
6105                 }
6106
6107                 public override bool Resolve (BlockContext ec)
6108                 {
6109                         expr = expr.Resolve (ec);
6110                         if (expr == null)
6111                                 return false;
6112
6113                         if (!TypeSpec.IsReferenceType (expr.Type) && expr.Type != InternalType.ErrorType) {
6114                                 ec.Report.Error (185, loc,
6115                                         "`{0}' is not a reference type as required by the lock statement",
6116                                         expr.Type.GetSignatureForError ());
6117                         }
6118
6119                         if (expr.Type.IsGenericParameter) {
6120                                 expr = Convert.ImplicitTypeParameterConversion (expr, (TypeParameterSpec)expr.Type, ec.BuiltinTypes.Object);
6121                         }
6122
6123                         VariableReference lv = expr as VariableReference;
6124                         bool locked;
6125                         if (lv != null) {
6126                                 locked = lv.IsLockedByStatement;
6127                                 lv.IsLockedByStatement = true;
6128                         } else {
6129                                 lv = null;
6130                                 locked = false;
6131                         }
6132
6133                         //
6134                         // Have to keep original lock value around to unlock same location
6135                         // in the case of original value has changed or is null
6136                         //
6137                         expr_copy = TemporaryVariableReference.Create (ec.BuiltinTypes.Object, ec.CurrentBlock, loc);
6138                         expr_copy.Resolve (ec);
6139
6140                         //
6141                         // Ensure Monitor methods are available
6142                         //
6143                         if (ResolvePredefinedMethods (ec) > 1) {
6144                                 lock_taken = TemporaryVariableReference.Create (ec.BuiltinTypes.Bool, ec.CurrentBlock, loc);
6145                                 lock_taken.Resolve (ec);
6146                         }
6147
6148                         using (ec.Set (ResolveContext.Options.LockScope)) {
6149                                 base.Resolve (ec);
6150                         }
6151
6152                         if (lv != null) {
6153                                 lv.IsLockedByStatement = locked;
6154                         }
6155
6156                         return true;
6157                 }
6158                 
6159                 protected override void EmitTryBodyPrepare (EmitContext ec)
6160                 {
6161                         expr_copy.EmitAssign (ec, expr);
6162
6163                         if (lock_taken != null) {
6164                                 //
6165                                 // Initialize ref variable
6166                                 //
6167                                 lock_taken.EmitAssign (ec, new BoolLiteral (ec.BuiltinTypes, false, loc));
6168                         } else {
6169                                 //
6170                                 // Monitor.Enter (expr_copy)
6171                                 //
6172                                 expr_copy.Emit (ec);
6173                                 ec.Emit (OpCodes.Call, ec.Module.PredefinedMembers.MonitorEnter.Get ());
6174                         }
6175
6176                         base.EmitTryBodyPrepare (ec);
6177                 }
6178
6179                 protected override void EmitTryBody (EmitContext ec)
6180                 {
6181                         //
6182                         // Monitor.Enter (expr_copy, ref lock_taken)
6183                         //
6184                         if (lock_taken != null) {
6185                                 expr_copy.Emit (ec);
6186                                 lock_taken.LocalInfo.CreateBuilder (ec);
6187                                 lock_taken.AddressOf (ec, AddressOp.Load);
6188                                 ec.Emit (OpCodes.Call, ec.Module.PredefinedMembers.MonitorEnter_v4.Get ());
6189                         }
6190
6191                         Statement.Emit (ec);
6192                 }
6193
6194                 public override void EmitFinallyBody (EmitContext ec)
6195                 {
6196                         //
6197                         // if (lock_taken) Monitor.Exit (expr_copy)
6198                         //
6199                         Label skip = ec.DefineLabel ();
6200
6201                         if (lock_taken != null) {
6202                                 lock_taken.Emit (ec);
6203                                 ec.Emit (OpCodes.Brfalse_S, skip);
6204                         }
6205
6206                         expr_copy.Emit (ec);
6207                         var m = ec.Module.PredefinedMembers.MonitorExit.Resolve (loc);
6208                         if (m != null)
6209                                 ec.Emit (OpCodes.Call, m);
6210
6211                         ec.MarkLabel (skip);
6212                 }
6213
6214                 int ResolvePredefinedMethods (ResolveContext rc)
6215                 {
6216                         // Try 4.0 Monitor.Enter (object, ref bool) overload first
6217                         var m = rc.Module.PredefinedMembers.MonitorEnter_v4.Get ();
6218                         if (m != null)
6219                                 return 4;
6220
6221                         m = rc.Module.PredefinedMembers.MonitorEnter.Get ();
6222                         if (m != null)
6223                                 return 1;
6224
6225                         rc.Module.PredefinedMembers.MonitorEnter_v4.Resolve (loc);
6226                         return 0;
6227                 }
6228
6229                 protected override void CloneTo (CloneContext clonectx, Statement t)
6230                 {
6231                         Lock target = (Lock) t;
6232
6233                         target.expr = expr.Clone (clonectx);
6234                         target.stmt = Statement.Clone (clonectx);
6235                 }
6236                 
6237                 public override object Accept (StructuralVisitor visitor)
6238                 {
6239                         return visitor.Visit (this);
6240                 }
6241
6242         }
6243
6244         public class Unchecked : Statement {
6245                 public Block Block;
6246                 
6247                 public Unchecked (Block b, Location loc)
6248                 {
6249                         Block = b;
6250                         b.Unchecked = true;
6251                         this.loc = loc;
6252                 }
6253
6254                 public override bool Resolve (BlockContext ec)
6255                 {
6256                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
6257                                 return Block.Resolve (ec);
6258                 }
6259                 
6260                 protected override void DoEmit (EmitContext ec)
6261                 {
6262                         using (ec.With (EmitContext.Options.CheckedScope, false))
6263                                 Block.Emit (ec);
6264                 }
6265
6266                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6267                 {
6268                         return Block.FlowAnalysis (fc);
6269                 }
6270
6271                 public override Reachability MarkReachable (Reachability rc)
6272                 {
6273                         base.MarkReachable (rc);
6274                         return Block.MarkReachable (rc);
6275                 }
6276
6277                 protected override void CloneTo (CloneContext clonectx, Statement t)
6278                 {
6279                         Unchecked target = (Unchecked) t;
6280
6281                         target.Block = clonectx.LookupBlock (Block);
6282                 }
6283                 
6284                 public override object Accept (StructuralVisitor visitor)
6285                 {
6286                         return visitor.Visit (this);
6287                 }
6288         }
6289
6290         public class Checked : Statement {
6291                 public Block Block;
6292                 
6293                 public Checked (Block b, Location loc)
6294                 {
6295                         Block = b;
6296                         b.Unchecked = false;
6297                         this.loc = loc;
6298                 }
6299
6300                 public override bool Resolve (BlockContext ec)
6301                 {
6302                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
6303                                 return Block.Resolve (ec);
6304                 }
6305
6306                 protected override void DoEmit (EmitContext ec)
6307                 {
6308                         using (ec.With (EmitContext.Options.CheckedScope, true))
6309                                 Block.Emit (ec);
6310                 }
6311
6312                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6313                 {
6314                         return Block.FlowAnalysis (fc);
6315                 }
6316
6317                 public override Reachability MarkReachable (Reachability rc)
6318                 {
6319                         base.MarkReachable (rc);
6320                         return Block.MarkReachable (rc);
6321                 }
6322
6323                 protected override void CloneTo (CloneContext clonectx, Statement t)
6324                 {
6325                         Checked target = (Checked) t;
6326
6327                         target.Block = clonectx.LookupBlock (Block);
6328                 }
6329                 
6330                 public override object Accept (StructuralVisitor visitor)
6331                 {
6332                         return visitor.Visit (this);
6333                 }
6334         }
6335
6336         public class Unsafe : Statement {
6337                 public Block Block;
6338
6339                 public Unsafe (Block b, Location loc)
6340                 {
6341                         Block = b;
6342                         Block.Unsafe = true;
6343                         this.loc = loc;
6344                 }
6345
6346                 public override bool Resolve (BlockContext ec)
6347                 {
6348                         if (ec.CurrentIterator != null)
6349                                 ec.Report.Error (1629, loc, "Unsafe code may not appear in iterators");
6350
6351                         using (ec.Set (ResolveContext.Options.UnsafeScope))
6352                                 return Block.Resolve (ec);
6353                 }
6354                 
6355                 protected override void DoEmit (EmitContext ec)
6356                 {
6357                         Block.Emit (ec);
6358                 }
6359
6360                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6361                 {
6362                         return Block.FlowAnalysis (fc);
6363                 }
6364
6365                 public override Reachability MarkReachable (Reachability rc)
6366                 {
6367                         base.MarkReachable (rc);
6368                         return Block.MarkReachable (rc);
6369                 }
6370
6371                 protected override void CloneTo (CloneContext clonectx, Statement t)
6372                 {
6373                         Unsafe target = (Unsafe) t;
6374
6375                         target.Block = clonectx.LookupBlock (Block);
6376                 }
6377                 
6378                 public override object Accept (StructuralVisitor visitor)
6379                 {
6380                         return visitor.Visit (this);
6381                 }
6382         }
6383
6384         // 
6385         // Fixed statement
6386         //
6387         public class Fixed : Statement
6388         {
6389                 abstract class Emitter : ShimExpression
6390                 {
6391                         protected LocalVariable vi;
6392
6393                         protected Emitter (Expression expr, LocalVariable li)
6394                                 : base (expr)
6395                         {
6396                                 vi = li;
6397                         }
6398
6399                         public abstract void EmitExit (EmitContext ec);
6400
6401                         public override void FlowAnalysis (FlowAnalysisContext fc)
6402                         {
6403                                 expr.FlowAnalysis (fc);
6404                         }
6405                 }
6406
6407                 sealed class ExpressionEmitter : Emitter {
6408                         public ExpressionEmitter (Expression converted, LocalVariable li)
6409                                 : base (converted, li)
6410                         {
6411                         }
6412
6413                         protected override Expression DoResolve (ResolveContext rc)
6414                         {
6415                                 throw new NotImplementedException ();
6416                         }
6417
6418                         public override void Emit (EmitContext ec) {
6419                                 //
6420                                 // Store pointer in pinned location
6421                                 //
6422                                 expr.Emit (ec);
6423                                 vi.EmitAssign (ec);
6424                         }
6425
6426                         public override void EmitExit (EmitContext ec)
6427                         {
6428                                 ec.EmitInt (0);
6429                                 ec.Emit (OpCodes.Conv_U);
6430                                 vi.EmitAssign (ec);
6431                         }
6432                 }
6433
6434                 class StringEmitter : Emitter
6435                 {
6436                         LocalVariable pinned_string;
6437
6438                         public StringEmitter (Expression expr, LocalVariable li)
6439                                 : base (expr, li)
6440                         {
6441                         }
6442
6443                         protected override Expression DoResolve (ResolveContext rc)
6444                         {
6445                                 pinned_string = new LocalVariable (vi.Block, "$pinned",
6446                                         LocalVariable.Flags.FixedVariable | LocalVariable.Flags.CompilerGenerated | LocalVariable.Flags.Used,
6447                                         vi.Location);
6448                                 pinned_string.Type = rc.BuiltinTypes.String;
6449                                 vi.IsFixed = false;
6450
6451                                 eclass = ExprClass.Variable;
6452                                 type = rc.BuiltinTypes.Int;
6453                                 return this;
6454                         }
6455
6456                         public override void Emit (EmitContext ec)
6457                         {
6458                                 pinned_string.CreateBuilder (ec);
6459
6460                                 expr.Emit (ec);
6461                                 pinned_string.EmitAssign (ec);
6462
6463                                 // TODO: Should use Binary::Add
6464                                 pinned_string.Emit (ec);
6465                                 ec.Emit (OpCodes.Conv_I);
6466
6467                                 var m = ec.Module.PredefinedMembers.RuntimeHelpersOffsetToStringData.Resolve (loc);
6468                                 if (m == null)
6469                                         return;
6470
6471                                 PropertyExpr pe = new PropertyExpr (m, pinned_string.Location);
6472                                 //pe.InstanceExpression = pinned_string;
6473                                 pe.Resolve (new ResolveContext (ec.MemberContext)).Emit (ec);
6474
6475                                 ec.Emit (OpCodes.Add);
6476                                 vi.EmitAssign (ec);
6477                         }
6478
6479                         public override void EmitExit (EmitContext ec)
6480                         {
6481                                 ec.EmitNull ();
6482                                 pinned_string.EmitAssign (ec);
6483                         }
6484                 }
6485
6486                 public class VariableDeclaration : BlockVariable
6487                 {
6488                         public VariableDeclaration (FullNamedExpression type, LocalVariable li)
6489                                 : base (type, li)
6490                         {
6491                         }
6492
6493                         protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
6494                         {
6495                                 if (!Variable.Type.IsPointer && li == Variable) {
6496                                         bc.Report.Error (209, TypeExpression.Location,
6497                                                 "The type of locals declared in a fixed statement must be a pointer type");
6498                                         return null;
6499                                 }
6500
6501                                 var res = initializer.Resolve (bc);
6502                                 if (res == null)
6503                                         return null;
6504
6505                                 //
6506                                 // Case 1: Array
6507                                 //
6508                                 var ac = res.Type as ArrayContainer;
6509                                 if (ac != null) {
6510                                         TypeSpec array_type = ac.Element;
6511
6512                                         //
6513                                         // Provided that array_type is unmanaged,
6514                                         //
6515                                         if (!TypeManager.VerifyUnmanaged (bc.Module, array_type, loc))
6516                                                 return null;
6517
6518                                         Expression res_init;
6519                                         if (ExpressionAnalyzer.IsInexpensiveLoad (res)) {
6520                                                 res_init = res;
6521                                         } else {
6522                                                 var expr_variable = LocalVariable.CreateCompilerGenerated (ac, bc.CurrentBlock, loc);
6523                                                 res_init = new CompilerAssign (expr_variable.CreateReferenceExpression (bc, loc), res, loc);
6524                                                 res = expr_variable.CreateReferenceExpression (bc, loc);
6525                                         }
6526
6527                                         //
6528                                         // and T* is implicitly convertible to the
6529                                         // pointer type given in the fixed statement.
6530                                         //
6531                                         ArrayPtr array_ptr = new ArrayPtr (res, array_type, loc);
6532
6533                                         Expression converted = Convert.ImplicitConversionRequired (bc, array_ptr.Resolve (bc), li.Type, loc);
6534                                         if (converted == null)
6535                                                 return null;
6536
6537                                         //
6538                                         // fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
6539                                         //
6540                                         converted = new Conditional (new BooleanExpression (new Binary (Binary.Operator.LogicalOr,
6541                                                 new Binary (Binary.Operator.Equality, res_init, new NullLiteral (loc)),
6542                                                 new Binary (Binary.Operator.Equality, new MemberAccess (res, "Length"), new IntConstant (bc.BuiltinTypes, 0, loc)))),
6543                                                         new NullLiteral (loc),
6544                                                         converted, loc);
6545
6546                                         converted = converted.Resolve (bc);
6547
6548                                         return new ExpressionEmitter (converted, li);
6549                                 }
6550
6551                                 //
6552                                 // Case 2: string
6553                                 //
6554                                 if (res.Type.BuiltinType == BuiltinTypeSpec.Type.String) {
6555                                         return new StringEmitter (res, li).Resolve (bc);
6556                                 }
6557
6558                                 // Case 3: fixed buffer
6559                                 if (res is FixedBufferPtr) {
6560                                         return new ExpressionEmitter (res, li);
6561                                 }
6562
6563                                 bool already_fixed = true;
6564
6565                                 //
6566                                 // Case 4: & object.
6567                                 //
6568                                 Unary u = res as Unary;
6569                                 if (u != null) {
6570                                         if (u.Oper == Unary.Operator.AddressOf) {
6571                                                 IVariableReference vr = u.Expr as IVariableReference;
6572                                                 if (vr == null || !vr.IsFixed) {
6573                                                         already_fixed = false;
6574                                                 }
6575                                         }
6576                                 } else if (initializer is Cast) {
6577                                         bc.Report.Error (254, initializer.Location, "The right hand side of a fixed statement assignment may not be a cast expression");
6578                                         return null;
6579                                 }
6580
6581                                 if (already_fixed) {
6582                                         bc.Report.Error (213, loc, "You cannot use the fixed statement to take the address of an already fixed expression");
6583                                 }
6584
6585                                 res = Convert.ImplicitConversionRequired (bc, res, li.Type, loc);
6586                                 return new ExpressionEmitter (res, li);
6587                         }
6588                 }
6589
6590
6591                 VariableDeclaration decl;
6592                 Statement statement;
6593                 bool has_ret;
6594
6595                 public Fixed (VariableDeclaration decl, Statement stmt, Location l)
6596                 {
6597                         this.decl = decl;
6598                         statement = stmt;
6599                         loc = l;
6600                 }
6601
6602                 #region Properties
6603
6604                 public Statement Statement {
6605                         get {
6606                                 return statement;
6607                         }
6608                 }
6609
6610                 public BlockVariable Variables {
6611                         get {
6612                                 return decl;
6613                         }
6614                 }
6615
6616                 #endregion
6617
6618                 public override bool Resolve (BlockContext bc)
6619                 {
6620                         using (bc.Set (ResolveContext.Options.FixedInitializerScope)) {
6621                                 if (!decl.Resolve (bc))
6622                                         return false;
6623                         }
6624
6625                         return statement.Resolve (bc);
6626                 }
6627
6628                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6629                 {
6630                         decl.FlowAnalysis (fc);
6631                         return statement.FlowAnalysis (fc);
6632                 }
6633                 
6634                 protected override void DoEmit (EmitContext ec)
6635                 {
6636                         decl.Variable.CreateBuilder (ec);
6637                         decl.Initializer.Emit (ec);
6638                         if (decl.Declarators != null) {
6639                                 foreach (var d in decl.Declarators) {
6640                                         d.Variable.CreateBuilder (ec);
6641                                         d.Initializer.Emit (ec);
6642                                 }
6643                         }
6644
6645                         statement.Emit (ec);
6646
6647                         if (has_ret)
6648                                 return;
6649
6650                         //
6651                         // Clear the pinned variable
6652                         //
6653                         ((Emitter) decl.Initializer).EmitExit (ec);
6654                         if (decl.Declarators != null) {
6655                                 foreach (var d in decl.Declarators) {
6656                                         ((Emitter)d.Initializer).EmitExit (ec);
6657                                 }
6658                         }
6659                 }
6660
6661                 public override Reachability MarkReachable (Reachability rc)
6662                 {
6663                         base.MarkReachable (rc);
6664
6665                         decl.MarkReachable (rc);
6666
6667                         rc = statement.MarkReachable (rc);
6668
6669                         // TODO: What if there is local exit?
6670                         has_ret = rc.IsUnreachable;
6671                         return rc;
6672                 }
6673
6674                 protected override void CloneTo (CloneContext clonectx, Statement t)
6675                 {
6676                         Fixed target = (Fixed) t;
6677
6678                         target.decl = (VariableDeclaration) decl.Clone (clonectx);
6679                         target.statement = statement.Clone (clonectx);
6680                 }
6681                 
6682                 public override object Accept (StructuralVisitor visitor)
6683                 {
6684                         return visitor.Visit (this);
6685                 }
6686         }
6687
6688         public class Catch : Statement
6689         {
6690                 class CatchVariableStore : Statement
6691                 {
6692                         readonly Catch ctch;
6693
6694                         public CatchVariableStore (Catch ctch)
6695                         {
6696                                 this.ctch = ctch;
6697                         }
6698
6699                         protected override void CloneTo (CloneContext clonectx, Statement target)
6700                         {
6701                         }
6702
6703                         protected override void DoEmit (EmitContext ec)
6704                         {
6705                                 // Emits catch variable debug information inside correct block
6706                                 ctch.EmitCatchVariableStore (ec);
6707                         }
6708
6709                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6710                         {
6711                                 return true;
6712                         }
6713                 }
6714
6715                 class FilterStatement : Statement
6716                 {
6717                         readonly Catch ctch;
6718
6719                         public FilterStatement (Catch ctch)
6720                         {
6721                                 this.ctch = ctch;
6722                         }
6723
6724                         protected override void CloneTo (CloneContext clonectx, Statement target)
6725                         {
6726                         }
6727
6728                         protected override void DoEmit (EmitContext ec)
6729                         {
6730                                 if (ctch.li != null) {
6731                                         if (ctch.hoisted_temp != null)
6732                                                 ctch.hoisted_temp.Emit (ec);
6733                                         else
6734                                                 ctch.li.Emit (ec);
6735
6736                                         if (!ctch.IsGeneral && ctch.type.Kind == MemberKind.TypeParameter)
6737                                                 ec.Emit (OpCodes.Box, ctch.type);
6738                                 }
6739
6740                                 var expr_start = ec.DefineLabel ();
6741                                 var end = ec.DefineLabel ();
6742
6743                                 ec.Emit (OpCodes.Brtrue_S, expr_start);
6744                                 ec.EmitInt (0);
6745                                 ec.Emit (OpCodes.Br, end);
6746                                 ec.MarkLabel (expr_start);
6747
6748                                 ctch.Filter.Emit (ec);
6749
6750                                 ec.MarkLabel (end);
6751                                 ec.Emit (OpCodes.Endfilter);
6752                                 ec.BeginFilterHandler ();
6753                                 ec.Emit (OpCodes.Pop);
6754                         }
6755
6756                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6757                         {
6758                                 ctch.Filter.FlowAnalysis (fc);
6759                                 return true;
6760                         }
6761
6762                         public override bool Resolve (BlockContext bc)
6763                         {
6764                                 ctch.Filter = ctch.Filter.Resolve (bc);
6765
6766                                 if (ctch.Filter != null) {
6767                                         if (ctch.Filter.ContainsEmitWithAwait ()) {
6768                                                 bc.Report.Error (7094, ctch.Filter.Location, "The `await' operator cannot be used in the filter expression of a catch clause");
6769                                         }
6770
6771                                         var c = ctch.Filter as Constant;
6772                                         if (c != null && !c.IsDefaultValue) {
6773                                                 bc.Report.Warning (7095, 1, ctch.Filter.Location, "Exception filter expression is a constant");
6774                                         }
6775                                 }
6776
6777                                 return true;
6778                         }
6779                 }
6780
6781                 ExplicitBlock block;
6782                 LocalVariable li;
6783                 FullNamedExpression type_expr;
6784                 CompilerAssign assign;
6785                 TypeSpec type;
6786                 LocalTemporary hoisted_temp;
6787
6788                 public Catch (ExplicitBlock block, Location loc)
6789                 {
6790                         this.block = block;
6791                         this.loc = loc;
6792                 }
6793
6794                 #region Properties
6795
6796                 public ExplicitBlock Block {
6797                         get {
6798                                 return block;
6799                         }
6800                 }
6801
6802                 public TypeSpec CatchType {
6803                         get {
6804                                 return type;
6805                         }
6806                 }
6807
6808                 public Expression Filter {
6809                         get; set;
6810                 }
6811
6812                 public bool IsGeneral {
6813                         get {
6814                                 return type_expr == null;
6815                         }
6816                 }
6817
6818                 public FullNamedExpression TypeExpression {
6819                         get {
6820                                 return type_expr;
6821                         }
6822                         set {
6823                                 type_expr = value;
6824                         }
6825                 }
6826
6827                 public LocalVariable Variable {
6828                         get {
6829                                 return li;
6830                         }
6831                         set {
6832                                 li = value;
6833                         }
6834                 }
6835
6836                 #endregion
6837
6838                 protected override void DoEmit (EmitContext ec)
6839                 {
6840                         if (Filter != null) {
6841                                 ec.BeginExceptionFilterBlock ();
6842                                 ec.Emit (OpCodes.Isinst, IsGeneral ? ec.BuiltinTypes.Object : CatchType);
6843
6844                                 if (Block.HasAwait) {
6845                                         Block.EmitScopeInitialization (ec);
6846                                 } else {
6847                                         Block.Emit (ec);
6848                                 }
6849
6850                                 return;
6851                         }
6852
6853                         if (IsGeneral)
6854                                 ec.BeginCatchBlock (ec.BuiltinTypes.Object);
6855                         else
6856                                 ec.BeginCatchBlock (CatchType);
6857
6858                         if (li == null)
6859                                 ec.Emit (OpCodes.Pop);
6860
6861                         if (Block.HasAwait) {
6862                                 if (li != null)
6863                                         EmitCatchVariableStore (ec);
6864                         } else {
6865                                 Block.Emit (ec);
6866                         }
6867                 }
6868
6869                 void EmitCatchVariableStore (EmitContext ec)
6870                 {
6871                         li.CreateBuilder (ec);
6872
6873                         //
6874                         // For hoisted catch variable we have to use a temporary local variable
6875                         // for captured variable initialization during storey setup because variable
6876                         // needs to be on the stack after storey instance for stfld operation
6877                         //
6878                         if (li.HoistedVariant != null) {
6879                                 hoisted_temp = new LocalTemporary (li.Type);
6880                                 hoisted_temp.Store (ec);
6881
6882                                 // switch to assignment from temporary variable and not from top of the stack
6883                                 assign.UpdateSource (hoisted_temp);
6884                         }
6885                 }
6886
6887                 public override bool Resolve (BlockContext bc)
6888                 {
6889                         using (bc.Set (ResolveContext.Options.CatchScope)) {
6890                                 if (type_expr == null) {
6891                                         if (CreateExceptionVariable (bc.Module.Compiler.BuiltinTypes.Object)) {
6892                                                 if (!block.HasAwait || Filter != null)
6893                                                         block.AddScopeStatement (new CatchVariableStore (this));
6894
6895                                                 Expression source = new EmptyExpression (li.Type);
6896                                                 assign = new CompilerAssign (new LocalVariableReference (li, Location.Null), source, Location.Null);
6897                                                 Block.AddScopeStatement (new StatementExpression (assign, Location.Null));
6898                                         }
6899                                 } else {
6900                                         type = type_expr.ResolveAsType (bc);
6901                                         if (type == null)
6902                                                 return false;
6903
6904                                         if (li == null)
6905                                                 CreateExceptionVariable (type);
6906
6907                                         if (type.BuiltinType != BuiltinTypeSpec.Type.Exception && !TypeSpec.IsBaseClass (type, bc.BuiltinTypes.Exception, false)) {
6908                                                 bc.Report.Error (155, loc, "The type caught or thrown must be derived from System.Exception");
6909                                         } else if (li != null) {
6910                                                 li.Type = type;
6911                                                 li.PrepareAssignmentAnalysis (bc);
6912
6913                                                 // source variable is at the top of the stack
6914                                                 Expression source = new EmptyExpression (li.Type);
6915                                                 if (li.Type.IsGenericParameter)
6916                                                         source = new UnboxCast (source, li.Type);
6917
6918                                                 if (!block.HasAwait || Filter != null)
6919                                                         block.AddScopeStatement (new CatchVariableStore (this));
6920
6921                                                 //
6922                                                 // Uses Location.Null to hide from symbol file
6923                                                 //
6924                                                 assign = new CompilerAssign (new LocalVariableReference (li, Location.Null), source, Location.Null);
6925                                                 Block.AddScopeStatement (new StatementExpression (assign, Location.Null));
6926                                         }
6927                                 }
6928
6929                                 if (Filter != null) {
6930                                         Block.AddScopeStatement (new FilterStatement (this));
6931                                 }
6932
6933                                 Block.SetCatchBlock ();
6934                                 return Block.Resolve (bc);
6935                         }
6936                 }
6937
6938                 bool CreateExceptionVariable (TypeSpec type)
6939                 {
6940                         if (!Block.HasAwait)
6941                                 return false;
6942
6943                         // TODO: Scan the block for rethrow expression
6944                         //if (!Block.HasRethrow)
6945                         //      return;
6946
6947                         li = LocalVariable.CreateCompilerGenerated (type, block, Location.Null);
6948                         return true;
6949                 }
6950
6951                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6952                 {
6953                         if (li != null && !li.IsCompilerGenerated) {
6954                                 fc.SetVariableAssigned (li.VariableInfo, true);
6955                         }
6956
6957                         return block.FlowAnalysis (fc);
6958                 }
6959
6960                 public override Reachability MarkReachable (Reachability rc)
6961                 {
6962                         base.MarkReachable (rc);
6963
6964                         var c = Filter as Constant;
6965                         if (c != null && c.IsDefaultValue)
6966                                 return Reachability.CreateUnreachable ();
6967
6968                         return block.MarkReachable (rc);
6969                 }
6970
6971                 protected override void CloneTo (CloneContext clonectx, Statement t)
6972                 {
6973                         Catch target = (Catch) t;
6974
6975                         if (type_expr != null)
6976                                 target.type_expr = (FullNamedExpression) type_expr.Clone (clonectx);
6977
6978                         if (Filter != null)
6979                                 target.Filter = Filter.Clone (clonectx);
6980
6981                         target.block = (ExplicitBlock) clonectx.LookupBlock (block);
6982                 }
6983         }
6984
6985         public class TryFinally : TryFinallyBlock
6986         {
6987                 ExplicitBlock fini;
6988                 List<DefiniteAssignmentBitSet> try_exit_dat;
6989                 List<Label> redirected_jumps;
6990                 Label? start_fin_label;
6991
6992                 public TryFinally (Statement stmt, ExplicitBlock fini, Location loc)
6993                          : base (stmt, loc)
6994                 {
6995                         this.fini = fini;
6996                 }
6997
6998                 public ExplicitBlock FinallyBlock {
6999                         get {
7000                                 return fini;
7001                         }
7002                 }
7003
7004                 public void RegisterForControlExitCheck (DefiniteAssignmentBitSet vector)
7005                 {
7006                         if (try_exit_dat == null)
7007                                 try_exit_dat = new List<DefiniteAssignmentBitSet> ();
7008
7009                         try_exit_dat.Add (vector);
7010                 }
7011
7012                 public override bool Resolve (BlockContext bc)
7013                 {
7014                         bool ok = base.Resolve (bc);
7015
7016                         fini.SetFinallyBlock ();
7017                         using (bc.Set (ResolveContext.Options.FinallyScope)) {
7018                                 ok &= fini.Resolve (bc);
7019                         }
7020
7021                         return ok;
7022                 }
7023
7024                 protected override void EmitTryBody (EmitContext ec)
7025                 {
7026                         if (fini.HasAwait) {
7027                                 if (ec.TryFinallyUnwind == null)
7028                                         ec.TryFinallyUnwind = new List<TryFinally> ();
7029
7030                                 ec.TryFinallyUnwind.Add (this);
7031                                 stmt.Emit (ec);
7032
7033                                 if (first_catch_resume_pc < 0 && stmt is TryCatch)
7034                                         ec.EndExceptionBlock ();
7035
7036                                 ec.TryFinallyUnwind.Remove (this);
7037
7038                                 if (start_fin_label != null)
7039                                         ec.MarkLabel (start_fin_label.Value);
7040
7041                                 return;
7042                         }
7043
7044                         stmt.Emit (ec);
7045                 }
7046
7047                 protected override bool EmitBeginFinallyBlock (EmitContext ec)
7048                 {
7049                         if (fini.HasAwait)
7050                                 return false;
7051
7052                         return base.EmitBeginFinallyBlock (ec);
7053                 }
7054
7055                 public override void EmitFinallyBody (EmitContext ec)
7056                 {
7057                         if (!fini.HasAwait) {
7058                                 fini.Emit (ec);
7059                                 return;
7060                         }
7061
7062                         //
7063                         // Emits catch block like
7064                         //
7065                         // catch (object temp) {
7066                         //      this.exception_field = temp;
7067                         // }
7068                         //
7069                         var type = ec.BuiltinTypes.Object;
7070                         ec.BeginCatchBlock (type);
7071
7072                         var temp = ec.GetTemporaryLocal (type);
7073                         ec.Emit (OpCodes.Stloc, temp);
7074
7075                         var exception_field = ec.GetTemporaryField (type);
7076                         exception_field.AutomaticallyReuse = false;
7077                         ec.EmitThis ();
7078                         ec.Emit (OpCodes.Ldloc, temp);
7079                         exception_field.EmitAssignFromStack (ec);
7080
7081                         ec.EndExceptionBlock ();
7082
7083                         ec.FreeTemporaryLocal (temp, type);
7084
7085                         fini.Emit (ec);
7086
7087                         //
7088                         // Emits exception rethrow
7089                         //
7090                         // if (this.exception_field != null)
7091                         //      throw this.exception_field;
7092                         //
7093                         exception_field.Emit (ec);
7094                         var skip_throw = ec.DefineLabel ();
7095                         ec.Emit (OpCodes.Brfalse_S, skip_throw);
7096                         exception_field.Emit (ec);
7097                         ec.Emit (OpCodes.Throw);
7098                         ec.MarkLabel (skip_throw);
7099
7100                         exception_field.PrepareCleanup (ec);
7101
7102                         EmitUnwindFinallyTable (ec);
7103                 }
7104
7105                 bool IsParentBlock (Block block)
7106                 {
7107                         for (Block b = fini; b != null; b = b.Parent) {
7108                                 if (b == block)
7109                                         return true;
7110                         }
7111
7112                         return false;
7113                 }
7114
7115                 public static Label EmitRedirectedJump (EmitContext ec, AsyncInitializer initializer, Label label, Block labelBlock)
7116                 {
7117                         int idx;
7118                         if (labelBlock != null) {
7119                                 for (idx = ec.TryFinallyUnwind.Count; idx != 0; --idx) {
7120                                         var fin = ec.TryFinallyUnwind [idx - 1];
7121                                         if (!fin.IsParentBlock (labelBlock))
7122                                                 break;
7123                                 }
7124                         } else {
7125                                 idx = 0;
7126                         }
7127
7128                         bool set_return_state = true;
7129
7130                         for (; idx < ec.TryFinallyUnwind.Count; ++idx) {
7131                                 var fin = ec.TryFinallyUnwind [idx];
7132                                 if (labelBlock != null && !fin.IsParentBlock (labelBlock))
7133                                         break;
7134
7135                                 fin.EmitRedirectedExit (ec, label, initializer, set_return_state);
7136                                 set_return_state = false;
7137
7138                                 if (fin.start_fin_label == null) {
7139                                         fin.start_fin_label = ec.DefineLabel ();
7140                                 }
7141
7142                                 label = fin.start_fin_label.Value;
7143                         }
7144
7145                         return label;
7146                 }
7147
7148                 public static Label EmitRedirectedReturn (EmitContext ec, AsyncInitializer initializer)
7149                 {
7150                         return EmitRedirectedJump (ec, initializer, initializer.BodyEnd, null);
7151                 }
7152
7153                 void EmitRedirectedExit (EmitContext ec, Label label, AsyncInitializer initializer, bool setReturnState)
7154                 {
7155                         if (redirected_jumps == null) {
7156                                 redirected_jumps = new List<Label> ();
7157
7158                                 // Add fallthrough label
7159                                 redirected_jumps.Add (ec.DefineLabel ());
7160
7161                                 if (setReturnState)
7162                                         initializer.HoistedReturnState = ec.GetTemporaryField (ec.Module.Compiler.BuiltinTypes.Int, true);
7163                         }
7164
7165                         int index = redirected_jumps.IndexOf (label);
7166                         if (index < 0) {
7167                                 redirected_jumps.Add (label);
7168                                 index = redirected_jumps.Count - 1;
7169                         }
7170
7171                         //
7172                         // Indicates we have captured exit jump
7173                         //
7174                         if (setReturnState) {
7175                                 var value = new IntConstant (initializer.HoistedReturnState.Type, index, Location.Null);
7176                                 initializer.HoistedReturnState.EmitAssign (ec, value, false, false);
7177                         }
7178                 }
7179
7180                 //
7181                 // Emits state table of jumps outside of try block and reload of return
7182                 // value when try block returns value
7183                 //
7184                 void EmitUnwindFinallyTable (EmitContext ec)
7185                 {
7186                         if (redirected_jumps == null)
7187                                 return;
7188
7189                         var initializer = (AsyncInitializer)ec.CurrentAnonymousMethod;
7190                         initializer.HoistedReturnState.EmitLoad (ec);
7191                         ec.Emit (OpCodes.Switch, redirected_jumps.ToArray ());
7192
7193                         // Mark fallthrough label
7194                         ec.MarkLabel (redirected_jumps [0]);
7195                 }
7196
7197                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
7198                 {
7199                         var da = fc.BranchDefiniteAssignment ();
7200
7201                         var tf = fc.TryFinally;
7202                         fc.TryFinally = this;
7203
7204                         var res_stmt = Statement.FlowAnalysis (fc);
7205
7206                         fc.TryFinally = tf;
7207
7208                         var try_da = fc.DefiniteAssignment;
7209                         fc.DefiniteAssignment = da;
7210
7211                         var res_fin = fini.FlowAnalysis (fc);
7212
7213                         if (try_exit_dat != null) {
7214                                 //
7215                                 // try block has global exit but we need to run definite assignment check
7216                                 // for parameter block out parameter after finally block because it's always
7217                                 // executed before exit
7218                                 //
7219                                 foreach (var try_da_part in try_exit_dat)
7220                                         fc.ParametersBlock.CheckControlExit (fc, fc.DefiniteAssignment | try_da_part);
7221
7222                                 try_exit_dat = null;
7223                         }
7224
7225                         fc.DefiniteAssignment |= try_da;
7226                         return res_stmt | res_fin;
7227                 }
7228
7229                 public override Reachability MarkReachable (Reachability rc)
7230                 {
7231                         //
7232                         // Mark finally block first for any exit statement in try block
7233                         // to know whether the code which follows finally is reachable
7234                         //
7235                         return fini.MarkReachable (rc) | base.MarkReachable (rc);
7236                 }
7237
7238                 protected override void CloneTo (CloneContext clonectx, Statement t)
7239                 {
7240                         TryFinally target = (TryFinally) t;
7241
7242                         target.stmt = stmt.Clone (clonectx);
7243                         if (fini != null)
7244                                 target.fini = (ExplicitBlock) clonectx.LookupBlock (fini);
7245                 }
7246                 
7247                 public override object Accept (StructuralVisitor visitor)
7248                 {
7249                         return visitor.Visit (this);
7250                 }
7251         }
7252
7253         public class TryCatch : ExceptionStatement
7254         {
7255                 public Block Block;
7256                 List<Catch> clauses;
7257                 readonly bool inside_try_finally;
7258                 List<Catch> catch_sm;
7259
7260                 public TryCatch (Block block, List<Catch> catch_clauses, Location l, bool inside_try_finally)
7261                         : base (l)
7262                 {
7263                         this.Block = block;
7264                         this.clauses = catch_clauses;
7265                         this.inside_try_finally = inside_try_finally;
7266                 }
7267
7268                 public List<Catch> Clauses {
7269                         get {
7270                                 return clauses;
7271                         }
7272                 }
7273
7274                 public bool HasClauseWithAwait {
7275                         get {
7276                                 return catch_sm != null;
7277                         }
7278                 }
7279
7280                 public bool IsTryCatchFinally {
7281                         get {
7282                                 return inside_try_finally;
7283                         }
7284                 }
7285
7286                 public override bool Resolve (BlockContext bc)
7287                 {
7288                         bool ok;
7289
7290                         using (bc.Set (ResolveContext.Options.TryScope)) {
7291
7292                                 parent_try_block = bc.CurrentTryBlock;
7293
7294                                 if (IsTryCatchFinally) {
7295                                         ok = Block.Resolve (bc);
7296                                 } else {
7297                                         using (bc.Set (ResolveContext.Options.TryWithCatchScope)) {
7298                                                 bc.CurrentTryBlock = this;
7299                                                 ok = Block.Resolve (bc);
7300                                                 bc.CurrentTryBlock = parent_try_block;
7301                                         }
7302                                 }
7303                         }
7304
7305                         var prev_catch = bc.CurrentTryCatch;
7306                         bc.CurrentTryCatch = this;
7307
7308                         for (int i = 0; i < clauses.Count; ++i) {
7309                                 var c = clauses[i];
7310
7311                                 ok &= c.Resolve (bc);
7312
7313                                 if (c.Block.HasAwait) {
7314                                         if (catch_sm == null)
7315                                                 catch_sm = new List<Catch> ();
7316
7317                                         catch_sm.Add (c);
7318                                 }
7319
7320                                 if (c.Filter != null)
7321                                         continue;
7322
7323                                 TypeSpec resolved_type = c.CatchType;
7324                                 if (resolved_type == null)
7325                                         continue;
7326
7327                                 for (int ii = 0; ii < clauses.Count; ++ii) {
7328                                         if (ii == i)
7329                                                 continue;
7330
7331                                         if (clauses[ii].Filter != null)
7332                                                 continue;
7333
7334                                         if (clauses[ii].IsGeneral) {
7335                                                 if (resolved_type.BuiltinType != BuiltinTypeSpec.Type.Exception)
7336                                                         continue;
7337
7338                                                 if (!bc.Module.DeclaringAssembly.WrapNonExceptionThrows)
7339                                                         continue;
7340
7341                                                 if (!bc.Module.PredefinedAttributes.RuntimeCompatibility.IsDefined)
7342                                                         continue;
7343
7344                                                 bc.Report.Warning (1058, 1, c.loc,
7345                                                         "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
7346
7347                                                 continue;
7348                                         }
7349
7350                                         if (ii >= i)
7351                                                 continue;
7352
7353                                         var ct = clauses[ii].CatchType;
7354                                         if (ct == null)
7355                                                 continue;
7356
7357                                         if (resolved_type == ct || TypeSpec.IsBaseClass (resolved_type, ct, true)) {
7358                                                 bc.Report.Error (160, c.loc,
7359                                                         "A previous catch clause already catches all exceptions of this or a super type `{0}'",
7360                                                         ct.GetSignatureForError ());
7361                                                 ok = false;
7362                                         }
7363                                 }
7364                         }
7365
7366                         bc.CurrentTryCatch = prev_catch;
7367
7368                         return base.Resolve (bc) && ok;
7369                 }
7370
7371                 protected sealed override void DoEmit (EmitContext ec)
7372                 {
7373                         if (!inside_try_finally)
7374                                 EmitTryBodyPrepare (ec);
7375
7376                         Block.Emit (ec);
7377
7378                         LocalBuilder state_variable = null;
7379                         foreach (Catch c in clauses) {
7380                                 c.Emit (ec);
7381
7382                                 if (catch_sm != null) {
7383                                         if (state_variable == null) {
7384                                                 //
7385                                                 // Cannot reuse temp variable because non-catch path assumes the value is 0
7386                                                 // which may not be true for reused local variable
7387                                                 //
7388                                                 state_variable = ec.DeclareLocal (ec.Module.Compiler.BuiltinTypes.Int, false);
7389                                         }
7390
7391                                         var index = catch_sm.IndexOf (c);
7392                                         if (index < 0)
7393                                                 continue;
7394
7395                                         ec.EmitInt (index + 1);
7396                                         ec.Emit (OpCodes.Stloc, state_variable);
7397                                 }
7398                         }
7399
7400                         if (state_variable == null) {
7401                                 if (!inside_try_finally)
7402                                         ec.EndExceptionBlock ();
7403                         } else {
7404                                 ec.EndExceptionBlock ();
7405
7406                                 ec.Emit (OpCodes.Ldloc, state_variable);
7407
7408                                 var labels = new Label [catch_sm.Count + 1];
7409                                 for (int i = 0; i < labels.Length; ++i) {
7410                                         labels [i] = ec.DefineLabel ();
7411                                 }
7412
7413                                 var end = ec.DefineLabel ();
7414                                 ec.Emit (OpCodes.Switch, labels);
7415
7416                                 // 0 value is default label
7417                                 ec.MarkLabel (labels [0]);
7418                                 ec.Emit (OpCodes.Br, end);
7419
7420                                 var atv = ec.AsyncThrowVariable;
7421                                 Catch c = null;
7422                                 for (int i = 0; i < catch_sm.Count; ++i) {
7423                                         if (c != null && c.Block.HasReachableClosingBrace)
7424                                                 ec.Emit (OpCodes.Br, end);
7425
7426                                         ec.MarkLabel (labels [i + 1]);
7427                                         c = catch_sm [i];
7428                                         ec.AsyncThrowVariable = c.Variable;
7429                                         c.Block.Emit (ec);
7430                                 }
7431                                 ec.AsyncThrowVariable = atv;
7432
7433                                 ec.MarkLabel (end);
7434                         }
7435                 }
7436
7437                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
7438                 {
7439                         var start_fc = fc.BranchDefiniteAssignment ();
7440                         var res = Block.FlowAnalysis (fc);
7441
7442                         DefiniteAssignmentBitSet try_fc = res ? null : fc.DefiniteAssignment;
7443
7444                         foreach (var c in clauses) {
7445                                 fc.BranchDefiniteAssignment (start_fc);
7446                                 if (!c.FlowAnalysis (fc)) {
7447                                         if (try_fc == null)
7448                                                 try_fc = fc.DefiniteAssignment;
7449                                         else
7450                                                 try_fc &= fc.DefiniteAssignment;
7451
7452                                         res = false;
7453                                 }
7454                         }
7455
7456                         fc.DefiniteAssignment = try_fc ?? start_fc;
7457                         parent_try_block = null;
7458                         return res;
7459                 }
7460
7461                 public override Reachability MarkReachable (Reachability rc)
7462                 {
7463                         if (rc.IsUnreachable)
7464                                 return rc;
7465
7466                         base.MarkReachable (rc);
7467
7468                         var tc_rc = Block.MarkReachable (rc);
7469
7470                         foreach (var c in clauses)
7471                                 tc_rc &= c.MarkReachable (rc);
7472
7473                         return tc_rc;
7474                 }
7475
7476                 protected override void CloneTo (CloneContext clonectx, Statement t)
7477                 {
7478                         TryCatch target = (TryCatch) t;
7479
7480                         target.Block = clonectx.LookupBlock (Block);
7481                         if (clauses != null){
7482                                 target.clauses = new List<Catch> ();
7483                                 foreach (Catch c in clauses)
7484                                         target.clauses.Add ((Catch) c.Clone (clonectx));
7485                         }
7486                 }
7487
7488                 public override object Accept (StructuralVisitor visitor)
7489                 {
7490                         return visitor.Visit (this);
7491                 }
7492         }
7493
7494         public class Using : TryFinallyBlock
7495         {
7496                 public class VariableDeclaration : BlockVariable
7497                 {
7498                         Statement dispose_call;
7499
7500                         public VariableDeclaration (FullNamedExpression type, LocalVariable li)
7501                                 : base (type, li)
7502                         {
7503                         }
7504
7505                         public VariableDeclaration (LocalVariable li, Location loc)
7506                                 : base (li)
7507                         {
7508                                 reachable = true;
7509                                 this.loc = loc;
7510                         }
7511
7512                         public VariableDeclaration (Expression expr)
7513                                 : base (null)
7514                         {
7515                                 loc = expr.Location;
7516                                 Initializer = expr;
7517                         }
7518
7519                         #region Properties
7520
7521                         public bool IsNested { get; private set; }
7522
7523                         #endregion
7524
7525                         public void EmitDispose (EmitContext ec)
7526                         {
7527                                 dispose_call.Emit (ec);
7528                         }
7529
7530                         public override bool Resolve (BlockContext bc)
7531                         {
7532                                 if (IsNested)
7533                                         return true;
7534
7535                                 return base.Resolve (bc, false);
7536                         }
7537
7538                         public Expression ResolveExpression (BlockContext bc)
7539                         {
7540                                 var e = Initializer.Resolve (bc);
7541                                 if (e == null)
7542                                         return null;
7543
7544                                 li = LocalVariable.CreateCompilerGenerated (e.Type, bc.CurrentBlock, loc);
7545                                 Initializer = ResolveInitializer (bc, Variable, e);
7546                                 return e;
7547                         }
7548
7549                         protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
7550                         {
7551                                 if (li.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
7552                                         initializer = initializer.Resolve (bc);
7553                                         if (initializer == null)
7554                                                 return null;
7555
7556                                         // Once there is dynamic used defer conversion to runtime even if we know it will never succeed
7557                                         Arguments args = new Arguments (1);
7558                                         args.Add (new Argument (initializer));
7559                                         initializer = new DynamicConversion (bc.BuiltinTypes.IDisposable, 0, args, initializer.Location).Resolve (bc);
7560                                         if (initializer == null)
7561                                                 return null;
7562
7563                                         var var = LocalVariable.CreateCompilerGenerated (initializer.Type, bc.CurrentBlock, loc);
7564                                         dispose_call = CreateDisposeCall (bc, var);
7565                                         dispose_call.Resolve (bc);
7566
7567                                         return base.ResolveInitializer (bc, li, new SimpleAssign (var.CreateReferenceExpression (bc, loc), initializer, loc));
7568                                 }
7569
7570                                 if (li == Variable) {
7571                                         CheckIDiposableConversion (bc, li, initializer);
7572                                         dispose_call = CreateDisposeCall (bc, li);
7573                                         dispose_call.Resolve (bc);
7574                                 }
7575
7576                                 return base.ResolveInitializer (bc, li, initializer);
7577                         }
7578
7579                         protected virtual void CheckIDiposableConversion (BlockContext bc, LocalVariable li, Expression initializer)
7580                         {
7581                                 var type = li.Type;
7582
7583                                 if (type.BuiltinType != BuiltinTypeSpec.Type.IDisposable && !CanConvertToIDisposable (bc, type)) {
7584                                         if (type.IsNullableType) {
7585                                                 // it's handled in CreateDisposeCall
7586                                                 return;
7587                                         }
7588
7589                                         if (type != InternalType.ErrorType) {
7590                                                 bc.Report.SymbolRelatedToPreviousError (type);
7591                                                 var loc = type_expr == null ? initializer.Location : type_expr.Location;
7592                                                 bc.Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
7593                                                         type.GetSignatureForError ());
7594                                         }
7595
7596                                         return;
7597                                 }
7598                         }
7599
7600                         static bool CanConvertToIDisposable (BlockContext bc, TypeSpec type)
7601                         {
7602                                 var target = bc.BuiltinTypes.IDisposable;
7603                                 var tp = type as TypeParameterSpec;
7604                                 if (tp != null)
7605                                         return Convert.ImplicitTypeParameterConversion (null, tp, target) != null;
7606
7607                                 return type.ImplementsInterface (target, false);
7608                         }
7609
7610                         protected virtual Statement CreateDisposeCall (BlockContext bc, LocalVariable lv)
7611                         {
7612                                 var lvr = lv.CreateReferenceExpression (bc, lv.Location);
7613                                 var type = lv.Type;
7614                                 var loc = lv.Location;
7615
7616                                 var idt = bc.BuiltinTypes.IDisposable;
7617                                 var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
7618
7619                                 var dispose_mg = MethodGroupExpr.CreatePredefined (m, idt, loc);
7620                                 dispose_mg.InstanceExpression = type.IsNullableType ?
7621                                         new Cast (new TypeExpression (idt, loc), lvr, loc).Resolve (bc) :
7622                                         lvr;
7623
7624                                 //
7625                                 // Hide it from symbol file via null location
7626                                 //
7627                                 Statement dispose = new StatementExpression (new Invocation (dispose_mg, null), Location.Null);
7628
7629                                 // Add conditional call when disposing possible null variable
7630                                 if (!TypeSpec.IsValueType (type) || type.IsNullableType)
7631                                         dispose = new If (new Binary (Binary.Operator.Inequality, lvr, new NullLiteral (loc)), dispose, dispose.loc);
7632
7633                                 return dispose;
7634                         }
7635
7636                         public void ResolveDeclaratorInitializer (BlockContext bc)
7637                         {
7638                                 Initializer = base.ResolveInitializer (bc, Variable, Initializer);
7639                         }
7640
7641                         public Statement RewriteUsingDeclarators (BlockContext bc, Statement stmt)
7642                         {
7643                                 for (int i = declarators.Count - 1; i >= 0; --i) {
7644                                         var d = declarators [i];
7645                                         var vd = new VariableDeclaration (d.Variable, d.Variable.Location);
7646                                         vd.Initializer = d.Initializer;
7647                                         vd.IsNested = true;
7648                                         vd.dispose_call = CreateDisposeCall (bc, d.Variable);
7649                                         vd.dispose_call.Resolve (bc);
7650
7651                                         stmt = new Using (vd, stmt, d.Variable.Location);
7652                                 }
7653
7654                                 declarators = null;
7655                                 return stmt;
7656                         }       
7657
7658                         public override object Accept (StructuralVisitor visitor)
7659                         {
7660                                 return visitor.Visit (this);
7661                         }       
7662                 }
7663
7664                 VariableDeclaration decl;
7665
7666                 public Using (VariableDeclaration decl, Statement stmt, Location loc)
7667                         : base (stmt, loc)
7668                 {
7669                         this.decl = decl;
7670                 }
7671
7672                 public Using (Expression expr, Statement stmt, Location loc)
7673                         : base (stmt, loc)
7674                 {
7675                         this.decl = new VariableDeclaration (expr);
7676                 }
7677
7678                 #region Properties
7679
7680                 public Expression Expr {
7681                         get {
7682                                 return decl.Variable == null ? decl.Initializer : null;
7683                         }
7684                 }
7685
7686                 public BlockVariable Variables {
7687                         get {
7688                                 return decl;
7689                         }
7690                 }
7691
7692                 #endregion
7693
7694                 public override void Emit (EmitContext ec)
7695                 {
7696                         //
7697                         // Don't emit sequence point it will be set on variable declaration
7698                         //
7699                         DoEmit (ec);
7700                 }
7701
7702                 protected override void EmitTryBodyPrepare (EmitContext ec)
7703                 {
7704                         decl.Emit (ec);
7705                         base.EmitTryBodyPrepare (ec);
7706                 }
7707
7708                 protected override void EmitTryBody (EmitContext ec)
7709                 {
7710                         stmt.Emit (ec);
7711                 }
7712
7713                 public override void EmitFinallyBody (EmitContext ec)
7714                 {
7715                         decl.EmitDispose (ec);
7716                 }
7717
7718                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
7719                 {
7720                         decl.FlowAnalysis (fc);
7721                         return stmt.FlowAnalysis (fc);
7722                 }
7723
7724                 public override Reachability MarkReachable (Reachability rc)
7725                 {
7726                         decl.MarkReachable (rc);
7727                         return base.MarkReachable (rc);
7728                 }
7729
7730                 public override bool Resolve (BlockContext ec)
7731                 {
7732                         VariableReference vr;
7733                         bool vr_locked = false;
7734
7735                         using (ec.Set (ResolveContext.Options.UsingInitializerScope)) {
7736                                 if (decl.Variable == null) {
7737                                         vr = decl.ResolveExpression (ec) as VariableReference;
7738                                         if (vr != null) {
7739                                                 vr_locked = vr.IsLockedByStatement;
7740                                                 vr.IsLockedByStatement = true;
7741                                         }
7742                                 } else {
7743                                         if (decl.IsNested) {
7744                                                 decl.ResolveDeclaratorInitializer (ec);
7745                                         } else {
7746                                                 if (!decl.Resolve (ec))
7747                                                         return false;
7748
7749                                                 if (decl.Declarators != null) {
7750                                                         stmt = decl.RewriteUsingDeclarators (ec, stmt);
7751                                                 }
7752                                         }
7753
7754                                         vr = null;
7755                                 }
7756                         }
7757
7758                         var ok = base.Resolve (ec);
7759
7760                         if (vr != null)
7761                                 vr.IsLockedByStatement = vr_locked;
7762
7763                         return ok;
7764                 }
7765
7766                 protected override void CloneTo (CloneContext clonectx, Statement t)
7767                 {
7768                         Using target = (Using) t;
7769
7770                         target.decl = (VariableDeclaration) decl.Clone (clonectx);
7771                         target.stmt = stmt.Clone (clonectx);
7772                 }
7773
7774                 public override object Accept (StructuralVisitor visitor)
7775                 {
7776                         return visitor.Visit (this);
7777                 }
7778         }
7779
7780         /// <summary>
7781         ///   Implementation of the foreach C# statement
7782         /// </summary>
7783         public class Foreach : LoopStatement
7784         {
7785                 abstract class IteratorStatement : Statement
7786                 {
7787                         protected readonly Foreach for_each;
7788
7789                         protected IteratorStatement (Foreach @foreach)
7790                         {
7791                                 this.for_each = @foreach;
7792                                 this.loc = @foreach.expr.Location;
7793                         }
7794
7795                         protected override void CloneTo (CloneContext clonectx, Statement target)
7796                         {
7797                                 throw new NotImplementedException ();
7798                         }
7799
7800                         public override void Emit (EmitContext ec)
7801                         {
7802                                 if (ec.EmitAccurateDebugInfo) {
7803                                         ec.Emit (OpCodes.Nop);
7804                                 }
7805
7806                                 base.Emit (ec);
7807                         }
7808
7809                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
7810                         {
7811                                 throw new NotImplementedException ();
7812                         }
7813                 }
7814
7815                 sealed class ArrayForeach : IteratorStatement
7816                 {
7817                         TemporaryVariableReference[] lengths;
7818                         Expression [] length_exprs;
7819                         StatementExpression[] counter;
7820                         TemporaryVariableReference[] variables;
7821
7822                         TemporaryVariableReference copy;
7823
7824                         public ArrayForeach (Foreach @foreach, int rank)
7825                                 : base (@foreach)
7826                         {
7827                                 counter = new StatementExpression[rank];
7828                                 variables = new TemporaryVariableReference[rank];
7829                                 length_exprs = new Expression [rank];
7830
7831                                 //
7832                                 // Only use temporary length variables when dealing with
7833                                 // multi-dimensional arrays
7834                                 //
7835                                 if (rank > 1)
7836                                         lengths = new TemporaryVariableReference [rank];
7837                         }
7838
7839                         public override bool Resolve (BlockContext ec)
7840                         {
7841                                 Block variables_block = for_each.variable.Block;
7842                                 copy = TemporaryVariableReference.Create (for_each.expr.Type, variables_block, loc);
7843                                 copy.Resolve (ec);
7844
7845                                 int rank = length_exprs.Length;
7846                                 Arguments list = new Arguments (rank);
7847                                 for (int i = 0; i < rank; i++) {
7848                                         var v = TemporaryVariableReference.Create (ec.BuiltinTypes.Int, variables_block, loc);
7849                                         variables[i] = v;
7850                                         counter[i] = new StatementExpression (new UnaryMutator (UnaryMutator.Mode.PostIncrement, v, Location.Null));
7851                                         counter[i].Resolve (ec);
7852
7853                                         if (rank == 1) {
7854                                                 length_exprs [i] = new MemberAccess (copy, "Length").Resolve (ec);
7855                                         } else {
7856                                                 lengths[i] = TemporaryVariableReference.Create (ec.BuiltinTypes.Int, variables_block, loc);
7857                                                 lengths[i].Resolve (ec);
7858
7859                                                 Arguments args = new Arguments (1);
7860                                                 args.Add (new Argument (new IntConstant (ec.BuiltinTypes, i, loc)));
7861                                                 length_exprs [i] = new Invocation (new MemberAccess (copy, "GetLength"), args).Resolve (ec);
7862                                         }
7863
7864                                         list.Add (new Argument (v));
7865                                 }
7866
7867                                 var access = new ElementAccess (copy, list, loc).Resolve (ec);
7868                                 if (access == null)
7869                                         return false;
7870
7871                                 TypeSpec var_type;
7872                                 if (for_each.type is VarExpr) {
7873                                         // Infer implicitly typed local variable from foreach array type
7874                                         var_type = access.Type;
7875                                 } else {
7876                                         var_type = for_each.type.ResolveAsType (ec);
7877
7878                                         if (var_type == null)
7879                                                 return false;
7880
7881                                         access = Convert.ExplicitConversion (ec, access, var_type, loc);
7882                                         if (access == null)
7883                                                 return false;
7884                                 }
7885
7886                                 for_each.variable.Type = var_type;
7887
7888                                 var prev_block = ec.CurrentBlock;
7889                                 ec.CurrentBlock = variables_block;
7890                                 var variable_ref = new LocalVariableReference (for_each.variable, loc).Resolve (ec);
7891                                 ec.CurrentBlock = prev_block;
7892
7893                                 if (variable_ref == null)
7894                                         return false;
7895
7896                                 for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, access, Location.Null), for_each.type.Location));
7897
7898                                 return for_each.body.Resolve (ec);
7899                         }
7900
7901                         protected override void DoEmit (EmitContext ec)
7902                         {
7903                                 copy.EmitAssign (ec, for_each.expr);
7904
7905                                 int rank = length_exprs.Length;
7906                                 Label[] test = new Label [rank];
7907                                 Label[] loop = new Label [rank];
7908
7909                                 for (int i = 0; i < rank; i++) {
7910                                         test [i] = ec.DefineLabel ();
7911                                         loop [i] = ec.DefineLabel ();
7912
7913                                         if (lengths != null)
7914                                                 lengths [i].EmitAssign (ec, length_exprs [i]);
7915                                 }
7916
7917                                 IntConstant zero = new IntConstant (ec.BuiltinTypes, 0, loc);
7918                                 for (int i = 0; i < rank; i++) {
7919                                         variables [i].EmitAssign (ec, zero);
7920
7921                                         ec.Emit (OpCodes.Br, test [i]);
7922                                         ec.MarkLabel (loop [i]);
7923                                 }
7924
7925                                 for_each.body.Emit (ec);
7926
7927                                 ec.MarkLabel (ec.LoopBegin);
7928                                 ec.Mark (for_each.expr.Location);
7929
7930                                 for (int i = rank - 1; i >= 0; i--){
7931                                         counter [i].Emit (ec);
7932
7933                                         ec.MarkLabel (test [i]);
7934                                         variables [i].Emit (ec);
7935
7936                                         if (lengths != null)
7937                                                 lengths [i].Emit (ec);
7938                                         else
7939                                                 length_exprs [i].Emit (ec);
7940
7941                                         ec.Emit (OpCodes.Blt, loop [i]);
7942                                 }
7943
7944                                 ec.MarkLabel (ec.LoopEnd);
7945                         }
7946                 }
7947
7948                 sealed class CollectionForeach : IteratorStatement, OverloadResolver.IErrorHandler
7949                 {
7950                         class RuntimeDispose : Using.VariableDeclaration
7951                         {
7952                                 public RuntimeDispose (LocalVariable lv, Location loc)
7953                                         : base (lv, loc)
7954                                 {
7955                                         reachable = true;
7956                                 }
7957
7958                                 protected override void CheckIDiposableConversion (BlockContext bc, LocalVariable li, Expression initializer)
7959                                 {
7960                                         // Defered to runtime check
7961                                 }
7962
7963                                 protected override Statement CreateDisposeCall (BlockContext bc, LocalVariable lv)
7964                                 {
7965                                         var idt = bc.BuiltinTypes.IDisposable;
7966
7967                                         //
7968                                         // Fabricates code like
7969                                         //
7970                                         // if ((temp = vr as IDisposable) != null) temp.Dispose ();
7971                                         //
7972
7973                                         var dispose_variable = LocalVariable.CreateCompilerGenerated (idt, bc.CurrentBlock, loc);
7974
7975                                         var idisaposable_test = new Binary (Binary.Operator.Inequality, new CompilerAssign (
7976                                                 dispose_variable.CreateReferenceExpression (bc, loc),
7977                                                 new As (lv.CreateReferenceExpression (bc, loc), new TypeExpression (dispose_variable.Type, loc), loc),
7978                                                 loc), new NullLiteral (loc));
7979
7980                                         var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
7981
7982                                         var dispose_mg = MethodGroupExpr.CreatePredefined (m, idt, loc);
7983                                         dispose_mg.InstanceExpression = dispose_variable.CreateReferenceExpression (bc, loc);
7984
7985                                         Statement dispose = new StatementExpression (new Invocation (dispose_mg, null));
7986                                         return new If (idisaposable_test, dispose, loc);
7987                                 }
7988                         }
7989
7990                         LocalVariable variable;
7991                         Expression expr;
7992                         Statement statement;
7993                         ExpressionStatement init;
7994                         TemporaryVariableReference enumerator_variable;
7995                         bool ambiguous_getenumerator_name;
7996
7997                         public CollectionForeach (Foreach @foreach, LocalVariable var, Expression expr)
7998                                 : base (@foreach)
7999                         {
8000                                 this.variable = var;
8001                                 this.expr = expr;
8002                         }
8003
8004                         void Error_WrongEnumerator (ResolveContext rc, MethodSpec enumerator)
8005                         {
8006                                 rc.Report.SymbolRelatedToPreviousError (enumerator);
8007                                 rc.Report.Error (202, loc,
8008                                         "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
8009                                                 enumerator.ReturnType.GetSignatureForError (), enumerator.GetSignatureForError ());
8010                         }
8011
8012                         MethodGroupExpr ResolveGetEnumerator (ResolveContext rc)
8013                         {
8014                                 //
8015                                 // Option 1: Try to match by name GetEnumerator first
8016                                 //
8017                                 var mexpr = Expression.MemberLookup (rc, false, expr.Type,
8018                                         "GetEnumerator", 0, Expression.MemberLookupRestrictions.ExactArity, loc);               // TODO: What if CS0229 ?
8019
8020                                 var mg = mexpr as MethodGroupExpr;
8021                                 if (mg != null) {
8022                                         mg.InstanceExpression = expr;
8023                                         Arguments args = new Arguments (0);
8024                                         mg = mg.OverloadResolve (rc, ref args, this, OverloadResolver.Restrictions.ProbingOnly | OverloadResolver.Restrictions.GetEnumeratorLookup);
8025
8026                                         // For ambiguous GetEnumerator name warning CS0278 was reported, but Option 2 could still apply
8027                                         if (ambiguous_getenumerator_name)
8028                                                 mg = null;
8029
8030                                         if (mg != null && !mg.BestCandidate.IsStatic && mg.BestCandidate.IsPublic) {
8031                                                 return mg;
8032                                         }
8033                                 }
8034
8035                                 //
8036                                 // Option 2: Try to match using IEnumerable interfaces with preference of generic version
8037                                 //
8038                                 var t = expr.Type;
8039                                 PredefinedMember<MethodSpec> iface_candidate = null;
8040                                 var ptypes = rc.Module.PredefinedTypes;
8041                                 var gen_ienumerable = ptypes.IEnumerableGeneric;
8042                                 if (!gen_ienumerable.Define ())
8043                                         gen_ienumerable = null;
8044
8045                                 var ifaces = t.Interfaces;
8046                                 if (ifaces != null) {
8047                                         foreach (var iface in ifaces) {
8048                                                 if (gen_ienumerable != null && iface.MemberDefinition == gen_ienumerable.TypeSpec.MemberDefinition) {
8049                                                         if (iface_candidate != null && iface_candidate != rc.Module.PredefinedMembers.IEnumerableGetEnumerator) {
8050                                                                 rc.Report.SymbolRelatedToPreviousError (expr.Type);
8051                                                                 rc.Report.Error (1640, loc,
8052                                                                         "foreach statement cannot operate on variables of type `{0}' because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
8053                                                                         expr.Type.GetSignatureForError (), gen_ienumerable.TypeSpec.GetSignatureForError ());
8054
8055                                                                 return null;
8056                                                         }
8057
8058                                                         // TODO: Cache this somehow
8059                                                         iface_candidate = new PredefinedMember<MethodSpec> (rc.Module, iface,
8060                                                                 MemberFilter.Method ("GetEnumerator", 0, ParametersCompiled.EmptyReadOnlyParameters, null));
8061
8062                                                         continue;
8063                                                 }
8064
8065                                                 if (iface.BuiltinType == BuiltinTypeSpec.Type.IEnumerable && iface_candidate == null) {
8066                                                         iface_candidate = rc.Module.PredefinedMembers.IEnumerableGetEnumerator;
8067                                                 }
8068                                         }
8069                                 }
8070
8071                                 if (iface_candidate == null) {
8072                                         if (expr.Type != InternalType.ErrorType) {
8073                                                 rc.Report.Error (1579, loc,
8074                                                         "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `{1}' or is inaccessible",
8075                                                         expr.Type.GetSignatureForError (), "GetEnumerator");
8076                                         }
8077
8078                                         return null;
8079                                 }
8080
8081                                 var method = iface_candidate.Resolve (loc);
8082                                 if (method == null)
8083                                         return null;
8084
8085                                 mg = MethodGroupExpr.CreatePredefined (method, expr.Type, loc);
8086                                 mg.InstanceExpression = expr;
8087                                 return mg;
8088                         }
8089
8090                         MethodGroupExpr ResolveMoveNext (ResolveContext rc, MethodSpec enumerator)
8091                         {
8092                                 var ms = MemberCache.FindMember (enumerator.ReturnType,
8093                                         MemberFilter.Method ("MoveNext", 0, ParametersCompiled.EmptyReadOnlyParameters, rc.BuiltinTypes.Bool),
8094                                         BindingRestriction.InstanceOnly) as MethodSpec;
8095
8096                                 if (ms == null || !ms.IsPublic) {
8097                                         Error_WrongEnumerator (rc, enumerator);
8098                                         return null;
8099                                 }
8100
8101                                 return MethodGroupExpr.CreatePredefined (ms, enumerator.ReturnType, expr.Location);
8102                         }
8103
8104                         PropertySpec ResolveCurrent (ResolveContext rc, MethodSpec enumerator)
8105                         {
8106                                 var ps = MemberCache.FindMember (enumerator.ReturnType,
8107                                         MemberFilter.Property ("Current", null),
8108                                         BindingRestriction.InstanceOnly) as PropertySpec;
8109
8110                                 if (ps == null || !ps.IsPublic) {
8111                                         Error_WrongEnumerator (rc, enumerator);
8112                                         return null;
8113                                 }
8114
8115                                 return ps;
8116                         }
8117
8118                         public override bool Resolve (BlockContext ec)
8119                         {
8120                                 bool is_dynamic = expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
8121
8122                                 if (is_dynamic) {
8123                                         expr = Convert.ImplicitConversionRequired (ec, expr, ec.BuiltinTypes.IEnumerable, loc);
8124                                 } else if (expr.Type.IsNullableType) {
8125                                         expr = new Nullable.UnwrapCall (expr).Resolve (ec);
8126                                 }
8127
8128                                 var get_enumerator_mg = ResolveGetEnumerator (ec);
8129                                 if (get_enumerator_mg == null) {
8130                                         return false;
8131                                 }
8132
8133                                 var get_enumerator = get_enumerator_mg.BestCandidate;
8134                                 enumerator_variable = TemporaryVariableReference.Create (get_enumerator.ReturnType, variable.Block, loc);
8135                                 enumerator_variable.Resolve (ec);
8136
8137                                 // Prepare bool MoveNext ()
8138                                 var move_next_mg = ResolveMoveNext (ec, get_enumerator);
8139                                 if (move_next_mg == null) {
8140                                         return false;
8141                                 }
8142
8143                                 move_next_mg.InstanceExpression = enumerator_variable;
8144
8145                                 // Prepare ~T~ Current { get; }
8146                                 var current_prop = ResolveCurrent (ec, get_enumerator);
8147                                 if (current_prop == null) {
8148                                         return false;
8149                                 }
8150
8151                                 var current_pe = new PropertyExpr (current_prop, loc) { InstanceExpression = enumerator_variable }.Resolve (ec);
8152                                 if (current_pe == null)
8153                                         return false;
8154
8155                                 VarExpr ve = for_each.type as VarExpr;
8156
8157                                 if (ve != null) {
8158                                         if (is_dynamic) {
8159                                                 // Source type is dynamic, set element type to dynamic too
8160                                                 variable.Type = ec.BuiltinTypes.Dynamic;
8161                                         } else {
8162                                                 // Infer implicitly typed local variable from foreach enumerable type
8163                                                 variable.Type = current_pe.Type;
8164                                         }
8165                                 } else {
8166                                         if (is_dynamic) {
8167                                                 // Explicit cast of dynamic collection elements has to be done at runtime
8168                                                 current_pe = EmptyCast.Create (current_pe, ec.BuiltinTypes.Dynamic);
8169                                         }
8170
8171                                         variable.Type = for_each.type.ResolveAsType (ec);
8172
8173                                         if (variable.Type == null)
8174                                                 return false;
8175
8176                                         current_pe = Convert.ExplicitConversion (ec, current_pe, variable.Type, loc);
8177                                         if (current_pe == null)
8178                                                 return false;
8179                                 }
8180
8181                                 var prev_block = ec.CurrentBlock;
8182                                 ec.CurrentBlock = for_each.variable.Block;
8183                                 var variable_ref = new LocalVariableReference (variable, loc).Resolve (ec);
8184                                 ec.CurrentBlock = prev_block;
8185                                 if (variable_ref == null)
8186                                         return false;
8187
8188                                 for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, current_pe, Location.Null), for_each.type.Location));
8189
8190                                 var init = new Invocation.Predefined (get_enumerator_mg, null);
8191
8192                                 statement = new While (new BooleanExpression (new Invocation (move_next_mg, null)),
8193                                          for_each.body, Location.Null);
8194
8195                                 var enum_type = enumerator_variable.Type;
8196
8197                                 //
8198                                 // Add Dispose method call when enumerator can be IDisposable
8199                                 //
8200                                 if (!enum_type.ImplementsInterface (ec.BuiltinTypes.IDisposable, false)) {
8201                                         if (!enum_type.IsSealed && !TypeSpec.IsValueType (enum_type)) {
8202                                                 //
8203                                                 // Runtime Dispose check
8204                                                 //
8205                                                 var vd = new RuntimeDispose (enumerator_variable.LocalInfo, Location.Null);
8206                                                 vd.Initializer = init;
8207                                                 statement = new Using (vd, statement, Location.Null);
8208                                         } else {
8209                                                 //
8210                                                 // No Dispose call needed
8211                                                 //
8212                                                 this.init = new SimpleAssign (enumerator_variable, init, Location.Null);
8213                                                 this.init.Resolve (ec);
8214                                         }
8215                                 } else {
8216                                         //
8217                                         // Static Dispose check
8218                                         //
8219                                         var vd = new Using.VariableDeclaration (enumerator_variable.LocalInfo, Location.Null);
8220                                         vd.Initializer = init;
8221                                         statement = new Using (vd, statement, Location.Null);
8222                                 }
8223
8224                                 return statement.Resolve (ec);
8225                         }
8226
8227                         protected override void DoEmit (EmitContext ec)
8228                         {
8229                                 enumerator_variable.LocalInfo.CreateBuilder (ec);
8230
8231                                 if (init != null)
8232                                         init.EmitStatement (ec);
8233
8234                                 statement.Emit (ec);
8235                         }
8236
8237                         #region IErrorHandler Members
8238
8239                         bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
8240                         {
8241                                 ec.Report.SymbolRelatedToPreviousError (best);
8242                                 ec.Report.Warning (278, 2, expr.Location,
8243                                         "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
8244                                         expr.Type.GetSignatureForError (), "enumerable",
8245                                         best.GetSignatureForError (), ambiguous.GetSignatureForError ());
8246
8247                                 ambiguous_getenumerator_name = true;
8248                                 return true;
8249                         }
8250
8251                         bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
8252                         {
8253                                 return false;
8254                         }
8255
8256                         bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
8257                         {
8258                                 return false;
8259                         }
8260
8261                         bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
8262                         {
8263                                 return false;
8264                         }
8265
8266                         #endregion
8267                 }
8268
8269                 Expression type;
8270                 LocalVariable variable;
8271                 Expression expr;
8272                 Block body;
8273
8274                 public Foreach (Expression type, LocalVariable var, Expression expr, Statement stmt, Block body, Location l)
8275                         : base (stmt)
8276                 {
8277                         this.type = type;
8278                         this.variable = var;
8279                         this.expr = expr;
8280                         this.body = body;
8281                         loc = l;
8282                 }
8283
8284                 public Expression Expr {
8285                         get { return expr; }
8286                 }
8287
8288                 public Expression TypeExpression {
8289                         get { return type; }
8290                 }
8291
8292                 public LocalVariable Variable {
8293                         get { return variable; }
8294                 }
8295
8296                 public override Reachability MarkReachable (Reachability rc)
8297                 {
8298                         base.MarkReachable (rc);
8299
8300                         body.MarkReachable (rc);
8301
8302                         return rc;
8303                 }
8304
8305                 public override bool Resolve (BlockContext ec)
8306                 {
8307                         expr = expr.Resolve (ec);
8308                         if (expr == null)
8309                                 return false;
8310
8311                         if (expr.IsNull) {
8312                                 ec.Report.Error (186, loc, "Use of null is not valid in this context");
8313                                 return false;
8314                         }
8315
8316                         body.AddStatement (Statement);
8317
8318                         if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.String) {
8319                                 Statement = new ArrayForeach (this, 1);
8320                         } else if (expr.Type is ArrayContainer) {
8321                                 Statement = new ArrayForeach (this, ((ArrayContainer) expr.Type).Rank);
8322                         } else {
8323                                 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
8324                                         ec.Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
8325                                                 expr.ExprClassName);
8326                                         return false;
8327                                 }
8328
8329                                 Statement = new CollectionForeach (this, variable, expr);
8330                         }
8331
8332                         return base.Resolve (ec);
8333                 }
8334
8335                 protected override void DoEmit (EmitContext ec)
8336                 {
8337                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
8338                         ec.LoopBegin = ec.DefineLabel ();
8339                         ec.LoopEnd = ec.DefineLabel ();
8340
8341                         if (!(Statement is Block))
8342                                 ec.BeginCompilerScope (variable.Block.Explicit.GetDebugSymbolScopeIndex ());
8343
8344                         variable.CreateBuilder (ec);
8345
8346                         Statement.Emit (ec);
8347
8348                         if (!(Statement is Block))
8349                                 ec.EndScope ();
8350
8351                         ec.LoopBegin = old_begin;
8352                         ec.LoopEnd = old_end;
8353                 }
8354
8355                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
8356                 {
8357                         expr.FlowAnalysis (fc);
8358
8359                         var da = fc.BranchDefiniteAssignment ();
8360                         body.FlowAnalysis (fc);
8361                         fc.DefiniteAssignment = da;
8362                         return false;
8363                 }
8364
8365                 protected override void CloneTo (CloneContext clonectx, Statement t)
8366                 {
8367                         Foreach target = (Foreach) t;
8368
8369                         target.type = type.Clone (clonectx);
8370                         target.expr = expr.Clone (clonectx);
8371                         target.body = (Block) body.Clone (clonectx);
8372                         target.Statement = Statement.Clone (clonectx);
8373                 }
8374                 
8375                 public override object Accept (StructuralVisitor visitor)
8376                 {
8377                         return visitor.Visit (this);
8378                 }
8379         }
8380
8381         class SentinelStatement: Statement
8382         {
8383                 protected override void CloneTo (CloneContext clonectx, Statement target)
8384                 {
8385                 }
8386
8387                 protected override void DoEmit (EmitContext ec)
8388                 {
8389                         var l = ec.DefineLabel ();
8390                         ec.MarkLabel (l);
8391                         ec.Emit (OpCodes.Br_S, l);
8392                 }
8393
8394                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
8395                 {
8396                         throw new NotImplementedException ();
8397                 }
8398         }
8399 }