2002-10-21 Miguel de Icaza <miguel@ximian.com>
[mono.git] / mcs / mcs / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@gnome.org)
7 //
8 // (C) 2001, 2002 Ximian, Inc.
9 //
10
11 using System;
12 using System.Text;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
16
17 namespace Mono.CSharp {
18
19         using System.Collections;
20         
21         public abstract class Statement {
22                 public Location loc;
23                 
24                 ///
25                 /// Resolves the statement, true means that all sub-statements
26                 /// did resolve ok.
27                 //
28                 public virtual bool Resolve (EmitContext ec)
29                 {
30                         return true;
31                 }
32                 
33                 /// <summary>
34                 ///   Return value indicates whether all code paths emitted return.
35                 /// </summary>
36                 protected abstract bool DoEmit (EmitContext ec);
37
38                 /// <summary>
39                 ///   Return value indicates whether all code paths emitted return.
40                 /// </summary>
41                 public virtual bool Emit (EmitContext ec)
42                 {
43                         ec.Mark (loc);
44                         Report.Debug (8, "MARK", this, loc);
45                         return DoEmit (ec);
46                 }
47                 
48                 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
49                 {
50                         e = e.Resolve (ec);
51                         if (e == null)
52                                 return null;
53                         
54                         if (e.Type != TypeManager.bool_type){
55                                 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
56                                                                 new Location (-1));
57                         }
58
59                         if (e == null){
60                                 Report.Error (
61                                         31, loc, "Can not convert the expression to a boolean");
62                         }
63
64                         ec.Mark (loc);
65
66                         return e;
67                 }
68                 
69                 /// <remarks>
70                 ///    Encapsulates the emission of a boolean test and jumping to a
71                 ///    destination.
72                 ///
73                 ///    This will emit the bool expression in `bool_expr' and if
74                 ///    `target_is_for_true' is true, then the code will generate a 
75                 ///    brtrue to the target.   Otherwise a brfalse. 
76                 /// </remarks>
77                 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
78                                                        Label target, bool target_is_for_true)
79                 {
80                         ILGenerator ig = ec.ig;
81                         
82                         bool invert = false;
83                         if (bool_expr is Unary){
84                                 Unary u = (Unary) bool_expr;
85                                 
86                                 if (u.Oper == Unary.Operator.LogicalNot){
87                                         invert = true;
88
89                                         u.EmitLogicalNot (ec);
90                                 }
91                         } else if (bool_expr is Binary){
92                                 Binary b = (Binary) bool_expr;
93
94                                 if (b.EmitBranchable (ec, target, target_is_for_true))
95                                         return;
96                         }
97
98                         if (!invert)
99                                 bool_expr.Emit (ec);
100
101                         if (target_is_for_true){
102                                 if (invert)
103                                         ig.Emit (OpCodes.Brfalse, target);
104                                 else
105                                         ig.Emit (OpCodes.Brtrue, target);
106                         } else {
107                                 if (invert)
108                                         ig.Emit (OpCodes.Brtrue, target);
109                                 else
110                                         ig.Emit (OpCodes.Brfalse, target);
111                         }
112                 }
113
114                 public static void Warning_DeadCodeFound (Location loc)
115                 {
116                         Report.Warning (162, loc, "Unreachable code detected");
117                 }
118         }
119
120         public class EmptyStatement : Statement {
121                 public override bool Resolve (EmitContext ec)
122                 {
123                         return true;
124                 }
125                 
126                 protected override bool DoEmit (EmitContext ec)
127                 {
128                         return false;
129                 }
130         }
131         
132         public class If : Statement {
133                 Expression expr;
134                 public Statement TrueStatement;
135                 public Statement FalseStatement;
136                 
137                 public If (Expression expr, Statement trueStatement, Location l)
138                 {
139                         this.expr = expr;
140                         TrueStatement = trueStatement;
141                         loc = l;
142                 }
143
144                 public If (Expression expr,
145                            Statement trueStatement,
146                            Statement falseStatement,
147                            Location l)
148                 {
149                         this.expr = expr;
150                         TrueStatement = trueStatement;
151                         FalseStatement = falseStatement;
152                         loc = l;
153                 }
154
155                 public override bool Resolve (EmitContext ec)
156                 {
157                         Report.Debug (1, "START IF BLOCK", loc);
158
159                         expr = ResolveBoolean (ec, expr, loc);
160                         if (expr == null){
161                                 return false;
162                         }
163                         
164                         ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
165                         
166                         if (!TrueStatement.Resolve (ec)) {
167                                 ec.KillFlowBranching ();
168                                 return false;
169                         }
170
171                         ec.CurrentBranching.CreateSibling ();
172
173                         if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
174                                 ec.KillFlowBranching ();
175                                 return false;
176                         }
177                                         
178                         ec.EndFlowBranching ();
179
180                         Report.Debug (1, "END IF BLOCK", loc);
181
182                         return true;
183                 }
184                 
185                 protected override bool DoEmit (EmitContext ec)
186                 {
187                         ILGenerator ig = ec.ig;
188                         Label false_target = ig.DefineLabel ();
189                         Label end;
190                         bool is_true_ret, is_false_ret;
191
192                         //
193                         // Dead code elimination
194                         //
195                         if (expr is BoolConstant){
196                                 bool take = ((BoolConstant) expr).Value;
197
198                                 if (take){
199                                         if (FalseStatement != null){
200                                                 Warning_DeadCodeFound (FalseStatement.loc);
201                                         }
202                                         return TrueStatement.Emit (ec);
203                                 } else {
204                                         Warning_DeadCodeFound (TrueStatement.loc);
205                                         if (FalseStatement != null)
206                                                 return FalseStatement.Emit (ec);
207                                 }
208                         }
209                         
210                         EmitBoolExpression (ec, expr, false_target, false);
211
212                         is_true_ret = TrueStatement.Emit (ec);
213                         is_false_ret = is_true_ret;
214
215                         if (FalseStatement != null){
216                                 bool branch_emitted = false;
217                                 
218                                 end = ig.DefineLabel ();
219                                 if (!is_true_ret){
220                                         ig.Emit (OpCodes.Br, end);
221                                         branch_emitted = true;
222                                 }
223
224                                 ig.MarkLabel (false_target);
225                                 is_false_ret = FalseStatement.Emit (ec);
226
227                                 if (branch_emitted)
228                                         ig.MarkLabel (end);
229                         } else {
230                                 ig.MarkLabel (false_target);
231                                 is_false_ret = false;
232                         }
233
234                         return is_true_ret && is_false_ret;
235                 }
236         }
237
238         public class Do : Statement {
239                 public Expression expr;
240                 public readonly Statement  EmbeddedStatement;
241                 bool infinite, may_return;
242                 
243                 public Do (Statement statement, Expression boolExpr, Location l)
244                 {
245                         expr = boolExpr;
246                         EmbeddedStatement = statement;
247                         loc = l;
248                 }
249
250                 public override bool Resolve (EmitContext ec)
251                 {
252                         bool ok = true;
253
254                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
255
256                         if (!EmbeddedStatement.Resolve (ec))
257                                 ok = false;
258
259                         expr = ResolveBoolean (ec, expr, loc);
260                         if (expr == null)
261                                 ok = false;
262                         else if (expr is BoolConstant){
263                                 bool res = ((BoolConstant) expr).Value;
264
265                                 if (res)
266                                         infinite = true;
267                         }
268
269                         ec.CurrentBranching.Infinite = infinite;
270                         FlowReturns returns = ec.EndFlowBranching ();
271                         may_return = returns != FlowReturns.NEVER;
272
273                         return ok;
274                 }
275                 
276                 protected override bool DoEmit (EmitContext ec)
277                 {
278                         ILGenerator ig = ec.ig;
279                         Label loop = ig.DefineLabel ();
280                         Label old_begin = ec.LoopBegin;
281                         Label old_end = ec.LoopEnd;
282                         bool  old_inloop = ec.InLoop;
283                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
284                         
285                         ec.LoopBegin = ig.DefineLabel ();
286                         ec.LoopEnd = ig.DefineLabel ();
287                         ec.InLoop = true;
288                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
289                                 
290                         ig.MarkLabel (loop);
291                         EmbeddedStatement.Emit (ec);
292                         ig.MarkLabel (ec.LoopBegin);
293
294                         //
295                         // Dead code elimination
296                         //
297                         if (expr is BoolConstant){
298                                 bool res = ((BoolConstant) expr).Value;
299
300                                 if (res)
301                                         ec.ig.Emit (OpCodes.Br, loop); 
302                         } else
303                                 EmitBoolExpression (ec, expr, loop, true);
304                         
305                         ig.MarkLabel (ec.LoopEnd);
306
307                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
308                         ec.LoopBegin = old_begin;
309                         ec.LoopEnd = old_end;
310                         ec.InLoop = old_inloop;
311
312                         if (infinite)
313                                 return may_return == false;
314                         else
315                                 return false;
316                 }
317         }
318
319         public class While : Statement {
320                 public Expression expr;
321                 public readonly Statement Statement;
322                 bool may_return, empty, infinite;
323                 
324                 public While (Expression boolExpr, Statement statement, Location l)
325                 {
326                         this.expr = boolExpr;
327                         Statement = statement;
328                         loc = l;
329                 }
330
331                 public override bool Resolve (EmitContext ec)
332                 {
333                         bool ok = true;
334
335                         expr = ResolveBoolean (ec, expr, loc);
336                         if (expr == null)
337                                 return false;
338
339                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
340
341                         //
342                         // Inform whether we are infinite or not
343                         //
344                         if (expr is BoolConstant){
345                                 BoolConstant bc = (BoolConstant) expr;
346
347                                 if (bc.Value == false){
348                                         Warning_DeadCodeFound (Statement.loc);
349                                         empty = true;
350                                 } else
351                                         infinite = true;
352                         } else {
353                                 //
354                                 // We are not infinite, so the loop may or may not be executed.
355                                 //
356                                 ec.CurrentBranching.CreateSibling ();
357                         }
358
359                         if (!Statement.Resolve (ec))
360                                 ok = false;
361
362                         if (empty)
363                                 ec.KillFlowBranching ();
364                         else {
365                                 ec.CurrentBranching.Infinite = infinite;
366                                 FlowReturns returns = ec.EndFlowBranching ();
367                                 may_return = returns != FlowReturns.NEVER;
368                         }
369
370                         return ok;
371                 }
372                 
373                 protected override bool DoEmit (EmitContext ec)
374                 {
375                         if (empty)
376                                 return false;
377
378                         ILGenerator ig = ec.ig;
379                         Label old_begin = ec.LoopBegin;
380                         Label old_end = ec.LoopEnd;
381                         bool old_inloop = ec.InLoop;
382                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
383                         bool ret;
384                         
385                         ec.LoopBegin = ig.DefineLabel ();
386                         ec.LoopEnd = ig.DefineLabel ();
387                         ec.InLoop = true;
388                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
389
390                         //
391                         // Inform whether we are infinite or not
392                         //
393                         if (expr is BoolConstant){
394                                 BoolConstant bc = (BoolConstant) expr;
395
396                                 ig.MarkLabel (ec.LoopBegin);
397                                 Statement.Emit (ec);
398                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
399                                         
400                                 //
401                                 // Inform that we are infinite (ie, `we return'), only
402                                 // if we do not `break' inside the code.
403                                 //
404                                 ret = may_return == false;
405                                 ig.MarkLabel (ec.LoopEnd);
406                         } else {
407                                 Label while_loop = ig.DefineLabel ();
408
409                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
410                                 ig.MarkLabel (while_loop);
411
412                                 Statement.Emit (ec);
413                         
414                                 ig.MarkLabel (ec.LoopBegin);
415
416                                 EmitBoolExpression (ec, expr, while_loop, true);
417                                 ig.MarkLabel (ec.LoopEnd);
418
419                                 ret = false;
420                         }       
421
422                         ec.LoopBegin = old_begin;
423                         ec.LoopEnd = old_end;
424                         ec.InLoop = old_inloop;
425                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
426
427                         return ret;
428                 }
429         }
430
431         public class For : Statement {
432                 Expression Test;
433                 readonly Statement InitStatement;
434                 readonly Statement Increment;
435                 readonly Statement Statement;
436                 bool may_return, infinite, empty;
437                 
438                 public For (Statement initStatement,
439                             Expression test,
440                             Statement increment,
441                             Statement statement,
442                             Location l)
443                 {
444                         InitStatement = initStatement;
445                         Test = test;
446                         Increment = increment;
447                         Statement = statement;
448                         loc = l;
449                 }
450
451                 public override bool Resolve (EmitContext ec)
452                 {
453                         bool ok = true;
454
455                         if (InitStatement != null){
456                                 if (!InitStatement.Resolve (ec))
457                                         ok = false;
458                         }
459
460                         if (Test != null){
461                                 Test = ResolveBoolean (ec, Test, loc);
462                                 if (Test == null)
463                                         ok = false;
464                                 else if (Test is BoolConstant){
465                                         BoolConstant bc = (BoolConstant) Test;
466
467                                         if (bc.Value == false){
468                                                 Warning_DeadCodeFound (Statement.loc);
469                                                 empty = true;
470                                         } else
471                                                 infinite = true;
472                                 }
473                         } else
474                                 infinite = true;
475
476                         if (Increment != null){
477                                 if (!Increment.Resolve (ec))
478                                         ok = false;
479                         }
480
481                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
482                         if (!infinite)
483                                 ec.CurrentBranching.CreateSibling ();
484
485                         if (!Statement.Resolve (ec))
486                                 ok = false;
487
488                         if (empty)
489                                 ec.KillFlowBranching ();
490                         else {
491                                 ec.CurrentBranching.Infinite = infinite;
492                                 FlowReturns returns = ec.EndFlowBranching ();
493                                 may_return = returns != FlowReturns.NEVER;
494                         }
495
496                         return ok;
497                 }
498                 
499                 protected override bool DoEmit (EmitContext ec)
500                 {
501                         if (empty)
502                                 return false;
503
504                         ILGenerator ig = ec.ig;
505                         Label old_begin = ec.LoopBegin;
506                         Label old_end = ec.LoopEnd;
507                         bool old_inloop = ec.InLoop;
508                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
509                         Label loop = ig.DefineLabel ();
510                         Label test = ig.DefineLabel ();
511                         
512                         if (InitStatement != null)
513                                 if (! (InitStatement is EmptyStatement))
514                                         InitStatement.Emit (ec);
515
516                         ec.LoopBegin = ig.DefineLabel ();
517                         ec.LoopEnd = ig.DefineLabel ();
518                         ec.InLoop = true;
519                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
520
521                         ig.Emit (OpCodes.Br, test);
522                         ig.MarkLabel (loop);
523                         Statement.Emit (ec);
524
525                         ig.MarkLabel (ec.LoopBegin);
526                         if (!(Increment is EmptyStatement))
527                                 Increment.Emit (ec);
528
529                         ig.MarkLabel (test);
530                         //
531                         // If test is null, there is no test, and we are just
532                         // an infinite loop
533                         //
534                         if (Test != null)
535                                 EmitBoolExpression (ec, Test, loop, true);
536                         else
537                                 ig.Emit (OpCodes.Br, loop);
538                         ig.MarkLabel (ec.LoopEnd);
539
540                         ec.LoopBegin = old_begin;
541                         ec.LoopEnd = old_end;
542                         ec.InLoop = old_inloop;
543                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
544                         
545                         //
546                         // Inform whether we are infinite or not
547                         //
548                         if (Test != null){
549                                 if (Test is BoolConstant){
550                                         BoolConstant bc = (BoolConstant) Test;
551
552                                         if (bc.Value)
553                                                 return may_return == false;
554                                 }
555                                 return false;
556                         } else
557                                 return may_return == false;
558                 }
559         }
560         
561         public class StatementExpression : Statement {
562                 Expression expr;
563                 
564                 public StatementExpression (ExpressionStatement expr, Location l)
565                 {
566                         this.expr = expr;
567                         loc = l;
568                 }
569
570                 public override bool Resolve (EmitContext ec)
571                 {
572                         expr = (Expression) expr.Resolve (ec);
573                         return expr != null;
574                 }
575                 
576                 protected override bool DoEmit (EmitContext ec)
577                 {
578                         ILGenerator ig = ec.ig;
579                         
580                         if (expr is ExpressionStatement)
581                                 ((ExpressionStatement) expr).EmitStatement (ec);
582                         else {
583                                 expr.Emit (ec);
584                                 ig.Emit (OpCodes.Pop);
585                         }
586
587                         return false;
588                 }
589
590                 public override string ToString ()
591                 {
592                         return "StatementExpression (" + expr + ")";
593                 }
594         }
595
596         /// <summary>
597         ///   Implements the return statement
598         /// </summary>
599         public class Return : Statement {
600                 public Expression Expr;
601                 
602                 public Return (Expression expr, Location l)
603                 {
604                         Expr = expr;
605                         loc = l;
606                 }
607
608                 public override bool Resolve (EmitContext ec)
609                 {
610                         if (Expr != null){
611                                 Expr = Expr.Resolve (ec);
612                                 if (Expr == null)
613                                         return false;
614                         }
615
616                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
617
618                         if (ec.CurrentBranching.InTryBlock ())
619                                 ec.CurrentBranching.AddFinallyVector (vector);
620                         else
621                                 vector.CheckOutParameters (ec.CurrentBranching);
622
623                         vector.Returns = FlowReturns.ALWAYS;
624                         vector.Breaks = FlowReturns.ALWAYS;
625                         return true;
626                 }
627                 
628                 protected override bool DoEmit (EmitContext ec)
629                 {
630                         if (ec.InFinally){
631                                 Report.Error (157,loc,"Control can not leave the body of the finally block");
632                                 return false;
633                         }
634                         
635                         if (ec.ReturnType == null){
636                                 if (Expr != null){
637                                         Report.Error (127, loc, "Return with a value not allowed here");
638                                         return true;
639                                 }
640                         } else {
641                                 if (Expr == null){
642                                         Report.Error (126, loc, "An object of type `" +
643                                                       TypeManager.CSharpName (ec.ReturnType) + "' is " +
644                                                       "expected for the return statement");
645                                         return true;
646                                 }
647
648                                 if (Expr.Type != ec.ReturnType)
649                                         Expr = Expression.ConvertImplicitRequired (
650                                                 ec, Expr, ec.ReturnType, loc);
651
652                                 if (Expr == null)
653                                         return true;
654
655                                 Expr.Emit (ec);
656
657                                 if (ec.InTry || ec.InCatch)
658                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
659                         }
660
661                         if (ec.InTry || ec.InCatch) {
662                                 if (!ec.HasReturnLabel) {
663                                         ec.ReturnLabel = ec.ig.DefineLabel ();
664                                         ec.HasReturnLabel = true;
665                                 }
666                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
667                         } else
668                                 ec.ig.Emit (OpCodes.Ret);
669
670                         return true; 
671                 }
672         }
673
674         public class Goto : Statement {
675                 string target;
676                 Block block;
677                 LabeledStatement label;
678                 
679                 public override bool Resolve (EmitContext ec)
680                 {
681                         label = block.LookupLabel (target);
682                         if (label == null){
683                                 Report.Error (
684                                         159, loc,
685                                         "No such label `" + target + "' in this scope");
686                                 return false;
687                         }
688
689                         // If this is a forward goto.
690                         if (!label.IsDefined)
691                                 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
692
693                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
694
695                         return true;
696                 }
697                 
698                 public Goto (Block parent_block, string label, Location l)
699                 {
700                         block = parent_block;
701                         loc = l;
702                         target = label;
703                 }
704
705                 public string Target {
706                         get {
707                                 return target;
708                         }
709                 }
710
711                 protected override bool DoEmit (EmitContext ec)
712                 {
713                         Label l = label.LabelTarget (ec);
714                         ec.ig.Emit (OpCodes.Br, l);
715                         
716                         return false;
717                 }
718         }
719
720         public class LabeledStatement : Statement {
721                 public readonly Location Location;
722                 string label_name;
723                 bool defined;
724                 bool referenced;
725                 Label label;
726
727                 ArrayList vectors;
728                 
729                 public LabeledStatement (string label_name, Location l)
730                 {
731                         this.label_name = label_name;
732                         this.Location = l;
733                 }
734
735                 public Label LabelTarget (EmitContext ec)
736                 {
737                         if (defined)
738                                 return label;
739                         label = ec.ig.DefineLabel ();
740                         defined = true;
741
742                         return label;
743                 }
744
745                 public bool IsDefined {
746                         get {
747                                 return defined;
748                         }
749                 }
750
751                 public bool HasBeenReferenced {
752                         get {
753                                 return referenced;
754                         }
755                 }
756
757                 public void AddUsageVector (FlowBranching.UsageVector vector)
758                 {
759                         if (vectors == null)
760                                 vectors = new ArrayList ();
761
762                         vectors.Add (vector.Clone ());
763                 }
764
765                 public override bool Resolve (EmitContext ec)
766                 {
767                         if (vectors != null)
768                                 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
769                         else {
770                                 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
771                                 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
772                         }
773
774                         referenced = true;
775
776                         return true;
777                 }
778
779                 protected override bool DoEmit (EmitContext ec)
780                 {
781                         LabelTarget (ec);
782                         ec.ig.MarkLabel (label);
783
784                         return false;
785                 }
786         }
787         
788
789         /// <summary>
790         ///   `goto default' statement
791         /// </summary>
792         public class GotoDefault : Statement {
793                 
794                 public GotoDefault (Location l)
795                 {
796                         loc = l;
797                 }
798
799                 public override bool Resolve (EmitContext ec)
800                 {
801                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
802                         return true;
803                 }
804
805                 protected override bool DoEmit (EmitContext ec)
806                 {
807                         if (ec.Switch == null){
808                                 Report.Error (153, loc, "goto default is only valid in a switch statement");
809                                 return false;
810                         }
811
812                         if (!ec.Switch.GotDefault){
813                                 Report.Error (159, loc, "No default target on switch statement");
814                                 return false;
815                         }
816                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
817                         return false;
818                 }
819         }
820
821         /// <summary>
822         ///   `goto case' statement
823         /// </summary>
824         public class GotoCase : Statement {
825                 Expression expr;
826                 Label label;
827                 
828                 public GotoCase (Expression e, Location l)
829                 {
830                         expr = e;
831                         loc = l;
832                 }
833
834                 public override bool Resolve (EmitContext ec)
835                 {
836                         if (ec.Switch == null){
837                                 Report.Error (153, loc, "goto case is only valid in a switch statement");
838                                 return false;
839                         }
840
841                         expr = expr.Resolve (ec);
842                         if (expr == null)
843                                 return false;
844
845                         if (!(expr is Constant)){
846                                 Report.Error (159, loc, "Target expression for goto case is not constant");
847                                 return false;
848                         }
849
850                         object val = Expression.ConvertIntLiteral (
851                                 (Constant) expr, ec.Switch.SwitchType, loc);
852
853                         if (val == null)
854                                 return false;
855                                         
856                         SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
857
858                         if (sl == null){
859                                 Report.Error (
860                                         159, loc,
861                                         "No such label 'case " + val + "': for the goto case");
862                         }
863
864                         label = sl.ILLabelCode;
865
866                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
867                         return true;
868                 }
869
870                 protected override bool DoEmit (EmitContext ec)
871                 {
872                         ec.ig.Emit (OpCodes.Br, label);
873                         return true;
874                 }
875         }
876         
877         public class Throw : Statement {
878                 Expression expr;
879                 
880                 public Throw (Expression expr, Location l)
881                 {
882                         this.expr = expr;
883                         loc = l;
884                 }
885
886                 public override bool Resolve (EmitContext ec)
887                 {
888                         if (expr != null){
889                                 expr = expr.Resolve (ec);
890                                 if (expr == null)
891                                         return false;
892
893                                 ExprClass eclass = expr.eclass;
894
895                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
896                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
897                                         expr.Error118 ("value, variable, property or indexer access ");
898                                         return false;
899                                 }
900
901                                 Type t = expr.Type;
902                                 
903                                 if ((t != TypeManager.exception_type) &&
904                                     !t.IsSubclassOf (TypeManager.exception_type) &&
905                                     !(expr is NullLiteral)) {
906                                         Report.Error (155, loc,
907                                                       "The type caught or thrown must be derived " +
908                                                       "from System.Exception");
909                                         return false;
910                                 }
911                         }
912
913                         ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
914                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
915                         return true;
916                 }
917                         
918                 protected override bool DoEmit (EmitContext ec)
919                 {
920                         if (expr == null){
921                                 if (ec.InCatch)
922                                         ec.ig.Emit (OpCodes.Rethrow);
923                                 else {
924                                         Report.Error (
925                                                 156, loc,
926                                                 "A throw statement with no argument is only " +
927                                                 "allowed in a catch clause");
928                                 }
929                                 return false;
930                         }
931
932                         expr.Emit (ec);
933
934                         ec.ig.Emit (OpCodes.Throw);
935
936                         return true;
937                 }
938         }
939
940         public class Break : Statement {
941                 
942                 public Break (Location l)
943                 {
944                         loc = l;
945                 }
946
947                 public override bool Resolve (EmitContext ec)
948                 {
949                         ec.CurrentBranching.MayLeaveLoop = true;
950                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
951                         return true;
952                 }
953
954                 protected override bool DoEmit (EmitContext ec)
955                 {
956                         ILGenerator ig = ec.ig;
957
958                         if (ec.InLoop == false && ec.Switch == null){
959                                 Report.Error (139, loc, "No enclosing loop or switch to continue to");
960                                 return false;
961                         }
962
963                         if (ec.InTry || ec.InCatch)
964                                 ig.Emit (OpCodes.Leave, ec.LoopEnd);
965                         else
966                                 ig.Emit (OpCodes.Br, ec.LoopEnd);
967
968                         return false;
969                 }
970         }
971
972         public class Continue : Statement {
973                 
974                 public Continue (Location l)
975                 {
976                         loc = l;
977                 }
978
979                 public override bool Resolve (EmitContext ec)
980                 {
981                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
982                         return true;
983                 }
984
985                 protected override bool DoEmit (EmitContext ec)
986                 {
987                         Label begin = ec.LoopBegin;
988                         
989                         if (!ec.InLoop){
990                                 Report.Error (139, loc, "No enclosing loop to continue to");
991                                 return false;
992                         } 
993
994                         //
995                         // UGH: Non trivial.  This Br might cross a try/catch boundary
996                         // How can we tell?
997                         //
998                         // while () {
999                         //   try { ... } catch { continue; }
1000                         // }
1001                         //
1002                         // From:
1003                         // try {} catch { while () { continue; }}
1004                         //
1005                         if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1006                                 ec.ig.Emit (OpCodes.Leave, begin);
1007                         else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1008                                 throw new Exception ("Should never happen");
1009                         else
1010                                 ec.ig.Emit (OpCodes.Br, begin);
1011                         return false;
1012                 }
1013         }
1014
1015         // <summary>
1016         //   This is used in the control flow analysis code to specify whether the
1017         //   current code block may return to its enclosing block before reaching
1018         //   its end.
1019         // </summary>
1020         public enum FlowReturns {
1021                 // It can never return.
1022                 NEVER,
1023
1024                 // This means that the block contains a conditional return statement
1025                 // somewhere.
1026                 SOMETIMES,
1027
1028                 // The code always returns, ie. there's an unconditional return / break
1029                 // statement in it.
1030                 ALWAYS,
1031
1032                 // The code always throws an exception.
1033                 EXCEPTION,
1034
1035                 // The current code block is unreachable.  This happens if it's immediately
1036                 // following a FlowReturns.ALWAYS block.
1037                 UNREACHABLE
1038         }
1039
1040         // <summary>
1041         //   This is a special bit vector which can inherit from another bit vector doing a
1042         //   copy-on-write strategy.  The inherited vector may have a smaller size than the
1043         //   current one.
1044         // </summary>
1045         public class MyBitVector {
1046                 public readonly int Count;
1047                 public readonly MyBitVector InheritsFrom;
1048
1049                 bool is_dirty;
1050                 BitArray vector;
1051
1052                 public MyBitVector (int Count)
1053                         : this (null, Count)
1054                 { }
1055
1056                 public MyBitVector (MyBitVector InheritsFrom, int Count)
1057                 {
1058                         this.InheritsFrom = InheritsFrom;
1059                         this.Count = Count;
1060                 }
1061
1062                 // <summary>
1063                 //   Checks whether this bit vector has been modified.  After setting this to true,
1064                 //   we won't use the inherited vector anymore, but our own copy of it.
1065                 // </summary>
1066                 public bool IsDirty {
1067                         get {
1068                                 return is_dirty;
1069                         }
1070
1071                         set {
1072                                 if (!is_dirty)
1073                                         initialize_vector ();
1074                         }
1075                 }
1076
1077                 // <summary>
1078                 //   Get/set bit `index' in the bit vector.
1079                 // </summary>
1080                 public bool this [int index]
1081                 {
1082                         get {
1083                                 if (index > Count)
1084                                         throw new ArgumentOutOfRangeException ();
1085
1086                                 // We're doing a "copy-on-write" strategy here; as long
1087                                 // as nobody writes to the array, we can use our parent's
1088                                 // copy instead of duplicating the vector.
1089
1090                                 if (vector != null)
1091                                         return vector [index];
1092                                 else if (InheritsFrom != null) {
1093                                         BitArray inherited = InheritsFrom.Vector;
1094
1095                                         if (index < inherited.Count)
1096                                                 return inherited [index];
1097                                         else
1098                                                 return false;
1099                                 } else
1100                                         return false;
1101                         }
1102
1103                         set {
1104                                 if (index > Count)
1105                                         throw new ArgumentOutOfRangeException ();
1106
1107                                 // Only copy the vector if we're actually modifying it.
1108
1109                                 if (this [index] != value) {
1110                                         initialize_vector ();
1111
1112                                         vector [index] = value;
1113                                 }
1114                         }
1115                 }
1116
1117                 // <summary>
1118                 //   If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1119                 //   copy of the bit vector.
1120                 // </summary>
1121                 public static explicit operator BitArray (MyBitVector vector)
1122                 {
1123                         vector.initialize_vector ();
1124                         return vector.Vector;
1125                 }
1126
1127                 // <summary>
1128                 //   Performs an `or' operation on the bit vector.  The `new_vector' may have a
1129                 //   different size than the current one.
1130                 // </summary>
1131                 public void Or (MyBitVector new_vector)
1132                 {
1133                         BitArray new_array = new_vector.Vector;
1134
1135                         initialize_vector ();
1136
1137                         int upper;
1138                         if (vector.Count < new_array.Count)
1139                                 upper = vector.Count;
1140                         else
1141                                 upper = new_array.Count;
1142
1143                         for (int i = 0; i < upper; i++)
1144                                 vector [i] = vector [i] | new_array [i];
1145                 }
1146
1147                 // <summary>
1148                 //   Perfonrms an `and' operation on the bit vector.  The `new_vector' may have
1149                 //   a different size than the current one.
1150                 // </summary>
1151                 public void And (MyBitVector new_vector)
1152                 {
1153                         BitArray new_array = new_vector.Vector;
1154
1155                         initialize_vector ();
1156
1157                         int lower, upper;
1158                         if (vector.Count < new_array.Count)
1159                                 lower = upper = vector.Count;
1160                         else {
1161                                 lower = new_array.Count;
1162                                 upper = vector.Count;
1163                         }
1164
1165                         for (int i = 0; i < lower; i++)
1166                                 vector [i] = vector [i] & new_array [i];
1167
1168                         for (int i = lower; i < upper; i++)
1169                                 vector [i] = false;
1170                 }
1171
1172                 // <summary>
1173                 //   This does a deep copy of the bit vector.
1174                 // </summary>
1175                 public MyBitVector Clone ()
1176                 {
1177                         MyBitVector retval = new MyBitVector (Count);
1178
1179                         retval.Vector = Vector;
1180
1181                         return retval;
1182                 }
1183
1184                 BitArray Vector {
1185                         get {
1186                                 if (vector != null)
1187                                         return vector;
1188                                 else if (!is_dirty && (InheritsFrom != null))
1189                                         return InheritsFrom.Vector;
1190
1191                                 initialize_vector ();
1192
1193                                 return vector;
1194                         }
1195
1196                         set {
1197                                 initialize_vector ();
1198
1199                                 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1200                                         vector [i] = value [i];
1201                         }
1202                 }
1203
1204                 void initialize_vector ()
1205                 {
1206                         if (vector != null)
1207                                 return;
1208
1209                         vector = new BitArray (Count, false);
1210                         if (InheritsFrom != null)
1211                                 Vector = InheritsFrom.Vector;
1212
1213                         is_dirty = true;
1214                 }
1215
1216                 public override string ToString ()
1217                 {
1218                         StringBuilder sb = new StringBuilder ("MyBitVector (");
1219
1220                         BitArray vector = Vector;
1221                         sb.Append (Count);
1222                         sb.Append (",");
1223                         if (!IsDirty)
1224                                 sb.Append ("INHERITED - ");
1225                         for (int i = 0; i < vector.Count; i++) {
1226                                 if (i > 0)
1227                                         sb.Append (",");
1228                                 sb.Append (vector [i]);
1229                         }
1230                         
1231                         sb.Append (")");
1232                         return sb.ToString ();
1233                 }
1234         }
1235
1236         // <summary>
1237         //   The type of a FlowBranching.
1238         // </summary>
1239         public enum FlowBranchingType {
1240                 // Normal (conditional or toplevel) block.
1241                 BLOCK,
1242
1243                 // A loop block.
1244                 LOOP_BLOCK,
1245
1246                 // Try/Catch block.
1247                 EXCEPTION,
1248
1249                 // Switch block.
1250                 SWITCH,
1251
1252                 // Switch section.
1253                 SWITCH_SECTION
1254         }
1255
1256         // <summary>
1257         //   A new instance of this class is created every time a new block is resolved
1258         //   and if there's branching in the block's control flow.
1259         // </summary>
1260         public class FlowBranching {
1261                 // <summary>
1262                 //   The type of this flow branching.
1263                 // </summary>
1264                 public readonly FlowBranchingType Type;
1265
1266                 // <summary>
1267                 //   The block this branching is contained in.  This may be null if it's not
1268                 //   a top-level block and it doesn't declare any local variables.
1269                 // </summary>
1270                 public readonly Block Block;
1271
1272                 // <summary>
1273                 //   The parent of this branching or null if this is the top-block.
1274                 // </summary>
1275                 public readonly FlowBranching Parent;
1276
1277                 // <summary>
1278                 //   Start-Location of this flow branching.
1279                 // </summary>
1280                 public readonly Location Location;
1281
1282                 // <summary>
1283                 //   A list of UsageVectors.  A new vector is added each time control flow may
1284                 //   take a different path.
1285                 // </summary>
1286                 public ArrayList Siblings;
1287
1288                 // <summary>
1289                 //   If this is an infinite loop.
1290                 // </summary>
1291                 public bool Infinite;
1292
1293                 // <summary>
1294                 //   If we may leave the current loop.
1295                 // </summary>
1296                 public bool MayLeaveLoop;
1297
1298                 //
1299                 // Private
1300                 //
1301                 InternalParameters param_info;
1302                 int[] param_map;
1303                 MyStructInfo[] struct_params;
1304                 int num_params;
1305                 ArrayList finally_vectors;
1306
1307                 static int next_id = 0;
1308                 int id;
1309
1310                 // <summary>
1311                 //   Performs an `And' operation on the FlowReturns status
1312                 //   (for instance, a block only returns ALWAYS if all its siblings
1313                 //   always return).
1314                 // </summary>
1315                 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1316                 {
1317                         if (b == FlowReturns.UNREACHABLE)
1318                                 return a;
1319
1320                         switch (a) {
1321                         case FlowReturns.NEVER:
1322                                 if (b == FlowReturns.NEVER)
1323                                         return FlowReturns.NEVER;
1324                                 else
1325                                         return FlowReturns.SOMETIMES;
1326
1327                         case FlowReturns.SOMETIMES:
1328                                 return FlowReturns.SOMETIMES;
1329
1330                         case FlowReturns.ALWAYS:
1331                                 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1332                                         return FlowReturns.ALWAYS;
1333                                 else
1334                                         return FlowReturns.SOMETIMES;
1335
1336                         case FlowReturns.EXCEPTION:
1337                                 if (b == FlowReturns.EXCEPTION)
1338                                         return FlowReturns.EXCEPTION;
1339                                 else if (b == FlowReturns.ALWAYS)
1340                                         return FlowReturns.ALWAYS;
1341                                 else
1342                                         return FlowReturns.SOMETIMES;
1343                         }
1344
1345                         return b;
1346                 }
1347
1348                 // <summary>
1349                 //   The vector contains a BitArray with information about which local variables
1350                 //   and parameters are already initialized at the current code position.
1351                 // </summary>
1352                 public class UsageVector {
1353                         // <summary>
1354                         //   If this is true, then the usage vector has been modified and must be
1355                         //   merged when we're done with this branching.
1356                         // </summary>
1357                         public bool IsDirty;
1358
1359                         // <summary>
1360                         //   The number of parameters in this block.
1361                         // </summary>
1362                         public readonly int CountParameters;
1363
1364                         // <summary>
1365                         //   The number of locals in this block.
1366                         // </summary>
1367                         public readonly int CountLocals;
1368
1369                         // <summary>
1370                         //   If not null, then we inherit our state from this vector and do a
1371                         //   copy-on-write.  If null, then we're the first sibling in a top-level
1372                         //   block and inherit from the empty vector.
1373                         // </summary>
1374                         public readonly UsageVector InheritsFrom;
1375
1376                         //
1377                         // Private.
1378                         //
1379                         MyBitVector locals, parameters;
1380                         FlowReturns real_returns, real_breaks;
1381                         bool is_finally;
1382
1383                         static int next_id = 0;
1384                         int id;
1385
1386                         //
1387                         // Normally, you should not use any of these constructors.
1388                         //
1389                         public UsageVector (UsageVector parent, int num_params, int num_locals)
1390                         {
1391                                 this.InheritsFrom = parent;
1392                                 this.CountParameters = num_params;
1393                                 this.CountLocals = num_locals;
1394                                 this.real_returns = FlowReturns.NEVER;
1395                                 this.real_breaks = FlowReturns.NEVER;
1396
1397                                 if (parent != null) {
1398                                         locals = new MyBitVector (parent.locals, CountLocals);
1399                                         if (num_params > 0)
1400                                                 parameters = new MyBitVector (parent.parameters, num_params);
1401                                         real_returns = parent.Returns;
1402                                         real_breaks = parent.Breaks;
1403                                 } else {
1404                                         locals = new MyBitVector (null, CountLocals);
1405                                         if (num_params > 0)
1406                                                 parameters = new MyBitVector (null, num_params);
1407                                 }
1408
1409                                 id = ++next_id;
1410                         }
1411
1412                         public UsageVector (UsageVector parent)
1413                                 : this (parent, parent.CountParameters, parent.CountLocals)
1414                         { }
1415
1416                         // <summary>
1417                         //   This does a deep copy of the usage vector.
1418                         // </summary>
1419                         public UsageVector Clone ()
1420                         {
1421                                 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1422
1423                                 retval.locals = locals.Clone ();
1424                                 if (parameters != null)
1425                                         retval.parameters = parameters.Clone ();
1426                                 retval.real_returns = real_returns;
1427                                 retval.real_breaks = real_breaks;
1428
1429                                 return retval;
1430                         }
1431
1432                         // 
1433                         // State of parameter `number'.
1434                         //
1435                         public bool this [int number]
1436                         {
1437                                 get {
1438                                         if (number == -1)
1439                                                 return true;
1440                                         else if (number == 0)
1441                                                 throw new ArgumentException ();
1442
1443                                         return parameters [number - 1];
1444                                 }
1445
1446                                 set {
1447                                         if (number == -1)
1448                                                 return;
1449                                         else if (number == 0)
1450                                                 throw new ArgumentException ();
1451
1452                                         parameters [number - 1] = value;
1453                                 }
1454                         }
1455
1456                         //
1457                         // State of the local variable `vi'.
1458                         // If the local variable is a struct, use a non-zero `field_idx'
1459                         // to check an individual field in it.
1460                         //
1461                         public bool this [VariableInfo vi, int field_idx]
1462                         {
1463                                 get {
1464                                         if (vi.Number == -1)
1465                                                 return true;
1466                                         else if (vi.Number == 0)
1467                                                 throw new ArgumentException ();
1468
1469                                         return locals [vi.Number + field_idx - 1];
1470                                 }
1471
1472                                 set {
1473                                         if (vi.Number == -1)
1474                                                 return;
1475                                         else if (vi.Number == 0)
1476                                                 throw new ArgumentException ();
1477
1478                                         locals [vi.Number + field_idx - 1] = value;
1479                                 }
1480                         }
1481
1482                         // <summary>
1483                         //   Specifies when the current block returns.
1484                         //   If this is FlowReturns.UNREACHABLE, then control can never reach the
1485                         //   end of the method (so that we don't need to emit a return statement).
1486                         //   The same applies for FlowReturns.EXCEPTION, but in this case the return
1487                         //   value will never be used.
1488                         // </summary>
1489                         public FlowReturns Returns {
1490                                 get {
1491                                         return real_returns;
1492                                 }
1493
1494                                 set {
1495                                         real_returns = value;
1496                                 }
1497                         }
1498
1499                         // <summary>
1500                         //   Specifies whether control may return to our containing block
1501                         //   before reaching the end of this block.  This happens if there
1502                         //   is a break/continue/goto/return in it.
1503                         //   This can also be used to find out whether the statement immediately
1504                         //   following the current block may be reached or not.
1505                         // </summary>
1506                         public FlowReturns Breaks {
1507                                 get {
1508                                         return real_breaks;
1509                                 }
1510
1511                                 set {
1512                                         real_breaks = value;
1513                                 }
1514                         }
1515
1516                         public bool AlwaysBreaks {
1517                                 get {
1518                                         return (Breaks == FlowReturns.ALWAYS) ||
1519                                                 (Breaks == FlowReturns.EXCEPTION) ||
1520                                                 (Breaks == FlowReturns.UNREACHABLE);
1521                                 }
1522                         }
1523
1524                         public bool MayBreak {
1525                                 get {
1526                                         return Breaks != FlowReturns.NEVER;
1527                                 }
1528                         }
1529
1530                         public bool AlwaysReturns {
1531                                 get {
1532                                         return (Returns == FlowReturns.ALWAYS) ||
1533                                                 (Returns == FlowReturns.EXCEPTION);
1534                                 }
1535                         }
1536
1537                         public bool MayReturn {
1538                                 get {
1539                                         return (Returns == FlowReturns.SOMETIMES) ||
1540                                                 (Returns == FlowReturns.ALWAYS);
1541                                 }
1542                         }
1543
1544                         // <summary>
1545                         //   Merge a child branching.
1546                         // </summary>
1547                         public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1548                         {
1549                                 MyBitVector new_locals = null;
1550                                 MyBitVector new_params = null;
1551
1552                                 FlowReturns new_returns = FlowReturns.NEVER;
1553                                 FlowReturns new_breaks = FlowReturns.NEVER;
1554                                 bool new_returns_set = false, new_breaks_set = false;
1555
1556                                 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1557                                               this, children.Count);
1558
1559                                 foreach (UsageVector child in children) {
1560                                         Report.Debug (2, "  MERGING CHILD", child, child.is_finally);
1561
1562                                         if (!child.is_finally) {
1563                                                 if (child.Breaks != FlowReturns.UNREACHABLE) {
1564                                                         // If Returns is already set, perform an
1565                                                         // `And' operation on it, otherwise just set just.
1566                                                         if (!new_returns_set) {
1567                                                                 new_returns = child.Returns;
1568                                                                 new_returns_set = true;
1569                                                         } else
1570                                                                 new_returns = AndFlowReturns (
1571                                                                         new_returns, child.Returns);
1572                                                 }
1573
1574                                                 // If Breaks is already set, perform an
1575                                                 // `And' operation on it, otherwise just set just.
1576                                                 if (!new_breaks_set) {
1577                                                         new_breaks = child.Breaks;
1578                                                         new_breaks_set = true;
1579                                                 } else
1580                                                         new_breaks = AndFlowReturns (
1581                                                                 new_breaks, child.Breaks);
1582                                         }
1583
1584                                         // Ignore unreachable children.
1585                                         if (child.Returns == FlowReturns.UNREACHABLE)
1586                                                 continue;
1587
1588                                         // A local variable is initialized after a flow branching if it
1589                                         // has been initialized in all its branches which do neither
1590                                         // always return or always throw an exception.
1591                                         //
1592                                         // If a branch may return, but does not always return, then we
1593                                         // can treat it like a never-returning branch here: control will
1594                                         // only reach the code position after the branching if we did not
1595                                         // return here.
1596                                         //
1597                                         // It's important to distinguish between always and sometimes
1598                                         // returning branches here:
1599                                         //
1600                                         //    1   int a;
1601                                         //    2   if (something) {
1602                                         //    3      return;
1603                                         //    4      a = 5;
1604                                         //    5   }
1605                                         //    6   Console.WriteLine (a);
1606                                         //
1607                                         // The if block in lines 3-4 always returns, so we must not look
1608                                         // at the initialization of `a' in line 4 - thus it'll still be
1609                                         // uninitialized in line 6.
1610                                         //
1611                                         // On the other hand, the following is allowed:
1612                                         //
1613                                         //    1   int a;
1614                                         //    2   if (something)
1615                                         //    3      a = 5;
1616                                         //    4   else
1617                                         //    5      return;
1618                                         //    6   Console.WriteLine (a);
1619                                         //
1620                                         // Here, `a' is initialized in line 3 and we must not look at
1621                                         // line 5 since it always returns.
1622                                         // 
1623                                         if (child.is_finally) {
1624                                                 if (new_locals == null)
1625                                                         new_locals = locals.Clone ();
1626                                                 new_locals.Or (child.locals);
1627
1628                                                 if (parameters != null) {
1629                                                         if (new_params == null)
1630                                                                 new_params = parameters.Clone ();
1631                                                         new_params.Or (child.parameters);
1632                                                 }
1633
1634                                         } else {
1635                                                 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1636                                                         if (new_locals != null)
1637                                                                 new_locals.And (child.locals);
1638                                                         else {
1639                                                                 new_locals = locals.Clone ();
1640                                                                 new_locals.Or (child.locals);
1641                                                         }
1642                                                 } else if (children.Count == 1) {
1643                                                         new_locals = locals.Clone ();
1644                                                         new_locals.Or (child.locals);
1645                                                 }
1646
1647                                                 // An `out' parameter must be assigned in all branches which do
1648                                                 // not always throw an exception.
1649                                                 if (parameters != null) {
1650                                                         if (child.Breaks != FlowReturns.EXCEPTION) {
1651                                                                 if (new_params != null)
1652                                                                         new_params.And (child.parameters);
1653                                                                 else {
1654                                                                         new_params = parameters.Clone ();
1655                                                                         new_params.Or (child.parameters);
1656                                                                 }
1657                                                         } else if (children.Count == 1) {
1658                                                                 new_params = parameters.Clone ();
1659                                                                 new_params.Or (child.parameters);
1660                                                         }
1661                                                 }
1662                                         }
1663                                 }
1664
1665                                 Returns = new_returns;
1666                                 if ((branching.Type == FlowBranchingType.BLOCK) ||
1667                                     (branching.Type == FlowBranchingType.EXCEPTION) ||
1668                                     (new_breaks == FlowReturns.UNREACHABLE) ||
1669                                     (new_breaks == FlowReturns.EXCEPTION))
1670                                         Breaks = new_breaks;
1671                                 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1672                                         Breaks = new_returns;
1673
1674                                 //
1675                                 // We've now either reached the point after the branching or we will
1676                                 // never get there since we always return or always throw an exception.
1677                                 //
1678                                 // If we can reach the point after the branching, mark all locals and
1679                                 // parameters as initialized which have been initialized in all branches
1680                                 // we need to look at (see above).
1681                                 //
1682
1683                                 if (((new_breaks != FlowReturns.ALWAYS) &&
1684                                      (new_breaks != FlowReturns.EXCEPTION) &&
1685                                      (new_breaks != FlowReturns.UNREACHABLE)) ||
1686                                     (children.Count == 1)) {
1687                                         if (new_locals != null)
1688                                                 locals.Or (new_locals);
1689
1690                                         if (new_params != null)
1691                                                 parameters.Or (new_params);
1692                                 }
1693
1694                                 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1695                                               new_params, new_locals, new_returns, new_breaks,
1696                                               branching.Infinite, branching.MayLeaveLoop, this);
1697
1698                                 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1699                                         if ((new_breaks != FlowReturns.ALWAYS) &&
1700                                             (new_breaks != FlowReturns.EXCEPTION) &&
1701                                             (new_breaks != FlowReturns.UNREACHABLE))
1702                                                 Report.Error (163, branching.Location,
1703                                                               "Control cannot fall through from one " +
1704                                                               "case label to another");
1705                                 }
1706
1707                                 if (branching.Infinite && !branching.MayLeaveLoop) {
1708                                         Report.Debug (1, "INFINITE", new_returns, new_breaks,
1709                                                       Returns, Breaks, this);
1710
1711                                         // We're actually infinite.
1712                                         if (new_returns == FlowReturns.NEVER) {
1713                                                 Breaks = FlowReturns.UNREACHABLE;
1714                                                 return FlowReturns.UNREACHABLE;
1715                                         }
1716
1717                                         // If we're an infinite loop and do not break, the code after
1718                                         // the loop can never be reached.  However, if we may return
1719                                         // from the loop, then we do always return (or stay in the loop
1720                                         // forever).
1721                                         if ((new_returns == FlowReturns.SOMETIMES) ||
1722                                             (new_returns == FlowReturns.ALWAYS)) {
1723                                                 Returns = FlowReturns.ALWAYS;
1724                                                 return FlowReturns.ALWAYS;
1725                                         }
1726                                 }
1727
1728                                 return new_returns;
1729                         }
1730
1731                         // <summary>
1732                         //   Tells control flow analysis that the current code position may be reached with
1733                         //   a forward jump from any of the origins listed in `origin_vectors' which is a
1734                         //   list of UsageVectors.
1735                         //
1736                         //   This is used when resolving forward gotos - in the following example, the
1737                         //   variable `a' is uninitialized in line 8 becase this line may be reached via
1738                         //   the goto in line 4:
1739                         //
1740                         //      1     int a;
1741                         //
1742                         //      3     if (something)
1743                         //      4        goto World;
1744                         //
1745                         //      6     a = 5;
1746                         //
1747                         //      7  World:
1748                         //      8     Console.WriteLine (a);
1749                         //
1750                         // </summary>
1751                         public void MergeJumpOrigins (ICollection origin_vectors)
1752                         {
1753                                 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1754
1755                                 real_breaks = FlowReturns.NEVER;
1756                                 real_returns = FlowReturns.NEVER;
1757
1758                                 foreach (UsageVector vector in origin_vectors) {
1759                                         Report.Debug (1, "  MERGING JUMP ORIGIN", vector);
1760
1761                                         locals.And (vector.locals);
1762                                         if (parameters != null)
1763                                                 parameters.And (vector.parameters);
1764                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1765                                         Returns = AndFlowReturns (Returns, vector.Returns);
1766                                 }
1767
1768                                 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1769                         }
1770
1771                         // <summary>
1772                         //   This is used at the beginning of a finally block if there were
1773                         //   any return statements in the try block or one of the catch blocks.
1774                         // </summary>
1775                         public void MergeFinallyOrigins (ICollection finally_vectors)
1776                         {
1777                                 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1778
1779                                 real_breaks = FlowReturns.NEVER;
1780
1781                                 foreach (UsageVector vector in finally_vectors) {
1782                                         Report.Debug (1, "  MERGING FINALLY ORIGIN", vector);
1783
1784                                         if (parameters != null)
1785                                                 parameters.And (vector.parameters);
1786                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1787                                 }
1788
1789                                 is_finally = true;
1790
1791                                 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1792                         }
1793
1794                         public void CheckOutParameters (FlowBranching branching)
1795                         {
1796                                 if (parameters != null)
1797                                         branching.CheckOutParameters (parameters, branching.Location);
1798                         }
1799
1800                         // <summary>
1801                         //   Performs an `or' operation on the locals and the parameters.
1802                         // </summary>
1803                         public void Or (UsageVector new_vector)
1804                         {
1805                                 locals.Or (new_vector.locals);
1806                                 if (parameters != null)
1807                                         parameters.Or (new_vector.parameters);
1808                         }
1809
1810                         // <summary>
1811                         //   Performs an `and' operation on the locals.
1812                         // </summary>
1813                         public void AndLocals (UsageVector new_vector)
1814                         {
1815                                 locals.And (new_vector.locals);
1816                         }
1817
1818                         // <summary>
1819                         //   Returns a deep copy of the parameters.
1820                         // </summary>
1821                         public MyBitVector Parameters {
1822                                 get {
1823                                         if (parameters != null)
1824                                                 return parameters.Clone ();
1825                                         else
1826                                                 return null;
1827                                 }
1828                         }
1829
1830                         // <summary>
1831                         //   Returns a deep copy of the locals.
1832                         // </summary>
1833                         public MyBitVector Locals {
1834                                 get {
1835                                         return locals.Clone ();
1836                                 }
1837                         }
1838
1839                         //
1840                         // Debugging stuff.
1841                         //
1842
1843                         public override string ToString ()
1844                         {
1845                                 StringBuilder sb = new StringBuilder ();
1846
1847                                 sb.Append ("Vector (");
1848                                 sb.Append (id);
1849                                 sb.Append (",");
1850                                 sb.Append (Returns);
1851                                 sb.Append (",");
1852                                 sb.Append (Breaks);
1853                                 if (parameters != null) {
1854                                         sb.Append (" - ");
1855                                         sb.Append (parameters);
1856                                 }
1857                                 sb.Append (" - ");
1858                                 sb.Append (locals);
1859                                 sb.Append (")");
1860
1861                                 return sb.ToString ();
1862                         }
1863                 }
1864
1865                 FlowBranching (FlowBranchingType type, Location loc)
1866                 {
1867                         this.Siblings = new ArrayList ();
1868                         this.Block = null;
1869                         this.Location = loc;
1870                         this.Type = type;
1871                         id = ++next_id;
1872                 }
1873
1874                 // <summary>
1875                 //   Creates a new flow branching for `block'.
1876                 //   This is used from Block.Resolve to create the top-level branching of
1877                 //   the block.
1878                 // </summary>
1879                 public FlowBranching (Block block, InternalParameters ip, Location loc)
1880                         : this (FlowBranchingType.BLOCK, loc)
1881                 {
1882                         Block = block;
1883                         Parent = null;
1884
1885                         int count = (ip != null) ? ip.Count : 0;
1886
1887                         param_info = ip;
1888                         param_map = new int [count];
1889                         struct_params = new MyStructInfo [count];
1890                         num_params = 0;
1891
1892                         for (int i = 0; i < count; i++) {
1893                                 Parameter.Modifier mod = param_info.ParameterModifier (i);
1894
1895                                 if ((mod & Parameter.Modifier.OUT) == 0)
1896                                         continue;
1897
1898                                 param_map [i] = ++num_params;
1899
1900                                 Type param_type = param_info.ParameterType (i);
1901
1902                                 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1903                                 if (struct_params [i] != null)
1904                                         num_params += struct_params [i].Count;
1905                         }
1906
1907                         Siblings = new ArrayList ();
1908                         Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1909                 }
1910
1911                 // <summary>
1912                 //   Creates a new flow branching which is contained in `parent'.
1913                 //   You should only pass non-null for the `block' argument if this block
1914                 //   introduces any new variables - in this case, we need to create a new
1915                 //   usage vector with a different size than our parent's one.
1916                 // </summary>
1917                 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1918                                       Block block, Location loc)
1919                         : this (type, loc)
1920                 {
1921                         Parent = parent;
1922                         Block = block;
1923
1924                         if (parent != null) {
1925                                 param_info = parent.param_info;
1926                                 param_map = parent.param_map;
1927                                 struct_params = parent.struct_params;
1928                                 num_params = parent.num_params;
1929                         }
1930
1931                         UsageVector vector;
1932                         if (Block != null)
1933                                 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1934                                                           Block.CountVariables);
1935                         else
1936                                 vector = new UsageVector (Parent.CurrentUsageVector);
1937
1938                         Siblings.Add (vector);
1939
1940                         switch (Type) {
1941                         case FlowBranchingType.EXCEPTION:
1942                                 finally_vectors = new ArrayList ();
1943                                 break;
1944
1945                         default:
1946                                 break;
1947                         }
1948                 }
1949
1950                 // <summary>
1951                 //   Returns the branching's current usage vector.
1952                 // </summary>
1953                 public UsageVector CurrentUsageVector
1954                 {
1955                         get {
1956                                 return (UsageVector) Siblings [Siblings.Count - 1];
1957                         }
1958                 }
1959
1960                 // <summary>
1961                 //   Creates a sibling of the current usage vector.
1962                 // </summary>
1963                 public void CreateSibling ()
1964                 {
1965                         Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1966
1967                         Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1968                 }
1969
1970                 // <summary>
1971                 //   Creates a sibling for a `finally' block.
1972                 // </summary>
1973                 public void CreateSiblingForFinally ()
1974                 {
1975                         if (Type != FlowBranchingType.EXCEPTION)
1976                                 throw new NotSupportedException ();
1977
1978                         CreateSibling ();
1979
1980                         CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1981                 }
1982
1983                 // <summary>
1984                 //   Check whether all `out' parameters have been assigned.
1985                 // </summary>
1986                 public void CheckOutParameters (MyBitVector parameters, Location loc)
1987                 {
1988                         if (InTryBlock ())
1989                                 return;
1990
1991                         for (int i = 0; i < param_map.Length; i++) {
1992                                 int index = param_map [i];
1993
1994                                 if (index == 0)
1995                                         continue;
1996
1997                                 if (parameters [index - 1])
1998                                         continue;
1999
2000                                 // If it's a struct, we must ensure that all its fields have
2001                                 // been assigned.  If the struct has any non-public fields, this
2002                                 // can only be done by assigning the whole struct.
2003
2004                                 MyStructInfo struct_info = struct_params [index - 1];
2005                                 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2006                                         Report.Error (
2007                                                 177, loc, "The out parameter `" +
2008                                                 param_info.ParameterName (i) + "' must be " +
2009                                                 "assigned before control leave the current method.");
2010                                         param_map [i] = 0;
2011                                         continue;
2012                                 }
2013
2014
2015                                 for (int j = 0; j < struct_info.Count; j++) {
2016                                         if (!parameters [index + j]) {
2017                                                 Report.Error (
2018                                                         177, loc, "The out parameter `" +
2019                                                         param_info.ParameterName (i) + "' must be " +
2020                                                         "assigned before control leave the current method.");
2021                                                 param_map [i] = 0;
2022                                                 break;
2023                                         }
2024                                 }
2025                         }
2026                 }
2027
2028                 // <summary>
2029                 //   Merge a child branching.
2030                 // </summary>
2031                 public FlowReturns MergeChild (FlowBranching child)
2032                 {
2033                         FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2034
2035                         if (child.Type != FlowBranchingType.LOOP_BLOCK)
2036                                 MayLeaveLoop |= child.MayLeaveLoop;
2037                         else
2038                                 MayLeaveLoop = false;
2039
2040                         return returns;
2041                 }
2042  
2043                 // <summary>
2044                 //   Does the toplevel merging.
2045                 // </summary>
2046                 public FlowReturns MergeTopBlock ()
2047                 {
2048                         if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2049                                 throw new NotSupportedException ();
2050
2051                         UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2052
2053                         Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2054
2055                         vector.MergeChildren (this, Siblings);
2056
2057                         Siblings.Clear ();
2058                         Siblings.Add (vector);
2059
2060                         Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2061
2062                         if (vector.Breaks != FlowReturns.EXCEPTION) {
2063                                 if (!vector.AlwaysBreaks)
2064                                         CheckOutParameters (CurrentUsageVector.Parameters, Location);
2065                                 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2066                         } else
2067                                 return FlowReturns.EXCEPTION;
2068                 }
2069
2070                 public bool InTryBlock ()
2071                 {
2072                         if (finally_vectors != null)
2073                                 return true;
2074                         else if (Parent != null)
2075                                 return Parent.InTryBlock ();
2076                         else
2077                                 return false;
2078                 }
2079
2080                 public void AddFinallyVector (UsageVector vector)
2081                 {
2082                         if (finally_vectors != null) {
2083                                 finally_vectors.Add (vector.Clone ());
2084                                 return;
2085                         }
2086
2087                         if (Parent != null)
2088                                 Parent.AddFinallyVector (vector);
2089                         else
2090                                 throw new NotSupportedException ();
2091                 }
2092
2093                 public bool IsVariableAssigned (VariableInfo vi)
2094                 {
2095                         if (CurrentUsageVector.AlwaysBreaks)
2096                                 return true;
2097                         else
2098                                 return CurrentUsageVector [vi, 0];
2099                 }
2100
2101                 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2102                 {
2103                         if (CurrentUsageVector.AlwaysBreaks)
2104                                 return true;
2105                         else
2106                                 return CurrentUsageVector [vi, field_idx];
2107                 }
2108
2109                 public void SetVariableAssigned (VariableInfo vi)
2110                 {
2111                         if (CurrentUsageVector.AlwaysBreaks)
2112                                 return;
2113
2114                         CurrentUsageVector [vi, 0] = true;
2115                 }
2116
2117                 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2118                 {
2119                         if (CurrentUsageVector.AlwaysBreaks)
2120                                 return;
2121
2122                         CurrentUsageVector [vi, field_idx] = true;
2123                 }
2124
2125                 public bool IsParameterAssigned (int number)
2126                 {
2127                         int index = param_map [number];
2128
2129                         if (index == 0)
2130                                 return true;
2131
2132                         if (CurrentUsageVector [index])
2133                                 return true;
2134
2135                         // Parameter is not assigned, so check whether it's a struct.
2136                         // If it's either not a struct or a struct which non-public
2137                         // fields, return false.
2138                         MyStructInfo struct_info = struct_params [number];
2139                         if ((struct_info == null) || struct_info.HasNonPublicFields)
2140                                 return false;
2141
2142                         // Ok, so each field must be assigned.
2143                         for (int i = 0; i < struct_info.Count; i++)
2144                                 if (!CurrentUsageVector [index + i])
2145                                         return false;
2146
2147                         return true;
2148                 }
2149
2150                 public bool IsParameterAssigned (int number, string field_name)
2151                 {
2152                         int index = param_map [number];
2153
2154                         if (index == 0)
2155                                 return true;
2156
2157                         MyStructInfo info = (MyStructInfo) struct_params [number];
2158                         if (info == null)
2159                                 return true;
2160
2161                         int field_idx = info [field_name];
2162
2163                         return CurrentUsageVector [index + field_idx];
2164                 }
2165
2166                 public void SetParameterAssigned (int number)
2167                 {
2168                         if (param_map [number] == 0)
2169                                 return;
2170
2171                         if (!CurrentUsageVector.AlwaysBreaks)
2172                                 CurrentUsageVector [param_map [number]] = true;
2173                 }
2174
2175                 public void SetParameterAssigned (int number, string field_name)
2176                 {
2177                         int index = param_map [number];
2178
2179                         if (index == 0)
2180                                 return;
2181
2182                         MyStructInfo info = (MyStructInfo) struct_params [number];
2183                         if (info == null)
2184                                 return;
2185
2186                         int field_idx = info [field_name];
2187
2188                         if (!CurrentUsageVector.AlwaysBreaks)
2189                                 CurrentUsageVector [index + field_idx] = true;
2190                 }
2191
2192                 public bool IsReachable ()
2193                 {
2194                         bool reachable;
2195
2196                         switch (Type) {
2197                         case FlowBranchingType.SWITCH_SECTION:
2198                                 // The code following a switch block is reachable unless the switch
2199                                 // block always returns.
2200                                 reachable = !CurrentUsageVector.AlwaysReturns;
2201                                 break;
2202
2203                         case FlowBranchingType.LOOP_BLOCK:
2204                                 // The code following a loop is reachable unless the loop always
2205                                 // returns or it's an infinite loop without any `break's in it.
2206                                 reachable = !CurrentUsageVector.AlwaysReturns &&
2207                                         (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2208                                 break;
2209
2210                         default:
2211                                 // The code following a block or exception is reachable unless the
2212                                 // block either always returns or always breaks.
2213                                 reachable = !CurrentUsageVector.AlwaysBreaks &&
2214                                         !CurrentUsageVector.AlwaysReturns;
2215                                 break;
2216                         }
2217
2218                         Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2219                                       CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2220
2221                         return reachable;
2222                 }
2223
2224                 public override string ToString ()
2225                 {
2226                         StringBuilder sb = new StringBuilder ("FlowBranching (");
2227
2228                         sb.Append (id);
2229                         sb.Append (",");
2230                         sb.Append (Type);
2231                         if (Block != null) {
2232                                 sb.Append (" - ");
2233                                 sb.Append (Block.ID);
2234                                 sb.Append (" - ");
2235                                 sb.Append (Block.StartLocation);
2236                         }
2237                         sb.Append (" - ");
2238                         sb.Append (Siblings.Count);
2239                         sb.Append (" - ");
2240                         sb.Append (CurrentUsageVector);
2241                         sb.Append (")");
2242                         return sb.ToString ();
2243                 }
2244         }
2245
2246         public class MyStructInfo {
2247                 public readonly Type Type;
2248                 public readonly FieldInfo[] Fields;
2249                 public readonly FieldInfo[] NonPublicFields;
2250                 public readonly int Count;
2251                 public readonly int CountNonPublic;
2252                 public readonly bool HasNonPublicFields;
2253
2254                 private static Hashtable field_type_hash = new Hashtable ();
2255                 private Hashtable field_hash;
2256
2257                 // Private constructor.  To save memory usage, we only need to create one instance
2258                 // of this class per struct type.
2259                 private MyStructInfo (Type type)
2260                 {
2261                         this.Type = type;
2262
2263                         if (type is TypeBuilder) {
2264                                 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2265
2266                                 ArrayList fields = tc.Fields;
2267                                 if (fields != null) {
2268                                         foreach (Field field in fields) {
2269                                                 if ((field.ModFlags & Modifiers.STATIC) != 0)
2270                                                         continue;
2271                                                 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2272                                                         ++Count;
2273                                                 else
2274                                                         ++CountNonPublic;
2275                                         }
2276                                 }
2277
2278                                 Fields = new FieldInfo [Count];
2279                                 NonPublicFields = new FieldInfo [CountNonPublic];
2280
2281                                 Count = CountNonPublic = 0;
2282                                 if (fields != null) {
2283                                         foreach (Field field in fields) {
2284                                                 if ((field.ModFlags & Modifiers.STATIC) != 0)
2285                                                         continue;
2286                                                 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2287                                                         Fields [Count++] = field.FieldBuilder;
2288                                                 else
2289                                                         NonPublicFields [CountNonPublic++] =
2290                                                                 field.FieldBuilder;
2291                                         }
2292                                 }
2293                                 
2294                         } else {
2295                                 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2296                                 Count = Fields.Length;
2297
2298                                 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2299                                 CountNonPublic = NonPublicFields.Length;
2300                         }
2301
2302                         Count += NonPublicFields.Length;
2303
2304                         int number = 0;
2305                         field_hash = new Hashtable ();
2306                         foreach (FieldInfo field in Fields)
2307                                 field_hash.Add (field.Name, ++number);
2308
2309                         if (NonPublicFields.Length != 0)
2310                                 HasNonPublicFields = true;
2311
2312                         foreach (FieldInfo field in NonPublicFields)
2313                                 field_hash.Add (field.Name, ++number);
2314                 }
2315
2316                 public int this [string name] {
2317                         get {
2318                                 if (field_hash.Contains (name))
2319                                         return (int) field_hash [name];
2320                                 else
2321                                         return 0;
2322                         }
2323                 }
2324
2325                 public FieldInfo this [int index] {
2326                         get {
2327                                 if (index >= Fields.Length)
2328                                         return NonPublicFields [index - Fields.Length];
2329                                 else
2330                                         return Fields [index];
2331                         }
2332                 }                      
2333
2334                 public static MyStructInfo GetStructInfo (Type type)
2335                 {
2336                         if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2337                                 return null;
2338
2339                         if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2340                                 return null;
2341
2342                         MyStructInfo info = (MyStructInfo) field_type_hash [type];
2343                         if (info != null)
2344                                 return info;
2345
2346                         info = new MyStructInfo (type);
2347                         field_type_hash.Add (type, info);
2348                         return info;
2349                 }
2350
2351                 public static MyStructInfo GetStructInfo (TypeContainer tc)
2352                 {
2353                         MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2354                         if (info != null)
2355                                 return info;
2356
2357                         info = new MyStructInfo (tc.TypeBuilder);
2358                         field_type_hash.Add (tc.TypeBuilder, info);
2359                         return info;
2360                 }
2361         }
2362         
2363         public class VariableInfo : IVariable {
2364                 public Expression Type;
2365                 public LocalBuilder LocalBuilder;
2366                 public Type VariableType;
2367                 public readonly string Name;
2368                 public readonly Location Location;
2369                 public readonly int Block;
2370
2371                 public int Number;
2372                 
2373                 public bool Used;
2374                 public bool Assigned;
2375                 public bool ReadOnly;
2376                 
2377                 public VariableInfo (Expression type, string name, int block, Location l)
2378                 {
2379                         Type = type;
2380                         Name = name;
2381                         Block = block;
2382                         LocalBuilder = null;
2383                         Location = l;
2384                 }
2385
2386                 public VariableInfo (TypeContainer tc, int block, Location l)
2387                 {
2388                         VariableType = tc.TypeBuilder;
2389                         struct_info = MyStructInfo.GetStructInfo (tc);
2390                         Block = block;
2391                         LocalBuilder = null;
2392                         Location = l;
2393                 }
2394
2395                 MyStructInfo struct_info;
2396                 public MyStructInfo StructInfo {
2397                         get {
2398                                 return struct_info;
2399                         }
2400                 }
2401
2402                 public bool IsAssigned (EmitContext ec, Location loc)
2403                 {
2404                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2405                                 return true;
2406
2407                         MyStructInfo struct_info = StructInfo;
2408                         if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2409                                 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2410                                 ec.CurrentBranching.SetVariableAssigned (this);
2411                                 return false;
2412                         }
2413
2414                         int count = struct_info.Count;
2415
2416                         for (int i = 0; i < count; i++) {
2417                                 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2418                                         if (Name != null) {
2419                                                 Report.Error (165, loc,
2420                                                               "Use of unassigned local variable `" +
2421                                                               Name + "'");
2422                                                 ec.CurrentBranching.SetVariableAssigned (this);
2423                                                 return false;
2424                                         }
2425
2426                                         FieldInfo field = struct_info [i];
2427                                         Report.Error (171, loc,
2428                                                       "Field `" + TypeManager.CSharpName (VariableType) +
2429                                                       "." + field.Name + "' must be fully initialized " +
2430                                                       "before control leaves the constructor");
2431                                         return false;
2432                                 }
2433                         }
2434
2435                         return true;
2436                 }
2437
2438                 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2439                 {
2440                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2441                             (struct_info == null))
2442                                 return true;
2443
2444                         int field_idx = StructInfo [name];
2445                         if (field_idx == 0)
2446                                 return true;
2447
2448                         if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2449                                 Report.Error (170, loc,
2450                                               "Use of possibly unassigned field `" + name + "'");
2451                                 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2452                                 return false;
2453                         }
2454
2455                         return true;
2456                 }
2457
2458                 public void SetAssigned (EmitContext ec)
2459                 {
2460                         if (ec.DoFlowAnalysis)
2461                                 ec.CurrentBranching.SetVariableAssigned (this);
2462                 }
2463
2464                 public void SetFieldAssigned (EmitContext ec, string name)
2465                 {
2466                         if (ec.DoFlowAnalysis && (struct_info != null))
2467                                 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2468                 }
2469
2470                 public bool Resolve (DeclSpace decl)
2471                 {
2472                         if (struct_info != null)
2473                                 return true;
2474
2475                         if (VariableType == null)
2476                                 VariableType = decl.ResolveType (Type, false, Location);
2477
2478                         if (VariableType == null)
2479                                 return false;
2480
2481                         struct_info = MyStructInfo.GetStructInfo (VariableType);
2482
2483                         return true;
2484                 }
2485
2486                 public void MakePinned ()
2487                 {
2488                         TypeManager.MakePinned (LocalBuilder);
2489                 }
2490
2491                 public override string ToString ()
2492                 {
2493                         return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2494                 }
2495         }
2496                 
2497         /// <summary>
2498         ///   Block represents a C# block.
2499         /// </summary>
2500         ///
2501         /// <remarks>
2502         ///   This class is used in a number of places: either to represent
2503         ///   explicit blocks that the programmer places or implicit blocks.
2504         ///
2505         ///   Implicit blocks are used as labels or to introduce variable
2506         ///   declarations.
2507         /// </remarks>
2508         public class Block : Statement {
2509                 public readonly Block     Parent;
2510                 public readonly bool      Implicit;
2511                 public readonly Location  StartLocation;
2512                 public Location           EndLocation;
2513
2514                 //
2515                 // The statements in this block
2516                 //
2517                 ArrayList statements;
2518
2519                 //
2520                 // An array of Blocks.  We keep track of children just
2521                 // to generate the local variable declarations.
2522                 //
2523                 // Statements and child statements are handled through the
2524                 // statements.
2525                 //
2526                 ArrayList children;
2527                 
2528                 //
2529                 // Labels.  (label, block) pairs.
2530                 //
2531                 Hashtable labels;
2532
2533                 //
2534                 // Keeps track of (name, type) pairs
2535                 //
2536                 Hashtable variables;
2537
2538                 //
2539                 // Keeps track of constants
2540                 Hashtable constants;
2541
2542                 //
2543                 // Maps variable names to ILGenerator.LocalBuilders
2544                 //
2545                 Hashtable local_builders;
2546
2547                 bool used = false;
2548
2549                 static int id;
2550
2551                 int this_id;
2552                 
2553                 public Block (Block parent)
2554                         : this (parent, false, Location.Null, Location.Null)
2555                 { }
2556
2557                 public Block (Block parent, bool implicit_block)
2558                         : this (parent, implicit_block, Location.Null, Location.Null)
2559                 { }
2560
2561                 public Block (Block parent, bool implicit_block, Parameters parameters)
2562                         : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2563                 { }
2564
2565                 public Block (Block parent, Location start, Location end)
2566                         : this (parent, false, start, end)
2567                 { }
2568
2569                 public Block (Block parent, Parameters parameters, Location start, Location end)
2570                         : this (parent, false, parameters, start, end)
2571                 { }
2572
2573                 public Block (Block parent, bool implicit_block, Location start, Location end)
2574                         : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2575                                 start, end)
2576                 { }
2577
2578                 public Block (Block parent, bool implicit_block, Parameters parameters,
2579                               Location start, Location end)
2580                 {
2581                         if (parent != null)
2582                                 parent.AddChild (this);
2583                         
2584                         this.Parent = parent;
2585                         this.Implicit = implicit_block;
2586                         this.parameters = parameters;
2587                         this.StartLocation = start;
2588                         this.EndLocation = end;
2589                         this.loc = start;
2590                         this_id = id++;
2591                         statements = new ArrayList ();
2592                 }
2593
2594                 public int ID {
2595                         get {
2596                                 return this_id;
2597                         }
2598                 }
2599
2600                 void AddChild (Block b)
2601                 {
2602                         if (children == null)
2603                                 children = new ArrayList ();
2604                         
2605                         children.Add (b);
2606                 }
2607
2608                 public void SetEndLocation (Location loc)
2609                 {
2610                         EndLocation = loc;
2611                 }
2612
2613                 /// <summary>
2614                 ///   Adds a label to the current block. 
2615                 /// </summary>
2616                 ///
2617                 /// <returns>
2618                 ///   false if the name already exists in this block. true
2619                 ///   otherwise.
2620                 /// </returns>
2621                 ///
2622                 public bool AddLabel (string name, LabeledStatement target)
2623                 {
2624                         if (labels == null)
2625                                 labels = new Hashtable ();
2626                         if (labels.Contains (name))
2627                                 return false;
2628                         
2629                         labels.Add (name, target);
2630                         return true;
2631                 }
2632
2633                 public LabeledStatement LookupLabel (string name)
2634                 {
2635                         if (labels != null){
2636                                 if (labels.Contains (name))
2637                                         return ((LabeledStatement) labels [name]);
2638                         }
2639
2640                         if (Parent != null)
2641                                 return Parent.LookupLabel (name);
2642
2643                         return null;
2644                 }
2645
2646                 VariableInfo this_variable = null;
2647
2648                 // <summary>
2649                 //   Returns the "this" instance variable of this block.
2650                 //   See AddThisVariable() for more information.
2651                 // </summary>
2652                 public VariableInfo ThisVariable {
2653                         get {
2654                                 if (this_variable != null)
2655                                         return this_variable;
2656                                 else if (Parent != null)
2657                                         return Parent.ThisVariable;
2658                                 else
2659                                         return null;
2660                         }
2661                 }
2662
2663                 Hashtable child_variable_names;
2664
2665                 // <summary>
2666                 //   Marks a variable with name @name as being used in a child block.
2667                 //   If a variable name has been used in a child block, it's illegal to
2668                 //   declare a variable with the same name in the current block.
2669                 // </summary>
2670                 public void AddChildVariableName (string name)
2671                 {
2672                         if (child_variable_names == null)
2673                                 child_variable_names = new Hashtable ();
2674
2675                         if (!child_variable_names.Contains (name))
2676                                 child_variable_names.Add (name, true);
2677                 }
2678
2679                 // <summary>
2680                 //   Marks all variables from block @block and all its children as being
2681                 //   used in a child block.
2682                 // </summary>
2683                 public void AddChildVariableNames (Block block)
2684                 {
2685                         if (block.Variables != null) {
2686                                 foreach (string name in block.Variables.Keys)
2687                                         AddChildVariableName (name);
2688                         }
2689
2690                         foreach (Block child in block.children) {
2691                                 if (child.Variables != null) {
2692                                         foreach (string name in child.Variables.Keys)
2693                                                 AddChildVariableName (name);
2694                                 }
2695                         }
2696                 }
2697
2698                 // <summary>
2699                 //   Checks whether a variable name has already been used in a child block.
2700                 // </summary>
2701                 public bool IsVariableNameUsedInChildBlock (string name)
2702                 {
2703                         if (child_variable_names == null)
2704                                 return false;
2705
2706                         return child_variable_names.Contains (name);
2707                 }
2708
2709                 // <summary>
2710                 //   This is used by non-static `struct' constructors which do not have an
2711                 //   initializer - in this case, the constructor must initialize all of the
2712                 //   struct's fields.  To do this, we add a "this" variable and use the flow
2713                 //   analysis code to ensure that it's been fully initialized before control
2714                 //   leaves the constructor.
2715                 // </summary>
2716                 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2717                 {
2718                         if (this_variable != null)
2719                                 return this_variable;
2720
2721                         this_variable = new VariableInfo (tc, ID, l);
2722
2723                         if (variables == null)
2724                                 variables = new Hashtable ();
2725                         variables.Add ("this", this_variable);
2726
2727                         return this_variable;
2728                 }
2729
2730                 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2731                 {
2732                         if (variables == null)
2733                                 variables = new Hashtable ();
2734
2735                         VariableInfo vi = GetVariableInfo (name);
2736                         if (vi != null) {
2737                                 if (vi.Block != ID)
2738                                         Report.Error (136, l, "A local variable named `" + name + "' " +
2739                                                       "cannot be declared in this scope since it would " +
2740                                                       "give a different meaning to `" + name + "', which " +
2741                                                       "is already used in a `parent or current' scope to " +
2742                                                       "denote something else");
2743                                 else
2744                                         Report.Error (128, l, "A local variable `" + name + "' is already " +
2745                                                       "defined in this scope");
2746                                 return null;
2747                         }
2748
2749                         if (IsVariableNameUsedInChildBlock (name)) {
2750                                 Report.Error (136, l, "A local variable named `" + name + "' " +
2751                                               "cannot be declared in this scope since it would " +
2752                                               "give a different meaning to `" + name + "', which " +
2753                                               "is already used in a `child' scope to denote something " +
2754                                               "else");
2755                                 return null;
2756                         }
2757
2758                         if (pars != null) {
2759                                 int idx = 0;
2760                                 Parameter p = pars.GetParameterByName (name, out idx);
2761                                 if (p != null) {
2762                                         Report.Error (136, l, "A local variable named `" + name + "' " +
2763                                                       "cannot be declared in this scope since it would " +
2764                                                       "give a different meaning to `" + name + "', which " +
2765                                                       "is already used in a `parent or current' scope to " +
2766                                                       "denote something else");
2767                                         return null;
2768                                 }
2769                         }
2770                         
2771                         vi = new VariableInfo (type, name, ID, l);
2772
2773                         variables.Add (name, vi);
2774
2775                         if (variables_initialized)
2776                                 throw new Exception ();
2777
2778                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
2779                         return vi;
2780                 }
2781
2782                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2783                 {
2784                         if (AddVariable (type, name, pars, l) == null)
2785                                 return false;
2786                         
2787                         if (constants == null)
2788                                 constants = new Hashtable ();
2789
2790                         constants.Add (name, value);
2791                         return true;
2792                 }
2793
2794                 public Hashtable Variables {
2795                         get {
2796                                 return variables;
2797                         }
2798                 }
2799
2800                 public VariableInfo GetVariableInfo (string name)
2801                 {
2802                         if (variables != null) {
2803                                 object temp;
2804                                 temp = variables [name];
2805
2806                                 if (temp != null){
2807                                         return (VariableInfo) temp;
2808                                 }
2809                         }
2810
2811                         if (Parent != null)
2812                                 return Parent.GetVariableInfo (name);
2813
2814                         return null;
2815                 }
2816                 
2817                 public Expression GetVariableType (string name)
2818                 {
2819                         VariableInfo vi = GetVariableInfo (name);
2820
2821                         if (vi != null)
2822                                 return vi.Type;
2823
2824                         return null;
2825                 }
2826
2827                 public Expression GetConstantExpression (string name)
2828                 {
2829                         if (constants != null) {
2830                                 object temp;
2831                                 temp = constants [name];
2832                                 
2833                                 if (temp != null)
2834                                         return (Expression) temp;
2835                         }
2836                         
2837                         if (Parent != null)
2838                                 return Parent.GetConstantExpression (name);
2839
2840                         return null;
2841                 }
2842                 
2843                 /// <summary>
2844                 ///   True if the variable named @name has been defined
2845                 ///   in this block
2846                 /// </summary>
2847                 public bool IsVariableDefined (string name)
2848                 {
2849                         // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2850                         if (variables != null) {
2851                                 if (variables.Contains (name))
2852                                         return true;
2853                         }
2854                         
2855                         if (Parent != null)
2856                                 return Parent.IsVariableDefined (name);
2857
2858                         return false;
2859                 }
2860
2861                 /// <summary>
2862                 ///   True if the variable named @name is a constant
2863                 ///  </summary>
2864                 public bool IsConstant (string name)
2865                 {
2866                         Expression e = null;
2867                         
2868                         e = GetConstantExpression (name);
2869                         
2870                         return e != null;
2871                 }
2872                 
2873                 /// <summary>
2874                 ///   Use to fetch the statement associated with this label
2875                 /// </summary>
2876                 public Statement this [string name] {
2877                         get {
2878                                 return (Statement) labels [name];
2879                         }
2880                 }
2881
2882                 Parameters parameters = null;
2883                 public Parameters Parameters {
2884                         get {
2885                                 if (Parent != null)
2886                                         return Parent.Parameters;
2887
2888                                 return parameters;
2889                         }
2890                 }
2891
2892                 /// <returns>
2893                 ///   A list of labels that were not used within this block
2894                 /// </returns>
2895                 public string [] GetUnreferenced ()
2896                 {
2897                         // FIXME: Implement me
2898                         return null;
2899                 }
2900
2901                 public void AddStatement (Statement s)
2902                 {
2903                         statements.Add (s);
2904                         used = true;
2905                 }
2906
2907                 public bool Used {
2908                         get {
2909                                 return used;
2910                         }
2911                 }
2912
2913                 public void Use ()
2914                 {
2915                         used = true;
2916                 }
2917
2918                 bool variables_initialized = false;
2919                 int count_variables = 0, first_variable = 0;
2920
2921                 void UpdateVariableInfo (EmitContext ec)
2922                 {
2923                         DeclSpace ds = ec.DeclSpace;
2924
2925                         first_variable = 0;
2926
2927                         if (Parent != null)
2928                                 first_variable += Parent.CountVariables;
2929
2930                         count_variables = first_variable;
2931                         if (variables != null) {
2932                                 foreach (VariableInfo vi in variables.Values) {
2933                                         if (!vi.Resolve (ds)) {
2934                                                 vi.Number = -1;
2935                                                 continue;
2936                                         }
2937
2938                                         vi.Number = ++count_variables;
2939
2940                                         if (vi.StructInfo != null)
2941                                                 count_variables += vi.StructInfo.Count;
2942                                 }
2943                         }
2944
2945                         variables_initialized = true;
2946                 }
2947
2948                 //
2949                 // <returns>
2950                 //   The number of local variables in this block
2951                 // </returns>
2952                 public int CountVariables
2953                 {
2954                         get {
2955                                 if (!variables_initialized)
2956                                         throw new Exception ();
2957
2958                                 return count_variables;
2959                         }
2960                 }
2961
2962                 /// <summary>
2963                 ///   Emits the variable declarations and labels.
2964                 /// </summary>
2965                 /// <remarks>
2966                 ///   tc: is our typecontainer (to resolve type references)
2967                 ///   ig: is the code generator:
2968                 ///   toplevel: the toplevel block.  This is used for checking 
2969                 ///             that no two labels with the same name are used.
2970                 /// </remarks>
2971                 public void EmitMeta (EmitContext ec, Block toplevel)
2972                 {
2973                         DeclSpace ds = ec.DeclSpace;
2974                         ILGenerator ig = ec.ig;
2975
2976                         if (!variables_initialized)
2977                                 UpdateVariableInfo (ec);
2978
2979                         //
2980                         // Process this block variables
2981                         //
2982                         if (variables != null){
2983                                 local_builders = new Hashtable ();
2984                                 
2985                                 foreach (DictionaryEntry de in variables){
2986                                         string name = (string) de.Key;
2987                                         VariableInfo vi = (VariableInfo) de.Value;
2988
2989                                         if (vi.VariableType == null)
2990                                                 continue;
2991
2992                                         vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2993
2994                                         if (CodeGen.SymbolWriter != null)
2995                                                 vi.LocalBuilder.SetLocalSymInfo (name);
2996
2997                                         if (constants == null)
2998                                                 continue;
2999
3000                                         Expression cv = (Expression) constants [name];
3001                                         if (cv == null)
3002                                                 continue;
3003
3004                                         Expression e = cv.Resolve (ec);
3005                                         if (e == null)
3006                                                 continue;
3007
3008                                         if (!(e is Constant)){
3009                                                 Report.Error (133, vi.Location,
3010                                                               "The expression being assigned to `" +
3011                                                               name + "' must be constant (" + e + ")");
3012                                                 continue;
3013                                         }
3014
3015                                         constants.Remove (name);
3016                                         constants.Add (name, e);
3017                                 }
3018                         }
3019
3020                         //
3021                         // Now, handle the children
3022                         //
3023                         if (children != null){
3024                                 foreach (Block b in children)
3025                                         b.EmitMeta (ec, toplevel);
3026                         }
3027                 }
3028
3029                 public void UsageWarning ()
3030                 {
3031                         string name;
3032                         
3033                         if (variables != null){
3034                                 foreach (DictionaryEntry de in variables){
3035                                         VariableInfo vi = (VariableInfo) de.Value;
3036                                         
3037                                         if (vi.Used)
3038                                                 continue;
3039                                         
3040                                         name = (string) de.Key;
3041                                                 
3042                                         if (vi.Assigned){
3043                                                 Report.Warning (
3044                                                         219, vi.Location, "The variable `" + name +
3045                                                         "' is assigned but its value is never used");
3046                                         } else {
3047                                                 Report.Warning (
3048                                                         168, vi.Location, "The variable `" +
3049                                                         name +
3050                                                         "' is declared but never used");
3051                                         } 
3052                                 }
3053                         }
3054
3055                         if (children != null)
3056                                 foreach (Block b in children)
3057                                         b.UsageWarning ();
3058                 }
3059
3060                 bool has_ret = false;
3061
3062                 public override bool Resolve (EmitContext ec)
3063                 {
3064                         Block prev_block = ec.CurrentBlock;
3065                         bool ok = true;
3066
3067                         ec.CurrentBlock = this;
3068                         ec.StartFlowBranching (this);
3069
3070                         Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3071
3072                         if (!variables_initialized)
3073                                 UpdateVariableInfo (ec);
3074
3075                         ArrayList new_statements = new ArrayList ();
3076                         bool unreachable = false, warning_shown = false;
3077
3078                         foreach (Statement s in statements){
3079                                 if (unreachable && !(s is LabeledStatement)) {
3080                                         if (!warning_shown && !(s is EmptyStatement)) {
3081                                                 warning_shown = true;
3082                                                 Warning_DeadCodeFound (s.loc);
3083                                         }
3084
3085                                         continue;
3086                                 }
3087
3088                                 if (s.Resolve (ec) == false) {
3089                                         ok = false;
3090                                         continue;
3091                                 }
3092
3093                                 if (s is LabeledStatement)
3094                                         unreachable = false;
3095                                 else
3096                                         unreachable = ! ec.CurrentBranching.IsReachable ();
3097
3098                                 new_statements.Add (s);
3099                         }
3100
3101                         statements = new_statements;
3102
3103                         Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3104
3105                         FlowReturns returns = ec.EndFlowBranching ();
3106                         ec.CurrentBlock = prev_block;
3107
3108                         // If we're a non-static `struct' constructor which doesn't have an
3109                         // initializer, then we must initialize all of the struct's fields.
3110                         if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3111                             !this_variable.IsAssigned (ec, loc))
3112                                 ok = false;
3113
3114                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3115                                 foreach (LabeledStatement label in labels.Values)
3116                                         if (!label.HasBeenReferenced)
3117                                                 Report.Warning (164, label.Location,
3118                                                                 "This label has not been referenced");
3119                         }
3120
3121                         if ((returns == FlowReturns.ALWAYS) ||
3122                             (returns == FlowReturns.EXCEPTION) ||
3123                             (returns == FlowReturns.UNREACHABLE))
3124                                 has_ret = true;
3125
3126                         return ok;
3127                 }
3128                 
3129                 protected override bool DoEmit (EmitContext ec)
3130                 {
3131                         Block prev_block = ec.CurrentBlock;
3132
3133                         ec.CurrentBlock = this;
3134
3135                         ec.Mark (StartLocation);
3136                         foreach (Statement s in statements)
3137                                 s.Emit (ec);
3138                         ec.Mark (EndLocation); 
3139                         
3140                         ec.CurrentBlock = prev_block;
3141                         return has_ret;
3142                 }
3143         }
3144
3145         public class SwitchLabel {
3146                 Expression label;
3147                 object converted;
3148                 public Location loc;
3149                 public Label ILLabel;
3150                 public Label ILLabelCode;
3151
3152                 //
3153                 // if expr == null, then it is the default case.
3154                 //
3155                 public SwitchLabel (Expression expr, Location l)
3156                 {
3157                         label = expr;
3158                         loc = l;
3159                 }
3160
3161                 public Expression Label {
3162                         get {
3163                                 return label;
3164                         }
3165                 }
3166
3167                 public object Converted {
3168                         get {
3169                                 return converted;
3170                         }
3171                 }
3172
3173                 //
3174                 // Resolves the expression, reduces it to a literal if possible
3175                 // and then converts it to the requested type.
3176                 //
3177                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3178                 {
3179                         ILLabel = ec.ig.DefineLabel ();
3180                         ILLabelCode = ec.ig.DefineLabel ();
3181
3182                         if (label == null)
3183                                 return true;
3184                         
3185                         Expression e = label.Resolve (ec);
3186
3187                         if (e == null)
3188                                 return false;
3189
3190                         if (!(e is Constant)){
3191                                 Console.WriteLine ("Value is: " + label);
3192                                 Report.Error (150, loc, "A constant value is expected");
3193                                 return false;
3194                         }
3195
3196                         if (e is StringConstant || e is NullLiteral){
3197                                 if (required_type == TypeManager.string_type){
3198                                         converted = e;
3199                                         ILLabel = ec.ig.DefineLabel ();
3200                                         return true;
3201                                 }
3202                         }
3203
3204                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3205                         if (converted == null)
3206                                 return false;
3207
3208                         return true;
3209                 }
3210         }
3211
3212         public class SwitchSection {
3213                 // An array of SwitchLabels.
3214                 public readonly ArrayList Labels;
3215                 public readonly Block Block;
3216                 
3217                 public SwitchSection (ArrayList labels, Block block)
3218                 {
3219                         Labels = labels;
3220                         Block = block;
3221                 }
3222         }
3223         
3224         public class Switch : Statement {
3225                 public readonly ArrayList Sections;
3226                 public Expression Expr;
3227
3228                 /// <summary>
3229                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
3230                 /// </summary>
3231                 public Hashtable Elements;
3232
3233                 /// <summary>
3234                 ///   The governing switch type
3235                 /// </summary>
3236                 public Type SwitchType;
3237
3238                 //
3239                 // Computed
3240                 //
3241                 bool got_default;
3242                 Label default_target;
3243                 Expression new_expr;
3244
3245                 //
3246                 // The types allowed to be implicitly cast from
3247                 // on the governing type
3248                 //
3249                 static Type [] allowed_types;
3250                 
3251                 public Switch (Expression e, ArrayList sects, Location l)
3252                 {
3253                         Expr = e;
3254                         Sections = sects;
3255                         loc = l;
3256                 }
3257
3258                 public bool GotDefault {
3259                         get {
3260                                 return got_default;
3261                         }
3262                 }
3263
3264                 public Label DefaultTarget {
3265                         get {
3266                                 return default_target;
3267                         }
3268                 }
3269
3270                 //
3271                 // Determines the governing type for a switch.  The returned
3272                 // expression might be the expression from the switch, or an
3273                 // expression that includes any potential conversions to the
3274                 // integral types or to string.
3275                 //
3276                 Expression SwitchGoverningType (EmitContext ec, Type t)
3277                 {
3278                         if (t == TypeManager.int32_type ||
3279                             t == TypeManager.uint32_type ||
3280                             t == TypeManager.char_type ||
3281                             t == TypeManager.byte_type ||
3282                             t == TypeManager.sbyte_type ||
3283                             t == TypeManager.ushort_type ||
3284                             t == TypeManager.short_type ||
3285                             t == TypeManager.uint64_type ||
3286                             t == TypeManager.int64_type ||
3287                             t == TypeManager.string_type ||
3288                                 t == TypeManager.bool_type ||
3289                                 t.IsSubclassOf (TypeManager.enum_type))
3290                                 return Expr;
3291
3292                         if (allowed_types == null){
3293                                 allowed_types = new Type [] {
3294                                         TypeManager.sbyte_type,
3295                                         TypeManager.byte_type,
3296                                         TypeManager.short_type,
3297                                         TypeManager.ushort_type,
3298                                         TypeManager.int32_type,
3299                                         TypeManager.uint32_type,
3300                                         TypeManager.int64_type,
3301                                         TypeManager.uint64_type,
3302                                         TypeManager.char_type,
3303                                         TypeManager.bool_type,
3304                                         TypeManager.string_type
3305                                 };
3306                         }
3307
3308                         //
3309                         // Try to find a *user* defined implicit conversion.
3310                         //
3311                         // If there is no implicit conversion, or if there are multiple
3312                         // conversions, we have to report an error
3313                         //
3314                         Expression converted = null;
3315                         foreach (Type tt in allowed_types){
3316                                 Expression e;
3317                                 
3318                                 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3319                                 if (e == null)
3320                                         continue;
3321
3322                                 if (converted != null){
3323                                         Report.Error (-12, loc, "More than one conversion to an integral " +
3324                                                       " type exists for type `" +
3325                                                       TypeManager.CSharpName (Expr.Type)+"'");
3326                                         return null;
3327                                 } else
3328                                         converted = e;
3329                         }
3330                         return converted;
3331                 }
3332
3333                 void error152 (string n)
3334                 {
3335                         Report.Error (
3336                                 152, "The label `" + n + ":' " +
3337                                 "is already present on this switch statement");
3338                 }
3339                 
3340                 //
3341                 // Performs the basic sanity checks on the switch statement
3342                 // (looks for duplicate keys and non-constant expressions).
3343                 //
3344                 // It also returns a hashtable with the keys that we will later
3345                 // use to compute the switch tables
3346                 //
3347                 bool CheckSwitch (EmitContext ec)
3348                 {
3349                         Type compare_type;
3350                         bool error = false;
3351                         Elements = new Hashtable ();
3352                                 
3353                         got_default = false;
3354
3355                         if (TypeManager.IsEnumType (SwitchType)){
3356                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3357                         } else
3358                                 compare_type = SwitchType;
3359                         
3360                         foreach (SwitchSection ss in Sections){
3361                                 foreach (SwitchLabel sl in ss.Labels){
3362                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
3363                                                 error = true;
3364                                                 continue;
3365                                         }
3366
3367                                         if (sl.Label == null){
3368                                                 if (got_default){
3369                                                         error152 ("default");
3370                                                         error = true;
3371                                                 }
3372                                                 got_default = true;
3373                                                 continue;
3374                                         }
3375                                         
3376                                         object key = sl.Converted;
3377
3378                                         if (key is Constant)
3379                                                 key = ((Constant) key).GetValue ();
3380
3381                                         if (key == null)
3382                                                 key = NullLiteral.Null;
3383                                         
3384                                         string lname = null;
3385                                         if (compare_type == TypeManager.uint64_type){
3386                                                 ulong v = (ulong) key;
3387
3388                                                 if (Elements.Contains (v))
3389                                                         lname = v.ToString ();
3390                                                 else
3391                                                         Elements.Add (v, sl);
3392                                         } else if (compare_type == TypeManager.int64_type){
3393                                                 long v = (long) key;
3394
3395                                                 if (Elements.Contains (v))
3396                                                         lname = v.ToString ();
3397                                                 else
3398                                                         Elements.Add (v, sl);
3399                                         } else if (compare_type == TypeManager.uint32_type){
3400                                                 uint v = (uint) key;
3401
3402                                                 if (Elements.Contains (v))
3403                                                         lname = v.ToString ();
3404                                                 else
3405                                                         Elements.Add (v, sl);
3406                                         } else if (compare_type == TypeManager.char_type){
3407                                                 char v = (char) key;
3408                                                 
3409                                                 if (Elements.Contains (v))
3410                                                         lname = v.ToString ();
3411                                                 else
3412                                                         Elements.Add (v, sl);
3413                                         } else if (compare_type == TypeManager.byte_type){
3414                                                 byte v = (byte) key;
3415                                                 
3416                                                 if (Elements.Contains (v))
3417                                                         lname = v.ToString ();
3418                                                 else
3419                                                         Elements.Add (v, sl);
3420                                         } else if (compare_type == TypeManager.sbyte_type){
3421                                                 sbyte v = (sbyte) key;
3422                                                 
3423                                                 if (Elements.Contains (v))
3424                                                         lname = v.ToString ();
3425                                                 else
3426                                                         Elements.Add (v, sl);
3427                                         } else if (compare_type == TypeManager.short_type){
3428                                                 short v = (short) key;
3429                                                 
3430                                                 if (Elements.Contains (v))
3431                                                         lname = v.ToString ();
3432                                                 else
3433                                                         Elements.Add (v, sl);
3434                                         } else if (compare_type == TypeManager.ushort_type){
3435                                                 ushort v = (ushort) key;
3436                                                 
3437                                                 if (Elements.Contains (v))
3438                                                         lname = v.ToString ();
3439                                                 else
3440                                                         Elements.Add (v, sl);
3441                                         } else if (compare_type == TypeManager.string_type){
3442                                                 if (key is NullLiteral){
3443                                                         if (Elements.Contains (NullLiteral.Null))
3444                                                                 lname = "null";
3445                                                         else
3446                                                                 Elements.Add (NullLiteral.Null, null);
3447                                                 } else {
3448                                                         string s = (string) key;
3449
3450                                                         if (Elements.Contains (s))
3451                                                                 lname = s;
3452                                                         else
3453                                                                 Elements.Add (s, sl);
3454                                                 }
3455                                         } else if (compare_type == TypeManager.int32_type) {
3456                                                 int v = (int) key;
3457
3458                                                 if (Elements.Contains (v))
3459                                                         lname = v.ToString ();
3460                                                 else
3461                                                         Elements.Add (v, sl);
3462                                         } else if (compare_type == TypeManager.bool_type) {
3463                                                 bool v = (bool) key;
3464
3465                                                 if (Elements.Contains (v))
3466                                                         lname = v.ToString ();
3467                                                 else
3468                                                         Elements.Add (v, sl);
3469                                         }
3470                                         else
3471                                         {
3472                                                 throw new Exception ("Unknown switch type!" +
3473                                                                      SwitchType + " " + compare_type);
3474                                         }
3475
3476                                         if (lname != null){
3477                                                 error152 ("case + " + lname);
3478                                                 error = true;
3479                                         }
3480                                 }
3481                         }
3482                         if (error)
3483                                 return false;
3484                         
3485                         return true;
3486                 }
3487
3488                 void EmitObjectInteger (ILGenerator ig, object k)
3489                 {
3490                         if (k is int)
3491                                 IntConstant.EmitInt (ig, (int) k);
3492                         else if (k is Constant) {
3493                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3494                         } 
3495                         else if (k is uint)
3496                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3497                         else if (k is long)
3498                         {
3499                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3500                                 {
3501                                         IntConstant.EmitInt (ig, (int) (long) k);
3502                                         ig.Emit (OpCodes.Conv_I8);
3503                                 }
3504                                 else
3505                                         LongConstant.EmitLong (ig, (long) k);
3506                         }
3507                         else if (k is ulong)
3508                         {
3509                                 if ((ulong) k < (1L<<32))
3510                                 {
3511                                         IntConstant.EmitInt (ig, (int) (long) k);
3512                                         ig.Emit (OpCodes.Conv_U8);
3513                                 }
3514                                 else
3515                                 {
3516                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3517                                 }
3518                         }
3519                         else if (k is char)
3520                                 IntConstant.EmitInt (ig, (int) ((char) k));
3521                         else if (k is sbyte)
3522                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3523                         else if (k is byte)
3524                                 IntConstant.EmitInt (ig, (int) ((byte) k));
3525                         else if (k is short)
3526                                 IntConstant.EmitInt (ig, (int) ((short) k));
3527                         else if (k is ushort)
3528                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
3529                         else if (k is bool)
3530                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3531                         else
3532                                 throw new Exception ("Unhandled case");
3533                 }
3534                 
3535                 // structure used to hold blocks of keys while calculating table switch
3536                 class KeyBlock : IComparable
3537                 {
3538                         public KeyBlock (long _nFirst)
3539                         {
3540                                 nFirst = nLast = _nFirst;
3541                         }
3542                         public long nFirst;
3543                         public long nLast;
3544                         public ArrayList rgKeys = null;
3545                         public int Length
3546                         {
3547                                 get { return (int) (nLast - nFirst + 1); }
3548                         }
3549                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3550                         {
3551                                 return kbLast.nLast - kbFirst.nFirst + 1;
3552                         }
3553                         public int CompareTo (object obj)
3554                         {
3555                                 KeyBlock kb = (KeyBlock) obj;
3556                                 int nLength = Length;
3557                                 int nLengthOther = kb.Length;
3558                                 if (nLengthOther == nLength)
3559                                         return (int) (kb.nFirst - nFirst);
3560                                 return nLength - nLengthOther;
3561                         }
3562                 }
3563
3564                 /// <summary>
3565                 /// This method emits code for a lookup-based switch statement (non-string)
3566                 /// Basically it groups the cases into blocks that are at least half full,
3567                 /// and then spits out individual lookup opcodes for each block.
3568                 /// It emits the longest blocks first, and short blocks are just
3569                 /// handled with direct compares.
3570                 /// </summary>
3571                 /// <param name="ec"></param>
3572                 /// <param name="val"></param>
3573                 /// <returns></returns>
3574                 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3575                 {
3576                         int cElements = Elements.Count;
3577                         object [] rgKeys = new object [cElements];
3578                         Elements.Keys.CopyTo (rgKeys, 0);
3579                         Array.Sort (rgKeys);
3580
3581                         // initialize the block list with one element per key
3582                         ArrayList rgKeyBlocks = new ArrayList ();
3583                         foreach (object key in rgKeys)
3584                                 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3585
3586                         KeyBlock kbCurr;
3587                         // iteratively merge the blocks while they are at least half full
3588                         // there's probably a really cool way to do this with a tree...
3589                         while (rgKeyBlocks.Count > 1)
3590                         {
3591                                 ArrayList rgKeyBlocksNew = new ArrayList ();
3592                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3593                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3594                                 {
3595                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3596                                         if ((kbCurr.Length + kb.Length) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
3597                                         {
3598                                                 // merge blocks
3599                                                 kbCurr.nLast = kb.nLast;
3600                                         }
3601                                         else
3602                                         {
3603                                                 // start a new block
3604                                                 rgKeyBlocksNew.Add (kbCurr);
3605                                                 kbCurr = kb;
3606                                         }
3607                                 }
3608                                 rgKeyBlocksNew.Add (kbCurr);
3609                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3610                                         break;
3611                                 rgKeyBlocks = rgKeyBlocksNew;
3612                         }
3613
3614                         // initialize the key lists
3615                         foreach (KeyBlock kb in rgKeyBlocks)
3616                                 kb.rgKeys = new ArrayList ();
3617
3618                         // fill the key lists
3619                         int iBlockCurr = 0;
3620                         if (rgKeyBlocks.Count > 0) {
3621                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3622                                 foreach (object key in rgKeys)
3623                                 {
3624                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3625                                         if (fNextBlock)
3626                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3627                                         kbCurr.rgKeys.Add (key);
3628                                 }
3629                         }
3630
3631                         // sort the blocks so we can tackle the largest ones first
3632                         rgKeyBlocks.Sort ();
3633
3634                         // okay now we can start...
3635                         ILGenerator ig = ec.ig;
3636                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
3637                         Label lblDefault = ig.DefineLabel ();
3638
3639                         Type typeKeys = null;
3640                         if (rgKeys.Length > 0)
3641                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
3642
3643                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3644                         {
3645                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3646                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3647                                 if (kb.Length <= 2)
3648                                 {
3649                                         foreach (object key in kb.rgKeys)
3650                                         {
3651                                                 ig.Emit (OpCodes.Ldloc, val);
3652                                                 EmitObjectInteger (ig, key);
3653                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
3654                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
3655                                         }
3656                                 }
3657                                 else
3658                                 {
3659                                         // TODO: if all the keys in the block are the same and there are
3660                                         //       no gaps/defaults then just use a range-check.
3661                                         if (SwitchType == TypeManager.int64_type ||
3662                                                 SwitchType == TypeManager.uint64_type)
3663                                         {
3664                                                 // TODO: optimize constant/I4 cases
3665
3666                                                 // check block range (could be > 2^31)
3667                                                 ig.Emit (OpCodes.Ldloc, val);
3668                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3669                                                 ig.Emit (OpCodes.Blt, lblDefault);
3670                                                 ig.Emit (OpCodes.Ldloc, val);
3671                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3672                                                 ig.Emit (OpCodes.Bgt, lblDefault);
3673
3674                                                 // normalize range
3675                                                 ig.Emit (OpCodes.Ldloc, val);
3676                                                 if (kb.nFirst != 0)
3677                                                 {
3678                                                         EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3679                                                         ig.Emit (OpCodes.Sub);
3680                                                 }
3681                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
3682                                         }
3683                                         else
3684                                         {
3685                                                 // normalize range
3686                                                 ig.Emit (OpCodes.Ldloc, val);
3687                                                 int nFirst = (int) kb.nFirst;
3688                                                 if (nFirst > 0)
3689                                                 {
3690                                                         IntConstant.EmitInt (ig, nFirst);
3691                                                         ig.Emit (OpCodes.Sub);
3692                                                 }
3693                                                 else if (nFirst < 0)
3694                                                 {
3695                                                         IntConstant.EmitInt (ig, -nFirst);
3696                                                         ig.Emit (OpCodes.Add);
3697                                                 }
3698                                         }
3699
3700                                         // first, build the list of labels for the switch
3701                                         int iKey = 0;
3702                                         int cJumps = kb.Length;
3703                                         Label [] rgLabels = new Label [cJumps];
3704                                         for (int iJump = 0; iJump < cJumps; iJump++)
3705                                         {
3706                                                 object key = kb.rgKeys [iKey];
3707                                                 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3708                                                 {
3709                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
3710                                                         rgLabels [iJump] = sl.ILLabel;
3711                                                         iKey++;
3712                                                 }
3713                                                 else
3714                                                         rgLabels [iJump] = lblDefault;
3715                                         }
3716                                         // emit the switch opcode
3717                                         ig.Emit (OpCodes.Switch, rgLabels);
3718                                 }
3719
3720                                 // mark the default for this block
3721                                 if (iBlock != 0)
3722                                         ig.MarkLabel (lblDefault);
3723                         }
3724
3725                         // TODO: find the default case and emit it here,
3726                         //       to prevent having to do the following jump.
3727                         //       make sure to mark other labels in the default section
3728
3729                         // the last default just goes to the end
3730                         ig.Emit (OpCodes.Br, lblDefault);
3731
3732                         // now emit the code for the sections
3733                         bool fFoundDefault = false;
3734                         bool fAllReturn = true;
3735                         foreach (SwitchSection ss in Sections)
3736                         {
3737                                 foreach (SwitchLabel sl in ss.Labels)
3738                                 {
3739                                         ig.MarkLabel (sl.ILLabel);
3740                                         ig.MarkLabel (sl.ILLabelCode);
3741                                         if (sl.Label == null)
3742                                         {
3743                                                 ig.MarkLabel (lblDefault);
3744                                                 fFoundDefault = true;
3745                                         }
3746                                 }
3747                                 bool returns = ss.Block.Emit (ec);
3748                                 fAllReturn &= returns;
3749                                 //ig.Emit (OpCodes.Br, lblEnd);
3750                         }
3751                         
3752                         if (!fFoundDefault) {
3753                                 ig.MarkLabel (lblDefault);
3754                                 fAllReturn = false;
3755                         }
3756                         ig.MarkLabel (lblEnd);
3757
3758                         return fAllReturn;
3759                 }
3760                 //
3761                 // This simple emit switch works, but does not take advantage of the
3762                 // `switch' opcode. 
3763                 // TODO: remove non-string logic from here
3764                 // TODO: binary search strings?
3765                 //
3766                 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3767                 {
3768                         ILGenerator ig = ec.ig;
3769                         Label end_of_switch = ig.DefineLabel ();
3770                         Label next_test = ig.DefineLabel ();
3771                         Label null_target = ig.DefineLabel ();
3772                         bool default_found = false;
3773                         bool first_test = true;
3774                         bool pending_goto_end = false;
3775                         bool all_return = true;
3776                         bool is_string = false;
3777                         bool null_found;
3778                         
3779                         //
3780                         // Special processing for strings: we cant compare
3781                         // against null.
3782                         //
3783                         if (SwitchType == TypeManager.string_type){
3784                                 ig.Emit (OpCodes.Ldloc, val);
3785                                 is_string = true;
3786                                 
3787                                 if (Elements.Contains (NullLiteral.Null)){
3788                                         ig.Emit (OpCodes.Brfalse, null_target);
3789                                 } else
3790                                         ig.Emit (OpCodes.Brfalse, default_target);
3791
3792                                 ig.Emit (OpCodes.Ldloc, val);
3793                                 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3794                                 ig.Emit (OpCodes.Stloc, val);
3795                         }
3796                         
3797                         foreach (SwitchSection ss in Sections){
3798                                 Label sec_begin = ig.DefineLabel ();
3799
3800                                 if (pending_goto_end)
3801                                         ig.Emit (OpCodes.Br, end_of_switch);
3802
3803                                 int label_count = ss.Labels.Count;
3804                                 null_found = false;
3805                                 foreach (SwitchLabel sl in ss.Labels){
3806                                         ig.MarkLabel (sl.ILLabel);
3807                                         
3808                                         if (!first_test){
3809                                                 ig.MarkLabel (next_test);
3810                                                 next_test = ig.DefineLabel ();
3811                                         }
3812                                         //
3813                                         // If we are the default target
3814                                         //
3815                                         if (sl.Label == null){
3816                                                 ig.MarkLabel (default_target);
3817                                                 default_found = true;
3818                                         } else {
3819                                                 object lit = sl.Converted;
3820
3821                                                 if (lit is NullLiteral){
3822                                                         null_found = true;
3823                                                         if (label_count == 1)
3824                                                                 ig.Emit (OpCodes.Br, next_test);
3825                                                         continue;
3826                                                                               
3827                                                 }
3828                                                 if (is_string){
3829                                                         StringConstant str = (StringConstant) lit;
3830
3831                                                         ig.Emit (OpCodes.Ldloc, val);
3832                                                         ig.Emit (OpCodes.Ldstr, str.Value);
3833                                                         if (label_count == 1)
3834                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
3835                                                         else
3836                                                                 ig.Emit (OpCodes.Beq, sec_begin);
3837                                                 } else {
3838                                                         ig.Emit (OpCodes.Ldloc, val);
3839                                                         EmitObjectInteger (ig, lit);
3840                                                         ig.Emit (OpCodes.Ceq);
3841                                                         if (label_count == 1)
3842                                                                 ig.Emit (OpCodes.Brfalse, next_test);
3843                                                         else
3844                                                                 ig.Emit (OpCodes.Brtrue, sec_begin);
3845                                                 }
3846                                         }
3847                                 }
3848                                 if (label_count != 1)
3849                                         ig.Emit (OpCodes.Br, next_test);
3850                                 
3851                                 if (null_found)
3852                                         ig.MarkLabel (null_target);
3853                                 ig.MarkLabel (sec_begin);
3854                                 foreach (SwitchLabel sl in ss.Labels)
3855                                         ig.MarkLabel (sl.ILLabelCode);
3856
3857                                 bool returns = ss.Block.Emit (ec);
3858                                 if (returns)
3859                                         pending_goto_end = false;
3860                                 else {
3861                                         all_return = false;
3862                                         pending_goto_end = true;
3863                                 }
3864                                 first_test = false;
3865                         }
3866                         if (!default_found){
3867                                 ig.MarkLabel (default_target);
3868                                 all_return = false;
3869                         }
3870                         ig.MarkLabel (next_test);
3871                         ig.MarkLabel (end_of_switch);
3872                         
3873                         return all_return;
3874                 }
3875
3876                 public override bool Resolve (EmitContext ec)
3877                 {
3878                         Expr = Expr.Resolve (ec);
3879                         if (Expr == null)
3880                                 return false;
3881
3882                         new_expr = SwitchGoverningType (ec, Expr.Type);
3883                         if (new_expr == null){
3884                                 Report.Error (151, loc, "An integer type or string was expected for switch");
3885                                 return false;
3886                         }
3887
3888                         // Validate switch.
3889                         SwitchType = new_expr.Type;
3890
3891                         if (!CheckSwitch (ec))
3892                                 return false;
3893
3894                         Switch old_switch = ec.Switch;
3895                         ec.Switch = this;
3896                         ec.Switch.SwitchType = SwitchType;
3897
3898                         ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3899
3900                         bool first = true;
3901                         foreach (SwitchSection ss in Sections){
3902                                 if (!first)
3903                                         ec.CurrentBranching.CreateSibling ();
3904                                 else
3905                                         first = false;
3906
3907                                 if (ss.Block.Resolve (ec) != true)
3908                                         return false;
3909                         }
3910
3911
3912                         if (!got_default)
3913                                 ec.CurrentBranching.CreateSibling ();
3914
3915                         ec.EndFlowBranching ();
3916                         ec.Switch = old_switch;
3917
3918                         return true;
3919                 }
3920                 
3921                 protected override bool DoEmit (EmitContext ec)
3922                 {
3923                         // Store variable for comparission purposes
3924                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3925                         new_expr.Emit (ec);
3926                         ec.ig.Emit (OpCodes.Stloc, value);
3927
3928                         ILGenerator ig = ec.ig;
3929
3930                         default_target = ig.DefineLabel ();
3931
3932                         //
3933                         // Setup the codegen context
3934                         //
3935                         Label old_end = ec.LoopEnd;
3936                         Switch old_switch = ec.Switch;
3937                         
3938                         ec.LoopEnd = ig.DefineLabel ();
3939                         ec.Switch = this;
3940
3941                         // Emit Code.
3942                         bool all_return;
3943                         if (SwitchType == TypeManager.string_type)
3944                                 all_return = SimpleSwitchEmit (ec, value);
3945                         else
3946                                 all_return = TableSwitchEmit (ec, value);
3947
3948                         // Restore context state. 
3949                         ig.MarkLabel (ec.LoopEnd);
3950
3951                         //
3952                         // Restore the previous context
3953                         //
3954                         ec.LoopEnd = old_end;
3955                         ec.Switch = old_switch;
3956                         
3957                         return all_return;
3958                 }
3959         }
3960
3961         public class Lock : Statement {
3962                 Expression expr;
3963                 Statement Statement;
3964                         
3965                 public Lock (Expression expr, Statement stmt, Location l)
3966                 {
3967                         this.expr = expr;
3968                         Statement = stmt;
3969                         loc = l;
3970                 }
3971
3972                 public override bool Resolve (EmitContext ec)
3973                 {
3974                         expr = expr.Resolve (ec);
3975                         return Statement.Resolve (ec) && expr != null;
3976                 }
3977                 
3978                 protected override bool DoEmit (EmitContext ec)
3979                 {
3980                         Type type = expr.Type;
3981                         bool val;
3982                         
3983                         if (type.IsValueType){
3984                                 Report.Error (185, loc, "lock statement requires the expression to be " +
3985                                               " a reference type (type is: `" +
3986                                               TypeManager.CSharpName (type) + "'");
3987                                 return false;
3988                         }
3989
3990                         ILGenerator ig = ec.ig;
3991                         LocalBuilder temp = ig.DeclareLocal (type);
3992                                 
3993                         expr.Emit (ec);
3994                         ig.Emit (OpCodes.Dup);
3995                         ig.Emit (OpCodes.Stloc, temp);
3996                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3997
3998                         // try
3999                         Label end = ig.BeginExceptionBlock ();
4000                         bool old_in_try = ec.InTry;
4001                         ec.InTry = true;
4002                         Label finish = ig.DefineLabel ();
4003                         val = Statement.Emit (ec);
4004                         ec.InTry = old_in_try;
4005                         // ig.Emit (OpCodes.Leave, finish);
4006
4007                         ig.MarkLabel (finish);
4008                         
4009                         // finally
4010                         ig.BeginFinallyBlock ();
4011                         ig.Emit (OpCodes.Ldloc, temp);
4012                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4013                         ig.EndExceptionBlock ();
4014                         
4015                         return val;
4016                 }
4017         }
4018
4019         public class Unchecked : Statement {
4020                 public readonly Block Block;
4021                 
4022                 public Unchecked (Block b)
4023                 {
4024                         Block = b;
4025                 }
4026
4027                 public override bool Resolve (EmitContext ec)
4028                 {
4029                         return Block.Resolve (ec);
4030                 }
4031                 
4032                 protected override bool DoEmit (EmitContext ec)
4033                 {
4034                         bool previous_state = ec.CheckState;
4035                         bool previous_state_const = ec.ConstantCheckState;
4036                         bool val;
4037                         
4038                         ec.CheckState = false;
4039                         ec.ConstantCheckState = false;
4040                         val = Block.Emit (ec);
4041                         ec.CheckState = previous_state;
4042                         ec.ConstantCheckState = previous_state_const;
4043
4044                         return val;
4045                 }
4046         }
4047
4048         public class Checked : Statement {
4049                 public readonly Block Block;
4050                 
4051                 public Checked (Block b)
4052                 {
4053                         Block = b;
4054                 }
4055
4056                 public override bool Resolve (EmitContext ec)
4057                 {
4058                         bool previous_state = ec.CheckState;
4059                         bool previous_state_const = ec.ConstantCheckState;
4060                         
4061                         ec.CheckState = true;
4062                         ec.ConstantCheckState = true;
4063                         bool ret = Block.Resolve (ec);
4064                         ec.CheckState = previous_state;
4065                         ec.ConstantCheckState = previous_state_const;
4066
4067                         return ret;
4068                 }
4069
4070                 protected override bool DoEmit (EmitContext ec)
4071                 {
4072                         bool previous_state = ec.CheckState;
4073                         bool previous_state_const = ec.ConstantCheckState;
4074                         bool val;
4075                         
4076                         ec.CheckState = true;
4077                         ec.ConstantCheckState = true;
4078                         val = Block.Emit (ec);
4079                         ec.CheckState = previous_state;
4080                         ec.ConstantCheckState = previous_state_const;
4081
4082                         return val;
4083                 }
4084         }
4085
4086         public class Unsafe : Statement {
4087                 public readonly Block Block;
4088
4089                 public Unsafe (Block b)
4090                 {
4091                         Block = b;
4092                 }
4093
4094                 public override bool Resolve (EmitContext ec)
4095                 {
4096                         bool previous_state = ec.InUnsafe;
4097                         bool val;
4098                         
4099                         ec.InUnsafe = true;
4100                         val = Block.Resolve (ec);
4101                         ec.InUnsafe = previous_state;
4102
4103                         return val;
4104                 }
4105                 
4106                 protected override bool DoEmit (EmitContext ec)
4107                 {
4108                         bool previous_state = ec.InUnsafe;
4109                         bool val;
4110                         
4111                         ec.InUnsafe = true;
4112                         val = Block.Emit (ec);
4113                         ec.InUnsafe = previous_state;
4114
4115                         return val;
4116                 }
4117         }
4118
4119         // 
4120         // Fixed statement
4121         //
4122         public class Fixed : Statement {
4123                 Expression type;
4124                 ArrayList declarators;
4125                 Statement statement;
4126                 Type expr_type;
4127                 FixedData[] data;
4128
4129                 struct FixedData {
4130                         public bool is_object;
4131                         public VariableInfo vi;
4132                         public Expression expr;
4133                         public Expression converted;
4134                 }                       
4135
4136                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4137                 {
4138                         this.type = type;
4139                         declarators = decls;
4140                         statement = stmt;
4141                         loc = l;
4142                 }
4143
4144                 public override bool Resolve (EmitContext ec)
4145                 {
4146                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4147                         if (expr_type == null)
4148                                 return false;
4149
4150                         data = new FixedData [declarators.Count];
4151
4152                         int i = 0;
4153                         foreach (Pair p in declarators){
4154                                 VariableInfo vi = (VariableInfo) p.First;
4155                                 Expression e = (Expression) p.Second;
4156
4157                                 vi.Number = -1;
4158
4159                                 //
4160                                 // The rules for the possible declarators are pretty wise,
4161                                 // but the production on the grammar is more concise.
4162                                 //
4163                                 // So we have to enforce these rules here.
4164                                 //
4165                                 // We do not resolve before doing the case 1 test,
4166                                 // because the grammar is explicit in that the token &
4167                                 // is present, so we need to test for this particular case.
4168                                 //
4169
4170                                 //
4171                                 // Case 1: & object.
4172                                 //
4173                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4174                                         Expression child = ((Unary) e).Expr;
4175
4176                                         vi.MakePinned ();
4177                                         if (child is ParameterReference || child is LocalVariableReference){
4178                                                 Report.Error (
4179                                                         213, loc, 
4180                                                         "No need to use fixed statement for parameters or " +
4181                                                         "local variable declarations (address is already " +
4182                                                         "fixed)");
4183                                                 return false;
4184                                         }
4185                                         
4186                                         e = e.Resolve (ec);
4187                                         if (e == null)
4188                                                 return false;
4189
4190                                         child = ((Unary) e).Expr;
4191                                         
4192                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
4193                                                 return false;
4194
4195                                         data [i].is_object = true;
4196                                         data [i].expr = e;
4197                                         data [i].converted = null;
4198                                         data [i].vi = vi;
4199                                         i++;
4200
4201                                         continue;
4202                                 }
4203
4204                                 e = e.Resolve (ec);
4205                                 if (e == null)
4206                                         return false;
4207
4208                                 //
4209                                 // Case 2: Array
4210                                 //
4211                                 if (e.Type.IsArray){
4212                                         Type array_type = e.Type.GetElementType ();
4213                                         
4214                                         vi.MakePinned ();
4215                                         //
4216                                         // Provided that array_type is unmanaged,
4217                                         //
4218                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
4219                                                 return false;
4220
4221                                         //
4222                                         // and T* is implicitly convertible to the
4223                                         // pointer type given in the fixed statement.
4224                                         //
4225                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
4226                                         
4227                                         Expression converted = Expression.ConvertImplicitRequired (
4228                                                 ec, array_ptr, vi.VariableType, loc);
4229                                         if (converted == null)
4230                                                 return false;
4231
4232                                         data [i].is_object = false;
4233                                         data [i].expr = e;
4234                                         data [i].converted = converted;
4235                                         data [i].vi = vi;
4236                                         i++;
4237
4238                                         continue;
4239                                 }
4240
4241                                 //
4242                                 // Case 3: string
4243                                 //
4244                                 if (e.Type == TypeManager.string_type){
4245                                         data [i].is_object = false;
4246                                         data [i].expr = e;
4247                                         data [i].converted = null;
4248                                         data [i].vi = vi;
4249                                         i++;
4250                                 }
4251                         }
4252
4253                         return statement.Resolve (ec);
4254                 }
4255                 
4256                 protected override bool DoEmit (EmitContext ec)
4257                 {
4258                         ILGenerator ig = ec.ig;
4259
4260                         bool is_ret = false;
4261
4262                         for (int i = 0; i < data.Length; i++) {
4263                                 VariableInfo vi = data [i].vi;
4264
4265                                 //
4266                                 // Case 1: & object.
4267                                 //
4268                                 if (data [i].is_object) {
4269                                         //
4270                                         // Store pointer in pinned location
4271                                         //
4272                                         data [i].expr.Emit (ec);
4273                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4274
4275                                         is_ret = statement.Emit (ec);
4276
4277                                         // Clear the pinned variable.
4278                                         ig.Emit (OpCodes.Ldc_I4_0);
4279                                         ig.Emit (OpCodes.Conv_U);
4280                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4281
4282                                         continue;
4283                                 }
4284
4285                                 //
4286                                 // Case 2: Array
4287                                 //
4288                                 if (data [i].expr.Type.IsArray){
4289                                         //
4290                                         // Store pointer in pinned location
4291                                         //
4292                                         data [i].converted.Emit (ec);
4293                                         
4294                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4295
4296                                         is_ret = statement.Emit (ec);
4297                                         
4298                                         // Clear the pinned variable.
4299                                         ig.Emit (OpCodes.Ldc_I4_0);
4300                                         ig.Emit (OpCodes.Conv_U);
4301                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4302
4303                                         continue;
4304                                 }
4305
4306                                 //
4307                                 // Case 3: string
4308                                 //
4309                                 if (data [i].expr.Type == TypeManager.string_type){
4310                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4311                                         TypeManager.MakePinned (pinned_string);
4312                                         
4313                                         data [i].expr.Emit (ec);
4314                                         ig.Emit (OpCodes.Stloc, pinned_string);
4315
4316                                         Expression sptr = new StringPtr (pinned_string, loc);
4317                                         Expression converted = Expression.ConvertImplicitRequired (
4318                                                 ec, sptr, vi.VariableType, loc);
4319                                         
4320                                         if (converted == null)
4321                                                 continue;
4322
4323                                         converted.Emit (ec);
4324                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4325                                         
4326                                         is_ret = statement.Emit (ec);
4327
4328                                         // Clear the pinned variable
4329                                         ig.Emit (OpCodes.Ldnull);
4330                                         ig.Emit (OpCodes.Stloc, pinned_string);
4331                                 }
4332                         }
4333
4334                         return is_ret;
4335                 }
4336         }
4337         
4338         public class Catch {
4339                 public readonly string Name;
4340                 public readonly Block  Block;
4341                 public readonly Location Location;
4342
4343                 Expression type_expr;
4344                 Type type;
4345                 
4346                 public Catch (Expression type, string name, Block block, Location l)
4347                 {
4348                         type_expr = type;
4349                         Name = name;
4350                         Block = block;
4351                         Location = l;
4352                 }
4353
4354                 public Type CatchType {
4355                         get {
4356                                 return type;
4357                         }
4358                 }
4359
4360                 public bool IsGeneral {
4361                         get {
4362                                 return type_expr == null;
4363                         }
4364                 }
4365
4366                 public bool Resolve (EmitContext ec)
4367                 {
4368                         if (type_expr != null) {
4369                                 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4370                                 if (type == null)
4371                                         return false;
4372
4373                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4374                                         Report.Error (155, Location,
4375                                                       "The type caught or thrown must be derived " +
4376                                                       "from System.Exception");
4377                                         return false;
4378                                 }
4379                         } else
4380                                 type = null;
4381
4382                         if (!Block.Resolve (ec))
4383                                 return false;
4384
4385                         return true;
4386                 }
4387         }
4388
4389         public class Try : Statement {
4390                 public readonly Block Fini, Block;
4391                 public readonly ArrayList Specific;
4392                 public readonly Catch General;
4393                 
4394                 //
4395                 // specific, general and fini might all be null.
4396                 //
4397                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4398                 {
4399                         if (specific == null && general == null){
4400                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4401                         }
4402                         
4403                         this.Block = block;
4404                         this.Specific = specific;
4405                         this.General = general;
4406                         this.Fini = fini;
4407                         loc = l;
4408                 }
4409
4410                 public override bool Resolve (EmitContext ec)
4411                 {
4412                         bool ok = true;
4413                         
4414                         ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4415
4416                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4417
4418                         bool old_in_try = ec.InTry;
4419                         ec.InTry = true;
4420
4421                         if (!Block.Resolve (ec))
4422                                 ok = false;
4423
4424                         ec.InTry = old_in_try;
4425
4426                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4427
4428                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
4429
4430                         foreach (Catch c in Specific){
4431                                 ec.CurrentBranching.CreateSibling ();
4432                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4433
4434                                 if (c.Name != null) {
4435                                         VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4436                                         if (vi == null)
4437                                                 throw new Exception ();
4438
4439                                         vi.Number = -1;
4440                                 }
4441
4442                                 bool old_in_catch = ec.InCatch;
4443                                 ec.InCatch = true;
4444
4445                                 if (!c.Resolve (ec))
4446                                         ok = false;
4447
4448                                 ec.InCatch = old_in_catch;
4449
4450                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4451
4452                                 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4453                                         vector.AndLocals (current);
4454                         }
4455
4456                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4457
4458                         if (General != null){
4459                                 ec.CurrentBranching.CreateSibling ();
4460                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4461
4462                                 bool old_in_catch = ec.InCatch;
4463                                 ec.InCatch = true;
4464
4465                                 if (!General.Resolve (ec))
4466                                         ok = false;
4467
4468                                 ec.InCatch = old_in_catch;
4469
4470                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4471
4472                                 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4473                                         vector.AndLocals (current);
4474                         }
4475
4476                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4477
4478                         if (Fini != null) {
4479                                 ec.CurrentBranching.CreateSiblingForFinally ();
4480                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4481
4482                                 bool old_in_finally = ec.InFinally;
4483                                 ec.InFinally = true;
4484
4485                                 if (!Fini.Resolve (ec))
4486                                         ok = false;
4487
4488                                 ec.InFinally = old_in_finally;
4489                         }
4490
4491                         FlowReturns returns = ec.EndFlowBranching ();
4492
4493                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4494
4495                         Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4496
4497                         if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4498                                 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4499                         }
4500
4501                         ec.CurrentBranching.CurrentUsageVector.Or (vector);
4502
4503                         Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4504
4505                         return ok;
4506                 }
4507                 
4508                 protected override bool DoEmit (EmitContext ec)
4509                 {
4510                         ILGenerator ig = ec.ig;
4511                         Label end;
4512                         Label finish = ig.DefineLabel ();;
4513                         bool returns;
4514
4515                         ec.TryCatchLevel++;
4516                         end = ig.BeginExceptionBlock ();
4517                         bool old_in_try = ec.InTry;
4518                         ec.InTry = true;
4519                         returns = Block.Emit (ec);
4520                         ec.InTry = old_in_try;
4521
4522                         //
4523                         // System.Reflection.Emit provides this automatically:
4524                         // ig.Emit (OpCodes.Leave, finish);
4525
4526                         bool old_in_catch = ec.InCatch;
4527                         ec.InCatch = true;
4528                         DeclSpace ds = ec.DeclSpace;
4529
4530                         foreach (Catch c in Specific){
4531                                 VariableInfo vi;
4532                                 
4533                                 ig.BeginCatchBlock (c.CatchType);
4534
4535                                 if (c.Name != null){
4536                                         vi = c.Block.GetVariableInfo (c.Name);
4537                                         if (vi == null)
4538                                                 throw new Exception ("Variable does not exist in this block");
4539
4540                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4541                                 } else
4542                                         ig.Emit (OpCodes.Pop);
4543                                 
4544                                 if (!c.Block.Emit (ec))
4545                                         returns = false;
4546                         }
4547
4548                         if (General != null){
4549                                 ig.BeginCatchBlock (TypeManager.object_type);
4550                                 ig.Emit (OpCodes.Pop);
4551                                 if (!General.Block.Emit (ec))
4552                                         returns = false;
4553                         }
4554                         ec.InCatch = old_in_catch;
4555
4556                         ig.MarkLabel (finish);
4557                         if (Fini != null){
4558                                 ig.BeginFinallyBlock ();
4559                                 bool old_in_finally = ec.InFinally;
4560                                 ec.InFinally = true;
4561                                 Fini.Emit (ec);
4562                                 ec.InFinally = old_in_finally;
4563                         }
4564                         
4565                         ig.EndExceptionBlock ();
4566                         ec.TryCatchLevel--;
4567
4568                         if (!returns || ec.InTry || ec.InCatch)
4569                                 return returns;
4570
4571                         // Unfortunately, System.Reflection.Emit automatically emits a leave
4572                         // to the end of the finally block.  This is a problem if `returns'
4573                         // is true since we may jump to a point after the end of the method.
4574                         // As a workaround, emit an explicit ret here.
4575
4576                         if (ec.ReturnType != null)
4577                                 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4578                         ec.ig.Emit (OpCodes.Ret);
4579
4580                         return true;
4581                 }
4582         }
4583
4584         public class Using : Statement {
4585                 object expression_or_block;
4586                 Statement Statement;
4587                 ArrayList var_list;
4588                 Expression expr;
4589                 Type expr_type;
4590                 Expression conv;
4591                 Expression [] converted_vars;
4592                 ExpressionStatement [] assign;
4593                 
4594                 public Using (object expression_or_block, Statement stmt, Location l)
4595                 {
4596                         this.expression_or_block = expression_or_block;
4597                         Statement = stmt;
4598                         loc = l;
4599                 }
4600
4601                 //
4602                 // Resolves for the case of using using a local variable declaration.
4603                 //
4604                 bool ResolveLocalVariableDecls (EmitContext ec)
4605                 {
4606                         bool need_conv = false;
4607                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4608                         int i = 0;
4609
4610                         if (expr_type == null)
4611                                 return false;
4612
4613                         //
4614                         // The type must be an IDisposable or an implicit conversion
4615                         // must exist.
4616                         //
4617                         converted_vars = new Expression [var_list.Count];
4618                         assign = new ExpressionStatement [var_list.Count];
4619                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4620                                 foreach (DictionaryEntry e in var_list){
4621                                         Expression var = (Expression) e.Key;
4622
4623                                         var = var.ResolveLValue (ec, new EmptyExpression ());
4624                                         if (var == null)
4625                                                 return false;
4626                                         
4627                                         converted_vars [i] = Expression.ConvertImplicitRequired (
4628                                                 ec, var, TypeManager.idisposable_type, loc);
4629
4630                                         if (converted_vars [i] == null)
4631                                                 return false;
4632                                         i++;
4633                                 }
4634                                 need_conv = true;
4635                         }
4636
4637                         i = 0;
4638                         foreach (DictionaryEntry e in var_list){
4639                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4640                                 Expression new_expr = (Expression) e.Value;
4641                                 Expression a;
4642
4643                                 a = new Assign (var, new_expr, loc);
4644                                 a = a.Resolve (ec);
4645                                 if (a == null)
4646                                         return false;
4647
4648                                 if (!need_conv)
4649                                         converted_vars [i] = var;
4650                                 assign [i] = (ExpressionStatement) a;
4651                                 i++;
4652                         }
4653
4654                         return true;
4655                 }
4656
4657                 bool ResolveExpression (EmitContext ec)
4658                 {
4659                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4660                                 conv = Expression.ConvertImplicitRequired (
4661                                         ec, expr, TypeManager.idisposable_type, loc);
4662
4663                                 if (conv == null)
4664                                         return false;
4665                         }
4666
4667                         return true;
4668                 }
4669                 
4670                 //
4671                 // Emits the code for the case of using using a local variable declaration.
4672                 //
4673                 bool EmitLocalVariableDecls (EmitContext ec)
4674                 {
4675                         ILGenerator ig = ec.ig;
4676                         int i = 0;
4677
4678                         bool old_in_try = ec.InTry;
4679                         ec.InTry = true;
4680                         for (i = 0; i < assign.Length; i++) {
4681                                 assign [i].EmitStatement (ec);
4682                                 
4683                                 ig.BeginExceptionBlock ();
4684                         }
4685                         Statement.Emit (ec);
4686                         ec.InTry = old_in_try;
4687
4688                         bool old_in_finally = ec.InFinally;
4689                         ec.InFinally = true;
4690                         var_list.Reverse ();
4691                         foreach (DictionaryEntry e in var_list){
4692                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4693                                 Label skip = ig.DefineLabel ();
4694                                 i--;
4695                                 
4696                                 ig.BeginFinallyBlock ();
4697                                 
4698                                 var.Emit (ec);
4699                                 ig.Emit (OpCodes.Brfalse, skip);
4700                                 converted_vars [i].Emit (ec);
4701                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4702                                 ig.MarkLabel (skip);
4703                                 ig.EndExceptionBlock ();
4704                         }
4705                         ec.InFinally = old_in_finally;
4706
4707                         return false;
4708                 }
4709
4710                 bool EmitExpression (EmitContext ec)
4711                 {
4712                         //
4713                         // Make a copy of the expression and operate on that.
4714                         //
4715                         ILGenerator ig = ec.ig;
4716                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4717                         if (conv != null)
4718                                 conv.Emit (ec);
4719                         else
4720                                 expr.Emit (ec);
4721                         ig.Emit (OpCodes.Stloc, local_copy);
4722
4723                         bool old_in_try = ec.InTry;
4724                         ec.InTry = true;
4725                         ig.BeginExceptionBlock ();
4726                         Statement.Emit (ec);
4727                         ec.InTry = old_in_try;
4728                         
4729                         Label skip = ig.DefineLabel ();
4730                         bool old_in_finally = ec.InFinally;
4731                         ig.BeginFinallyBlock ();
4732                         ig.Emit (OpCodes.Ldloc, local_copy);
4733                         ig.Emit (OpCodes.Brfalse, skip);
4734                         ig.Emit (OpCodes.Ldloc, local_copy);
4735                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4736                         ig.MarkLabel (skip);
4737                         ec.InFinally = old_in_finally;
4738                         ig.EndExceptionBlock ();
4739
4740                         return false;
4741                 }
4742                 
4743                 public override bool Resolve (EmitContext ec)
4744                 {
4745                         if (expression_or_block is DictionaryEntry){
4746                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4747                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4748
4749                                 if (!ResolveLocalVariableDecls (ec))
4750                                         return false;
4751
4752                         } else if (expression_or_block is Expression){
4753                                 expr = (Expression) expression_or_block;
4754
4755                                 expr = expr.Resolve (ec);
4756                                 if (expr == null)
4757                                         return false;
4758
4759                                 expr_type = expr.Type;
4760
4761                                 if (!ResolveExpression (ec))
4762                                         return false;
4763                         }                       
4764
4765                         return Statement.Resolve (ec);
4766                 }
4767                 
4768                 protected override bool DoEmit (EmitContext ec)
4769                 {
4770                         if (expression_or_block is DictionaryEntry)
4771                                 return EmitLocalVariableDecls (ec);
4772                         else if (expression_or_block is Expression)
4773                                 return EmitExpression (ec);
4774
4775                         return false;
4776                 }
4777         }
4778
4779         /// <summary>
4780         ///   Implementation of the foreach C# statement
4781         /// </summary>
4782         public class Foreach : Statement {
4783                 Expression type;
4784                 LocalVariableReference variable;
4785                 Expression expr;
4786                 Statement statement;
4787                 ForeachHelperMethods hm;
4788                 Expression empty, conv;
4789                 Type array_type, element_type;
4790                 Type var_type;
4791                 
4792                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4793                                 Statement stmt, Location l)
4794                 {
4795                         this.type = type;
4796                         this.variable = var;
4797                         this.expr = expr;
4798                         statement = stmt;
4799                         loc = l;
4800                 }
4801                 
4802                 public override bool Resolve (EmitContext ec)
4803                 {
4804                         expr = expr.Resolve (ec);
4805                         if (expr == null)
4806                                 return false;
4807
4808                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
4809                         if (var_type == null)
4810                                 return false;
4811                         
4812                         //
4813                         // We need an instance variable.  Not sure this is the best
4814                         // way of doing this.
4815                         //
4816                         // FIXME: When we implement propertyaccess, will those turn
4817                         // out to return values in ExprClass?  I think they should.
4818                         //
4819                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4820                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4821                                 error1579 (expr.Type);
4822                                 return false;
4823                         }
4824
4825                         if (expr.Type.IsArray) {
4826                                 array_type = expr.Type;
4827                                 element_type = array_type.GetElementType ();
4828
4829                                 empty = new EmptyExpression (element_type);
4830                         } else {
4831                                 hm = ProbeCollectionType (ec, expr.Type);
4832                                 if (hm == null){
4833                                         error1579 (expr.Type);
4834                                         return false;
4835                                 }
4836
4837                                 array_type = expr.Type;
4838                                 element_type = hm.element_type;
4839
4840                                 empty = new EmptyExpression (hm.element_type);
4841                         }
4842
4843                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4844                         ec.CurrentBranching.CreateSibling ();
4845
4846                         //
4847                         //
4848                         // FIXME: maybe we can apply the same trick we do in the
4849                         // array handling to avoid creating empty and conv in some cases.
4850                         //
4851                         // Although it is not as important in this case, as the type
4852                         // will not likely be object (what the enumerator will return).
4853                         //
4854                         conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4855                         if (conv == null)
4856                                 return false;
4857
4858                         if (variable.ResolveLValue (ec, empty) == null)
4859                                 return false;
4860
4861                         if (!statement.Resolve (ec))
4862                                 return false;
4863
4864                         FlowReturns returns = ec.EndFlowBranching ();
4865
4866                         return true;
4867                 }
4868                 
4869                 //
4870                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4871                 //
4872                 static MethodInfo FetchMethodMoveNext (Type t)
4873                 {
4874                         MemberList move_next_list;
4875                         
4876                         move_next_list = TypeContainer.FindMembers (
4877                                 t, MemberTypes.Method,
4878                                 BindingFlags.Public | BindingFlags.Instance,
4879                                 Type.FilterName, "MoveNext");
4880                         if (move_next_list.Count == 0)
4881                                 return null;
4882
4883                         foreach (MemberInfo m in move_next_list){
4884                                 MethodInfo mi = (MethodInfo) m;
4885                                 Type [] args;
4886                                 
4887                                 args = TypeManager.GetArgumentTypes (mi);
4888                                 if (args != null && args.Length == 0){
4889                                         if (mi.ReturnType == TypeManager.bool_type)
4890                                                 return mi;
4891                                 }
4892                         }
4893                         return null;
4894                 }
4895                 
4896                 //
4897                 // Retrieves a `public T get_Current ()' method from the Type `t'
4898                 //
4899                 static MethodInfo FetchMethodGetCurrent (Type t)
4900                 {
4901                         MemberList move_next_list;
4902                         
4903                         move_next_list = TypeContainer.FindMembers (
4904                                 t, MemberTypes.Method,
4905                                 BindingFlags.Public | BindingFlags.Instance,
4906                                 Type.FilterName, "get_Current");
4907                         if (move_next_list.Count == 0)
4908                                 return null;
4909
4910                         foreach (MemberInfo m in move_next_list){
4911                                 MethodInfo mi = (MethodInfo) m;
4912                                 Type [] args;
4913
4914                                 args = TypeManager.GetArgumentTypes (mi);
4915                                 if (args != null && args.Length == 0)
4916                                         return mi;
4917                         }
4918                         return null;
4919                 }
4920
4921                 // 
4922                 // This struct records the helper methods used by the Foreach construct
4923                 //
4924                 class ForeachHelperMethods {
4925                         public EmitContext ec;
4926                         public MethodInfo get_enumerator;
4927                         public MethodInfo move_next;
4928                         public MethodInfo get_current;
4929                         public Type element_type;
4930                         public Type enumerator_type;
4931                         public bool is_disposable;
4932
4933                         public ForeachHelperMethods (EmitContext ec)
4934                         {
4935                                 this.ec = ec;
4936                                 this.element_type = TypeManager.object_type;
4937                                 this.enumerator_type = TypeManager.ienumerator_type;
4938                                 this.is_disposable = true;
4939                         }
4940                 }
4941                 
4942                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4943                 {
4944                         if (m == null)
4945                                 return false;
4946                         
4947                         if (!(m is MethodInfo))
4948                                 return false;
4949                         
4950                         if (m.Name != "GetEnumerator")
4951                                 return false;
4952
4953                         MethodInfo mi = (MethodInfo) m;
4954                         Type [] args = TypeManager.GetArgumentTypes (mi);
4955                         if (args != null){
4956                                 if (args.Length != 0)
4957                                         return false;
4958                         }
4959                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4960                         EmitContext ec = hm.ec;
4961
4962                         //
4963                         // Check whether GetEnumerator is accessible to us
4964                         //
4965                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4966
4967                         Type declaring = mi.DeclaringType;
4968                         if (prot == MethodAttributes.Private){
4969                                 if (declaring != ec.ContainerType)
4970                                         return false;
4971                         } else if (prot == MethodAttributes.FamANDAssem){
4972                                 // If from a different assembly, false
4973                                 if (!(mi is MethodBuilder))
4974                                         return false;
4975                                 //
4976                                 // Are we being invoked from the same class, or from a derived method?
4977                                 //
4978                                 if (ec.ContainerType != declaring){
4979                                         if (!ec.ContainerType.IsSubclassOf (declaring))
4980                                                 return false;
4981                                 }
4982                         } else if (prot == MethodAttributes.FamORAssem){
4983                                 if (!(mi is MethodBuilder ||
4984                                       ec.ContainerType == declaring ||
4985                                       ec.ContainerType.IsSubclassOf (declaring)))
4986                                         return false;
4987                         } if (prot == MethodAttributes.Family){
4988                                 if (!(ec.ContainerType == declaring ||
4989                                       ec.ContainerType.IsSubclassOf (declaring)))
4990                                         return false;
4991                         }
4992
4993                         //
4994                         // Ok, we can access it, now make sure that we can do something
4995                         // with this `GetEnumerator'
4996                         //
4997
4998                         if (mi.ReturnType == TypeManager.ienumerator_type ||
4999                             TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5000                             (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5001                                 hm.move_next = TypeManager.bool_movenext_void;
5002                                 hm.get_current = TypeManager.object_getcurrent_void;
5003                                 return true;
5004                         }
5005
5006                         //
5007                         // Ok, so they dont return an IEnumerable, we will have to
5008                         // find if they support the GetEnumerator pattern.
5009                         //
5010                         Type return_type = mi.ReturnType;
5011
5012                         hm.move_next = FetchMethodMoveNext (return_type);
5013                         if (hm.move_next == null)
5014                                 return false;
5015                         hm.get_current = FetchMethodGetCurrent (return_type);
5016                         if (hm.get_current == null)
5017                                 return false;
5018
5019                         hm.element_type = hm.get_current.ReturnType;
5020                         hm.enumerator_type = return_type;
5021                         hm.is_disposable = TypeManager.ImplementsInterface (
5022                                 hm.enumerator_type, TypeManager.idisposable_type);
5023
5024                         return true;
5025                 }
5026                 
5027                 /// <summary>
5028                 ///   This filter is used to find the GetEnumerator method
5029                 ///   on which IEnumerator operates
5030                 /// </summary>
5031                 static MemberFilter FilterEnumerator;
5032                 
5033                 static Foreach ()
5034                 {
5035                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5036                 }
5037
5038                 void error1579 (Type t)
5039                 {
5040                         Report.Error (1579, loc,
5041                                       "foreach statement cannot operate on variables of type `" +
5042                                       t.FullName + "' because that class does not provide a " +
5043                                       " GetEnumerator method or it is inaccessible");
5044                 }
5045
5046                 static bool TryType (Type t, ForeachHelperMethods hm)
5047                 {
5048                         MemberList mi;
5049                         
5050                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5051                                                         BindingFlags.Public | BindingFlags.NonPublic |
5052                                                         BindingFlags.Instance,
5053                                                         FilterEnumerator, hm);
5054
5055                         if (mi.Count == 0)
5056                                 return false;
5057
5058                         hm.get_enumerator = (MethodInfo) mi [0];
5059                         return true;    
5060                 }
5061                 
5062                 //
5063                 // Looks for a usable GetEnumerator in the Type, and if found returns
5064                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5065                 //
5066                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5067                 {
5068                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5069
5070                         if (TryType (t, hm))
5071                                 return hm;
5072
5073                         //
5074                         // Now try to find the method in the interfaces
5075                         //
5076                         while (t != null){
5077                                 Type [] ifaces = t.GetInterfaces ();
5078
5079                                 foreach (Type i in ifaces){
5080                                         if (TryType (i, hm))
5081                                                 return hm;
5082                                 }
5083                                 
5084                                 //
5085                                 // Since TypeBuilder.GetInterfaces only returns the interface
5086                                 // types for this type, we have to keep looping, but once
5087                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5088                                 // done, because it returns all the types
5089                                 //
5090                                 if ((t is TypeBuilder))
5091                                         t = t.BaseType;
5092                                 else
5093                                         break;
5094                         } 
5095
5096                         return null;
5097                 }
5098
5099                 //
5100                 // FIXME: possible optimization.
5101                 // We might be able to avoid creating `empty' if the type is the sam
5102                 //
5103                 bool EmitCollectionForeach (EmitContext ec)
5104                 {
5105                         ILGenerator ig = ec.ig;
5106                         LocalBuilder enumerator, disposable;
5107
5108                         enumerator = ig.DeclareLocal (hm.enumerator_type);
5109                         if (hm.is_disposable)
5110                                 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5111                         else
5112                                 disposable = null;
5113                         
5114                         //
5115                         // Instantiate the enumerator
5116                         //
5117                         if (expr.Type.IsValueType){
5118                                 if (expr is IMemoryLocation){
5119                                         IMemoryLocation ml = (IMemoryLocation) expr;
5120
5121                                         ml.AddressOf (ec, AddressOp.Load);
5122                                 } else
5123                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
5124                                                              " does not implement IMemoryLocation");
5125                                 ig.Emit (OpCodes.Call, hm.get_enumerator);
5126                         } else {
5127                                 expr.Emit (ec);
5128                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5129                         }
5130                         ig.Emit (OpCodes.Stloc, enumerator);
5131
5132                         //
5133                         // Protect the code in a try/finalize block, so that
5134                         // if the beast implement IDisposable, we get rid of it
5135                         //
5136                         Label l;
5137                         bool old_in_try = ec.InTry;
5138
5139                         if (hm.is_disposable) {
5140                                 l = ig.BeginExceptionBlock ();
5141                                 ec.InTry = true;
5142                         }
5143                         
5144                         Label end_try = ig.DefineLabel ();
5145                         
5146                         ig.MarkLabel (ec.LoopBegin);
5147                         ig.Emit (OpCodes.Ldloc, enumerator);
5148                         ig.Emit (OpCodes.Callvirt, hm.move_next);
5149                         ig.Emit (OpCodes.Brfalse, end_try);
5150                         ig.Emit (OpCodes.Ldloc, enumerator);
5151                         ig.Emit (OpCodes.Callvirt, hm.get_current);
5152                         variable.EmitAssign (ec, conv);
5153                         statement.Emit (ec);
5154                         ig.Emit (OpCodes.Br, ec.LoopBegin);
5155                         ig.MarkLabel (end_try);
5156                         ec.InTry = old_in_try;
5157                         
5158                         // The runtime provides this for us.
5159                         // ig.Emit (OpCodes.Leave, end);
5160
5161                         //
5162                         // Now the finally block
5163                         //
5164                         if (hm.is_disposable) {
5165                                 Label end_finally = ig.DefineLabel ();
5166                                 bool old_in_finally = ec.InFinally;
5167                                 ec.InFinally = true;
5168                                 ig.BeginFinallyBlock ();
5169                         
5170                                 ig.Emit (OpCodes.Ldloc, enumerator);
5171                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5172                                 ig.Emit (OpCodes.Stloc, disposable);
5173                                 ig.Emit (OpCodes.Ldloc, disposable);
5174                                 ig.Emit (OpCodes.Brfalse, end_finally);
5175                                 ig.Emit (OpCodes.Ldloc, disposable);
5176                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5177                                 ig.MarkLabel (end_finally);
5178                                 ec.InFinally = old_in_finally;
5179
5180                                 // The runtime generates this anyways.
5181                                 // ig.Emit (OpCodes.Endfinally);
5182
5183                                 ig.EndExceptionBlock ();
5184                         }
5185
5186                         ig.MarkLabel (ec.LoopEnd);
5187                         return false;
5188                 }
5189
5190                 //
5191                 // FIXME: possible optimization.
5192                 // We might be able to avoid creating `empty' if the type is the sam
5193                 //
5194                 bool EmitArrayForeach (EmitContext ec)
5195                 {
5196                         int rank = array_type.GetArrayRank ();
5197                         ILGenerator ig = ec.ig;
5198
5199                         LocalBuilder copy = ig.DeclareLocal (array_type);
5200                         
5201                         //
5202                         // Make our copy of the array
5203                         //
5204                         expr.Emit (ec);
5205                         ig.Emit (OpCodes.Stloc, copy);
5206                         
5207                         if (rank == 1){
5208                                 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5209
5210                                 Label loop, test;
5211                                 
5212                                 ig.Emit (OpCodes.Ldc_I4_0);
5213                                 ig.Emit (OpCodes.Stloc, counter);
5214                                 test = ig.DefineLabel ();
5215                                 ig.Emit (OpCodes.Br, test);
5216
5217                                 loop = ig.DefineLabel ();
5218                                 ig.MarkLabel (loop);
5219
5220                                 ig.Emit (OpCodes.Ldloc, copy);
5221                                 ig.Emit (OpCodes.Ldloc, counter);
5222                                 ArrayAccess.EmitLoadOpcode (ig, var_type);
5223
5224                                 variable.EmitAssign (ec, conv);
5225
5226                                 statement.Emit (ec);
5227
5228                                 ig.MarkLabel (ec.LoopBegin);
5229                                 ig.Emit (OpCodes.Ldloc, counter);
5230                                 ig.Emit (OpCodes.Ldc_I4_1);
5231                                 ig.Emit (OpCodes.Add);
5232                                 ig.Emit (OpCodes.Stloc, counter);
5233
5234                                 ig.MarkLabel (test);
5235                                 ig.Emit (OpCodes.Ldloc, counter);
5236                                 ig.Emit (OpCodes.Ldloc, copy);
5237                                 ig.Emit (OpCodes.Ldlen);
5238                                 ig.Emit (OpCodes.Conv_I4);
5239                                 ig.Emit (OpCodes.Blt, loop);
5240                         } else {
5241                                 LocalBuilder [] dim_len   = new LocalBuilder [rank];
5242                                 LocalBuilder [] dim_count = new LocalBuilder [rank];
5243                                 Label [] loop = new Label [rank];
5244                                 Label [] test = new Label [rank];
5245                                 int dim;
5246                                 
5247                                 for (dim = 0; dim < rank; dim++){
5248                                         dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5249                                         dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5250                                         test [dim] = ig.DefineLabel ();
5251                                         loop [dim] = ig.DefineLabel ();
5252                                 }
5253                                         
5254                                 for (dim = 0; dim < rank; dim++){
5255                                         ig.Emit (OpCodes.Ldloc, copy);
5256                                         IntLiteral.EmitInt (ig, dim);
5257                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5258                                         ig.Emit (OpCodes.Stloc, dim_len [dim]);
5259                                 }
5260
5261                                 for (dim = 0; dim < rank; dim++){
5262                                         ig.Emit (OpCodes.Ldc_I4_0);
5263                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
5264                                         ig.Emit (OpCodes.Br, test [dim]);
5265                                         ig.MarkLabel (loop [dim]);
5266                                 }
5267
5268                                 ig.Emit (OpCodes.Ldloc, copy);
5269                                 for (dim = 0; dim < rank; dim++)
5270                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5271
5272                                 //
5273                                 // FIXME: Maybe we can cache the computation of `get'?
5274                                 //
5275                                 Type [] args = new Type [rank];
5276                                 MethodInfo get;
5277
5278                                 for (int i = 0; i < rank; i++)
5279                                         args [i] = TypeManager.int32_type;
5280
5281                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
5282                                 get = mb.GetArrayMethod (
5283                                         array_type, "Get",
5284                                         CallingConventions.HasThis| CallingConventions.Standard,
5285                                         var_type, args);
5286                                 ig.Emit (OpCodes.Call, get);
5287                                 variable.EmitAssign (ec, conv);
5288                                 statement.Emit (ec);
5289                                 ig.MarkLabel (ec.LoopBegin);
5290                                 for (dim = rank - 1; dim >= 0; dim--){
5291                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5292                                         ig.Emit (OpCodes.Ldc_I4_1);
5293                                         ig.Emit (OpCodes.Add);
5294                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
5295
5296                                         ig.MarkLabel (test [dim]);
5297                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5298                                         ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5299                                         ig.Emit (OpCodes.Blt, loop [dim]);
5300                                 }
5301                         }
5302                         ig.MarkLabel (ec.LoopEnd);
5303                         
5304                         return false;
5305                 }
5306                 
5307                 protected override bool DoEmit (EmitContext ec)
5308                 {
5309                         bool ret_val;
5310                         
5311                         ILGenerator ig = ec.ig;
5312                         
5313                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5314                         bool old_inloop = ec.InLoop;
5315                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5316                         ec.LoopBegin = ig.DefineLabel ();
5317                         ec.LoopEnd = ig.DefineLabel ();
5318                         ec.InLoop = true;
5319                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5320                         
5321                         if (hm != null)
5322                                 ret_val = EmitCollectionForeach (ec);
5323                         else
5324                                 ret_val = EmitArrayForeach (ec);
5325                         
5326                         ec.LoopBegin = old_begin;
5327                         ec.LoopEnd = old_end;
5328                         ec.InLoop = old_inloop;
5329                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5330
5331                         return ret_val;
5332                 }
5333         }
5334 }