2004-05-27 Umadevi S <sumadevi@novell.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, 2003 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                 /// <summary>
25                 ///   Resolves the statement, true means that all sub-statements
26                 ///   did resolve ok.
27                 //  </summary>
28                 public virtual bool Resolve (EmitContext ec)
29                 {
30                         return true;
31                 }
32
33                 /// <summary>
34                 ///   We already know that the statement is unreachable, but we still
35                 ///   need to resolve it to catch errors.
36                 /// </summary>
37                 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
38                 {
39                         //
40                         // This conflicts with csc's way of doing this, but IMHO it's
41                         // the right thing to do.
42                         //
43                         // If something is unreachable, we still check whether it's
44                         // correct.  This means that you cannot use unassigned variables
45                         // in unreachable code, for instance.
46                         //
47
48                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
49                         bool ok = Resolve (ec);
50                         ec.KillFlowBranching ();
51
52                         if (!ok)
53                                 return false;
54
55                         if (warn)
56                                 Report.Warning (162, loc, "Unreachable code detected");
57                         return true;
58                 }
59                 
60                 /// <summary>
61                 ///   Return value indicates whether all code paths emitted return.
62                 /// </summary>
63                 protected abstract void DoEmit (EmitContext ec);
64
65                 /// <summary>
66                 ///   Utility wrapper routine for Error, just to beautify the code
67                 /// </summary>
68                 public void Error (int error, string format, params object[] args)
69                 {
70                         Error (error, String.Format (format, args));
71                 }
72
73                 public void Error (int error, string s)
74                 {
75                         if (!Location.IsNull (loc))
76                                 Report.Error (error, loc, s);
77                         else
78                                 Report.Error (error, s);
79                 }
80
81                 /// <summary>
82                 ///   Return value indicates whether all code paths emitted return.
83                 /// </summary>
84                 public virtual void Emit (EmitContext ec)
85                 {
86                         ec.Mark (loc, true);
87                         DoEmit (ec);
88                 }               
89         }
90
91         public sealed class EmptyStatement : Statement {
92                 
93                 private EmptyStatement () {}
94                 
95                 public static readonly EmptyStatement Value = new EmptyStatement ();
96                 
97                 public override bool Resolve (EmitContext ec)
98                 {
99                         return true;
100                 }
101                 
102                 protected override void DoEmit (EmitContext ec)
103                 {
104                 }
105         }
106         
107         public class If : Statement {
108                 Expression expr;
109                 public Statement TrueStatement;
110                 public Statement FalseStatement;
111
112                 bool is_true_ret;
113                 
114                 public If (Expression expr, Statement trueStatement, Location l)
115                 {
116                         this.expr = expr;
117                         TrueStatement = trueStatement;
118                         loc = l;
119                 }
120
121                 public If (Expression expr,
122                            Statement trueStatement,
123                            Statement falseStatement,
124                            Location l)
125                 {
126                         this.expr = expr;
127                         TrueStatement = trueStatement;
128                         FalseStatement = falseStatement;
129                         loc = l;
130                 }
131
132                 public override bool Resolve (EmitContext ec)
133                 {
134                         Report.Debug (1, "START IF BLOCK", loc);
135
136                         expr = Expression.ResolveBoolean (ec, expr, loc);
137                         if (expr == null){
138                                 return false;
139                         }
140
141                         //
142                         // Dead code elimination
143                         //
144                         if (expr is BoolConstant){
145                                 bool take = ((BoolConstant) expr).Value;
146
147                                 if (take){
148                                         if (!TrueStatement.Resolve (ec))
149                                                 return false;
150
151                                         if ((FalseStatement != null) &&
152                                             !FalseStatement.ResolveUnreachable (ec, true))
153                                                 return false;
154                                         FalseStatement = null;
155                                 } else {
156                                         if (!TrueStatement.ResolveUnreachable (ec, true))
157                                                 return false;
158                                         TrueStatement = null;
159
160                                         if ((FalseStatement != null) &&
161                                             !FalseStatement.Resolve (ec))
162                                                 return false;
163                                 }
164
165                                 return true;
166                         }
167                         
168                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
169                         
170                         bool ok = TrueStatement.Resolve (ec);
171
172                         is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
173
174                         ec.CurrentBranching.CreateSibling ();
175
176                         if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
177                                 ok = false;
178                                         
179                         ec.EndFlowBranching ();
180
181                         Report.Debug (1, "END IF BLOCK", loc);
182
183                         return ok;
184                 }
185                 
186                 protected override void DoEmit (EmitContext ec)
187                 {
188                         ILGenerator ig = ec.ig;
189                         Label false_target = ig.DefineLabel ();
190                         Label end;
191
192                         //
193                         // If we're a boolean expression, Resolve() already
194                         // eliminated dead code for us.
195                         //
196                         if (expr is BoolConstant){
197                                 bool take = ((BoolConstant) expr).Value;
198
199                                 if (take)
200                                         TrueStatement.Emit (ec);
201                                 else if (FalseStatement != null)
202                                         FalseStatement.Emit (ec);
203
204                                 return;
205                         }
206                         
207                         expr.EmitBranchable (ec, false_target, false);
208                         
209                         TrueStatement.Emit (ec);
210
211                         if (FalseStatement != null){
212                                 bool branch_emitted = false;
213                                 
214                                 end = ig.DefineLabel ();
215                                 if (!is_true_ret){
216                                         ig.Emit (OpCodes.Br, end);
217                                         branch_emitted = true;
218                                 }
219
220                                 ig.MarkLabel (false_target);
221                                 FalseStatement.Emit (ec);
222
223                                 if (branch_emitted)
224                                         ig.MarkLabel (end);
225                         } else {
226                                 ig.MarkLabel (false_target);
227                         }
228                 }
229         }
230
231         public class Do : Statement {
232                 public Expression expr;
233                 public readonly Statement  EmbeddedStatement;
234                 bool infinite;
235                 
236                 public Do (Statement statement, Expression boolExpr, Location l)
237                 {
238                         expr = boolExpr;
239                         EmbeddedStatement = statement;
240                         loc = l;
241                 }
242
243                 public override bool Resolve (EmitContext ec)
244                 {
245                         bool ok = true;
246
247                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
248
249                         if (!EmbeddedStatement.Resolve (ec))
250                                 ok = false;
251
252                         expr = Expression.ResolveBoolean (ec, expr, loc);
253                         if (expr == null)
254                                 ok = false;
255                         else if (expr is BoolConstant){
256                                 bool res = ((BoolConstant) expr).Value;
257
258                                 if (res)
259                                         infinite = true;
260                         }
261
262                         ec.CurrentBranching.Infinite = infinite;
263                         ec.EndFlowBranching ();
264
265                         return ok;
266                 }
267                 
268                 protected override void DoEmit (EmitContext ec)
269                 {
270                         ILGenerator ig = ec.ig;
271                         Label loop = ig.DefineLabel ();
272                         Label old_begin = ec.LoopBegin;
273                         Label old_end = ec.LoopEnd;
274                         
275                         ec.LoopBegin = ig.DefineLabel ();
276                         ec.LoopEnd = ig.DefineLabel ();
277                                 
278                         ig.MarkLabel (loop);
279                         EmbeddedStatement.Emit (ec);
280                         ig.MarkLabel (ec.LoopBegin);
281
282                         //
283                         // Dead code elimination
284                         //
285                         if (expr is BoolConstant){
286                                 bool res = ((BoolConstant) expr).Value;
287
288                                 if (res)
289                                         ec.ig.Emit (OpCodes.Br, loop); 
290                         } else
291                                 expr.EmitBranchable (ec, loop, true);
292                         
293                         ig.MarkLabel (ec.LoopEnd);
294
295                         ec.LoopBegin = old_begin;
296                         ec.LoopEnd = old_end;
297                 }
298         }
299
300         public class While : Statement {
301                 public Expression expr;
302                 public readonly Statement Statement;
303                 bool infinite, empty;
304                 
305                 public While (Expression boolExpr, Statement statement, Location l)
306                 {
307                         this.expr = boolExpr;
308                         Statement = statement;
309                         loc = l;
310                 }
311
312                 public override bool Resolve (EmitContext ec)
313                 {
314                         bool ok = true;
315
316                         expr = Expression.ResolveBoolean (ec, expr, loc);
317                         if (expr == null)
318                                 return false;
319
320                         //
321                         // Inform whether we are infinite or not
322                         //
323                         if (expr is BoolConstant){
324                                 BoolConstant bc = (BoolConstant) expr;
325
326                                 if (bc.Value == false){
327                                         if (!Statement.ResolveUnreachable (ec, true))
328                                                 return false;
329                                         empty = true;
330                                         return true;
331                                 } else
332                                         infinite = true;
333                         }
334
335                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
336
337                         if (!Statement.Resolve (ec))
338                                 ok = false;
339
340                         ec.CurrentBranching.Infinite = infinite;
341                         ec.EndFlowBranching ();
342
343                         return ok;
344                 }
345                 
346                 protected override void DoEmit (EmitContext ec)
347                 {
348                         if (empty)
349                                 return;
350
351                         ILGenerator ig = ec.ig;
352                         Label old_begin = ec.LoopBegin;
353                         Label old_end = ec.LoopEnd;
354                         
355                         ec.LoopBegin = ig.DefineLabel ();
356                         ec.LoopEnd = ig.DefineLabel ();
357
358                         //
359                         // Inform whether we are infinite or not
360                         //
361                         if (expr is BoolConstant){
362                                 ig.MarkLabel (ec.LoopBegin);
363                                 Statement.Emit (ec);
364                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
365                                         
366                                 //
367                                 // Inform that we are infinite (ie, `we return'), only
368                                 // if we do not `break' inside the code.
369                                 //
370                                 ig.MarkLabel (ec.LoopEnd);
371                         } else {
372                                 Label while_loop = ig.DefineLabel ();
373
374                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
375                                 ig.MarkLabel (while_loop);
376
377                                 Statement.Emit (ec);
378                         
379                                 ig.MarkLabel (ec.LoopBegin);
380
381                                 expr.EmitBranchable (ec, while_loop, true);
382                                 
383                                 ig.MarkLabel (ec.LoopEnd);
384                         }       
385
386                         ec.LoopBegin = old_begin;
387                         ec.LoopEnd = old_end;
388                 }
389         }
390
391         public class For : Statement {
392                 Expression Test;
393                 readonly Statement InitStatement;
394                 readonly Statement Increment;
395                 readonly Statement Statement;
396                 bool infinite, empty;
397                 
398                 public For (Statement initStatement,
399                             Expression test,
400                             Statement increment,
401                             Statement statement,
402                             Location l)
403                 {
404                         InitStatement = initStatement;
405                         Test = test;
406                         Increment = increment;
407                         Statement = statement;
408                         loc = l;
409                 }
410
411                 public override bool Resolve (EmitContext ec)
412                 {
413                         bool ok = true;
414
415                         if (InitStatement != null){
416                                 if (!InitStatement.Resolve (ec))
417                                         ok = false;
418                         }
419
420                         if (Test != null){
421                                 Test = Expression.ResolveBoolean (ec, Test, loc);
422                                 if (Test == null)
423                                         ok = false;
424                                 else if (Test is BoolConstant){
425                                         BoolConstant bc = (BoolConstant) Test;
426
427                                         if (bc.Value == false){
428                                                 if (!Statement.ResolveUnreachable (ec, true))
429                                                         return false;
430                                                 if ((Increment != null) &&
431                                                     !Increment.ResolveUnreachable (ec, false))
432                                                         return false;
433                                                 empty = true;
434                                                 return true;
435                                         } else
436                                                 infinite = true;
437                                 }
438                         } else
439                                 infinite = true;
440
441                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
442                         if (!infinite)
443                                 ec.CurrentBranching.CreateSibling ();
444
445                         if (!Statement.Resolve (ec))
446                                 ok = false;
447
448                         if (Increment != null){
449                                 if (!Increment.Resolve (ec))
450                                         ok = false;
451                         }
452
453                         ec.CurrentBranching.Infinite = infinite;
454                         ec.EndFlowBranching ();
455
456                         return ok;
457                 }
458                 
459                 protected override void DoEmit (EmitContext ec)
460                 {
461                         if (empty)
462                                 return;
463
464                         ILGenerator ig = ec.ig;
465                         Label old_begin = ec.LoopBegin;
466                         Label old_end = ec.LoopEnd;
467                         Label loop = ig.DefineLabel ();
468                         Label test = ig.DefineLabel ();
469                         
470                         if (InitStatement != null && InitStatement != EmptyStatement.Value)
471                                 InitStatement.Emit (ec);
472
473                         ec.LoopBegin = ig.DefineLabel ();
474                         ec.LoopEnd = ig.DefineLabel ();
475
476                         ig.Emit (OpCodes.Br, test);
477                         ig.MarkLabel (loop);
478                         Statement.Emit (ec);
479
480                         ig.MarkLabel (ec.LoopBegin);
481                         if (Increment != EmptyStatement.Value)
482                                 Increment.Emit (ec);
483
484                         ig.MarkLabel (test);
485                         //
486                         // If test is null, there is no test, and we are just
487                         // an infinite loop
488                         //
489                         if (Test != null){
490                                 //
491                                 // The Resolve code already catches the case for
492                                 // Test == BoolConstant (false) so we know that
493                                 // this is true
494                                 //
495                                 if (Test is BoolConstant)
496                                         ig.Emit (OpCodes.Br, loop);
497                                 else
498                                         Test.EmitBranchable (ec, loop, true);
499                                 
500                         } else
501                                 ig.Emit (OpCodes.Br, loop);
502                         ig.MarkLabel (ec.LoopEnd);
503
504                         ec.LoopBegin = old_begin;
505                         ec.LoopEnd = old_end;
506                 }
507         }
508         
509         public class StatementExpression : Statement {
510                 ExpressionStatement expr;
511                 
512                 public StatementExpression (ExpressionStatement expr, Location l)
513                 {
514                         this.expr = expr;
515                         loc = l;
516                 }
517
518                 public override bool Resolve (EmitContext ec)
519                 {
520                         expr = expr.ResolveStatement (ec);
521                         return expr != null;
522                 }
523                 
524                 protected override void DoEmit (EmitContext ec)
525                 {
526                         expr.EmitStatement (ec);
527                 }
528
529                 public override string ToString ()
530                 {
531                         return "StatementExpression (" + expr + ")";
532                 }
533         }
534
535         /// <summary>
536         ///   Implements the return statement
537         /// </summary>
538         public class Return : Statement {
539                 public Expression Expr;
540                 
541                 public Return (Expression expr, Location l)
542                 {
543                         Expr = expr;
544                         loc = l;
545                 }
546
547                 bool in_exc;
548
549                 public override bool Resolve (EmitContext ec)
550                 {
551                         if (ec.ReturnType == null){
552                                 if (Expr != null){
553                                         Error (127, "Return with a value not allowed here");
554                                         return false;
555                                 }
556                         } else {
557                                 if (Expr == null){
558                                         Error (126, "An object of type `{0}' is expected " +
559                                                "for the return statement",
560                                                TypeManager.CSharpName (ec.ReturnType));
561                                         return false;
562                                 }
563
564                                 Expr = Expr.Resolve (ec);
565                                 if (Expr == null)
566                                         return false;
567
568                                 if (Expr.Type != ec.ReturnType) {
569                                         Expr = Convert.ImplicitConversionRequired (
570                                                 ec, Expr, ec.ReturnType, loc);
571                                         if (Expr == null)
572                                                 return false;
573                                 }
574                         }
575
576                         if (ec.InIterator){
577                                 Error (-206, "Return statement not allowed inside iterators");
578                                 return false;
579                         }
580                                 
581                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
582
583                         if (ec.CurrentBranching.InTryOrCatch (true)) {
584                                 ec.CurrentBranching.AddFinallyVector (vector);
585                                 in_exc = true;
586                         } else if (ec.CurrentBranching.InFinally (true)) {
587                                 Error (157, "Control can not leave the body of the finally block");
588                                 return false;
589                         } else
590                                 vector.CheckOutParameters (ec.CurrentBranching);
591
592                         ec.CurrentBranching.CurrentUsageVector.Return ();
593                         return true;
594                 }
595                 
596                 protected override void DoEmit (EmitContext ec)
597                 {
598                         if (Expr != null) {
599                                 Expr.Emit (ec);
600
601                                 if (in_exc)
602                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
603                         }
604
605                         if (in_exc) {
606                                 ec.NeedReturnLabel ();
607                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
608                         } else {
609                                 ec.ig.Emit (OpCodes.Ret);
610                         }
611                 }
612         }
613
614         public class Goto : Statement {
615                 string target;
616                 Block block;
617                 LabeledStatement label;
618                 
619                 public override bool Resolve (EmitContext ec)
620                 {
621                         label = ec.CurrentBranching.LookupLabel (target, loc);
622                         if (label == null)
623                                 return false;
624
625                         // If this is a forward goto.
626                         if (!label.IsDefined)
627                                 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
628
629                         ec.CurrentBranching.CurrentUsageVector.Goto ();
630
631                         return true;
632                 }
633                 
634                 public Goto (Block parent_block, string label, Location l)
635                 {
636                         block = parent_block;
637                         loc = l;
638                         target = label;
639                 }
640
641                 public string Target {
642                         get {
643                                 return target;
644                         }
645                 }
646
647                 protected override void DoEmit (EmitContext ec)
648                 {
649                         Label l = label.LabelTarget (ec);
650                         ec.ig.Emit (OpCodes.Br, l);
651                 }
652         }
653
654         public class LabeledStatement : Statement {
655                 public readonly Location Location;
656                 bool defined;
657                 bool referenced;
658                 Label label;
659
660                 FlowBranching.UsageVector vectors;
661                 
662                 public LabeledStatement (string label_name, Location l)
663                 {
664                         this.Location = l;
665                 }
666
667                 public Label LabelTarget (EmitContext ec)
668                 {
669                         if (defined)
670                                 return label;
671                         label = ec.ig.DefineLabel ();
672                         defined = true;
673
674                         return label;
675                 }
676
677                 public bool IsDefined {
678                         get {
679                                 return defined;
680                         }
681                 }
682
683                 public bool HasBeenReferenced {
684                         get {
685                                 return referenced;
686                         }
687                 }
688
689                 public void AddUsageVector (FlowBranching.UsageVector vector)
690                 {
691                         vector = vector.Clone ();
692                         vector.Next = vectors;
693                         vectors = vector;
694                 }
695
696                 public override bool Resolve (EmitContext ec)
697                 {
698                         ec.CurrentBranching.Label (vectors);
699
700                         referenced = true;
701
702                         return true;
703                 }
704
705                 protected override void DoEmit (EmitContext ec)
706                 {
707                         LabelTarget (ec);
708                         ec.ig.MarkLabel (label);
709                 }
710         }
711         
712
713         /// <summary>
714         ///   `goto default' statement
715         /// </summary>
716         public class GotoDefault : Statement {
717                 
718                 public GotoDefault (Location l)
719                 {
720                         loc = l;
721                 }
722
723                 public override bool Resolve (EmitContext ec)
724                 {
725                         ec.CurrentBranching.CurrentUsageVector.Goto ();
726                         return true;
727                 }
728
729                 protected override void DoEmit (EmitContext ec)
730                 {
731                         if (ec.Switch == null){
732                                 Report.Error (153, loc, "goto default is only valid in a switch statement");
733                                 return;
734                         }
735
736                         if (!ec.Switch.GotDefault){
737                                 Report.Error (159, loc, "No default target on switch statement");
738                                 return;
739                         }
740                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
741                 }
742         }
743
744         /// <summary>
745         ///   `goto case' statement
746         /// </summary>
747         public class GotoCase : Statement {
748                 Expression expr;
749                 Label label;
750                 
751                 public GotoCase (Expression e, Location l)
752                 {
753                         expr = e;
754                         loc = l;
755                 }
756
757                 public override bool Resolve (EmitContext ec)
758                 {
759                         if (ec.Switch == null){
760                                 Report.Error (153, loc, "goto case is only valid in a switch statement");
761                                 return false;
762                         }
763
764                         expr = expr.Resolve (ec);
765                         if (expr == null)
766                                 return false;
767
768                         if (!(expr is Constant)){
769                                 Report.Error (159, loc, "Target expression for goto case is not constant");
770                                 return false;
771                         }
772
773                         object val = Expression.ConvertIntLiteral (
774                                 (Constant) expr, ec.Switch.SwitchType, loc);
775
776                         if (val == null)
777                                 return false;
778                                         
779                         SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
780
781                         if (sl == null){
782                                 Report.Error (
783                                         159, loc,
784                                         "No such label 'case " + val + "': for the goto case");
785                                 return false;
786                         }
787
788                         label = sl.ILLabelCode;
789
790                         ec.CurrentBranching.CurrentUsageVector.Goto ();
791                         return true;
792                 }
793
794                 protected override void DoEmit (EmitContext ec)
795                 {
796                         ec.ig.Emit (OpCodes.Br, label);
797                 }
798         }
799         
800         public class Throw : Statement {
801                 Expression expr;
802                 
803                 public Throw (Expression expr, Location l)
804                 {
805                         this.expr = expr;
806                         loc = l;
807                 }
808
809                 public override bool Resolve (EmitContext ec)
810                 {
811                         bool in_catch = ec.CurrentBranching.InCatch ();
812                         ec.CurrentBranching.CurrentUsageVector.Throw ();
813
814                         if (expr != null){
815                                 expr = expr.Resolve (ec);
816                                 if (expr == null)
817                                         return false;
818
819                                 ExprClass eclass = expr.eclass;
820
821                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
822                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
823                                         expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
824                                         return false;
825                                 }
826
827                                 Type t = expr.Type;
828                                 
829                                 if ((t != TypeManager.exception_type) &&
830                                     !t.IsSubclassOf (TypeManager.exception_type) &&
831                                     !(expr is NullLiteral)) {
832                                         Error (155,
833                                                "The type caught or thrown must be derived " +
834                                                "from System.Exception");
835                                         return false;
836                                 }
837                         } else if (!in_catch) {
838                                 Error (156,
839                                        "A throw statement with no argument is only " +
840                                        "allowed in a catch clause");
841                                 return false;
842                         }
843
844                         return true;
845                 }
846                         
847                 protected override void DoEmit (EmitContext ec)
848                 {
849                         if (expr == null)
850                                 ec.ig.Emit (OpCodes.Rethrow);
851                         else {
852                                 expr.Emit (ec);
853
854                                 ec.ig.Emit (OpCodes.Throw);
855                         }
856                 }
857         }
858
859         public class Break : Statement {
860                 
861                 public Break (Location l)
862                 {
863                         loc = l;
864                 }
865
866                 bool crossing_exc;
867
868                 public override bool Resolve (EmitContext ec)
869                 {
870                         if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
871                                 Error (139, "No enclosing loop or switch to continue to");
872                                 return false;
873                         } else if (ec.CurrentBranching.InFinally (false)) {
874                                 Error (157, "Control can not leave the body of the finally block");
875                                 return false;
876                         } else if (ec.CurrentBranching.InTryOrCatch (false))
877                                 ec.CurrentBranching.AddFinallyVector (
878                                         ec.CurrentBranching.CurrentUsageVector);
879                         else if (ec.CurrentBranching.InLoop ())
880                                 ec.CurrentBranching.AddBreakVector (
881                                         ec.CurrentBranching.CurrentUsageVector);
882
883                         crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
884
885                         ec.CurrentBranching.CurrentUsageVector.Break ();
886                         return true;
887                 }
888
889                 protected override void DoEmit (EmitContext ec)
890                 {
891                         ILGenerator ig = ec.ig;
892
893                         if (crossing_exc)
894                                 ig.Emit (OpCodes.Leave, ec.LoopEnd);
895                         else {
896                                 ec.NeedReturnLabel ();
897                                 ig.Emit (OpCodes.Br, ec.LoopEnd);
898                         }
899                 }
900         }
901
902         public class Continue : Statement {
903                 
904                 public Continue (Location l)
905                 {
906                         loc = l;
907                 }
908
909                 bool crossing_exc;
910
911                 public override bool Resolve (EmitContext ec)
912                 {
913                         if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
914                                 Error (139, "No enclosing loop to continue to");
915                                 return false;
916                         } else if (ec.CurrentBranching.InFinally (false)) {
917                                 Error (157, "Control can not leave the body of the finally block");
918                                 return false;
919                         } else if (ec.CurrentBranching.InTryOrCatch (false))
920                                 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
921
922                         crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
923
924                         ec.CurrentBranching.CurrentUsageVector.Goto ();
925                         return true;
926                 }
927
928                 protected override void DoEmit (EmitContext ec)
929                 {
930                         Label begin = ec.LoopBegin;
931                         
932                         if (crossing_exc)
933                                 ec.ig.Emit (OpCodes.Leave, begin);
934                         else
935                                 ec.ig.Emit (OpCodes.Br, begin);
936                 }
937         }
938
939         public class LocalInfo {
940                 public Expression Type;
941
942                 //
943                 // Most of the time a variable will be stored in a LocalBuilder
944                 //
945                 // But sometimes, it will be stored in a field.  The context of the field will
946                 // be stored in the EmitContext
947                 //
948                 //
949                 public LocalBuilder LocalBuilder;
950                 public FieldBuilder FieldBuilder;
951
952                 public Type VariableType;
953                 public readonly string Name;
954                 public readonly Location Location;
955                 public readonly Block Block;
956
957                 public VariableInfo VariableInfo;
958
959                 enum Flags : byte {
960                         Used = 1,
961                         ReadOnly = 2,
962                         Fixed = 4
963                 }
964
965                 Flags flags;
966                 
967                 public LocalInfo (Expression type, string name, Block block, Location l)
968                 {
969                         Type = type;
970                         Name = name;
971                         Block = block;
972                         Location = l;
973                 }
974
975                 public LocalInfo (TypeContainer tc, Block block, Location l)
976                 {
977                         VariableType = tc.TypeBuilder;
978                         Block = block;
979                         Location = l;
980                 }
981
982                 public bool IsThisAssigned (EmitContext ec, Location loc)
983                 {
984                         if (VariableInfo == null)
985                                 throw new Exception ();
986
987                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
988                                 return true;
989
990                         return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
991                 }
992
993                 public bool IsAssigned (EmitContext ec)
994                 {
995                         if (VariableInfo == null)
996                                 throw new Exception ();
997
998                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
999                 }
1000
1001                 public bool Resolve (EmitContext ec)
1002                 {
1003                         if (VariableType == null)
1004                                 VariableType = ec.DeclSpace.ResolveType (Type, false, Location);
1005
1006                         if (VariableType == TypeManager.void_type) {
1007                                 Report.Error (1547, Location,
1008                                               "Keyword 'void' cannot be used in this context");
1009                                 return false;
1010                         }
1011
1012                         if (VariableType == null)
1013                                 return false;
1014
1015 // TODO: breaks the build
1016 //                      if (VariableType.IsPointer && !ec.InUnsafe)
1017 //                              Expression.UnsafeError (Location);
1018
1019                         return true;
1020                 }
1021
1022                 public void MakePinned ()
1023                 {
1024                         TypeManager.MakePinned (LocalBuilder);
1025                         flags |= Flags.Fixed;
1026                 }
1027
1028                 public bool IsFixed {
1029                         get {
1030                                 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1031                                         return true;
1032
1033                                 return false;
1034                         }
1035                 }
1036
1037                 public override string ToString ()
1038                 {
1039                         return String.Format ("LocalInfo ({0},{1},{2},{3})",
1040                                               Name, Type, VariableInfo, Location);
1041                 }
1042
1043                 public bool Used {
1044                         get {
1045                                 return (flags & Flags.Used) != 0;
1046                         }
1047                         set {
1048                                 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1049                         }
1050                 }
1051
1052                 public bool ReadOnly {
1053                         get {
1054                                 return (flags & Flags.ReadOnly) != 0;
1055                         }
1056                         set {
1057                                 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1058                         }
1059                 }
1060
1061                 
1062                 
1063         }
1064                 
1065         /// <summary>
1066         ///   Block represents a C# block.
1067         /// </summary>
1068         ///
1069         /// <remarks>
1070         ///   This class is used in a number of places: either to represent
1071         ///   explicit blocks that the programmer places or implicit blocks.
1072         ///
1073         ///   Implicit blocks are used as labels or to introduce variable
1074         ///   declarations.
1075         ///
1076         ///   Top-level blocks derive from Block, and they are called ToplevelBlock
1077         ///   they contain extra information that is not necessary on normal blocks.
1078         /// </remarks>
1079         public class Block : Statement {
1080                 public readonly Block     Parent;
1081                 public readonly Location  StartLocation;
1082                 public Location           EndLocation = Location.Null;
1083
1084                 [Flags]
1085                 public enum Flags : byte {
1086                         Implicit  = 1,
1087                         Unchecked = 2,
1088                         BlockUsed = 4,
1089                         VariablesInitialized = 8,
1090                         HasRet = 16,
1091                         IsDestructor = 32       
1092                 }
1093                 Flags flags;
1094
1095                 public bool Implicit {
1096                         get {
1097                                 return (flags & Flags.Implicit) != 0;
1098                         }
1099                 }
1100
1101                 public bool Unchecked {
1102                         get {
1103                                 return (flags & Flags.Unchecked) != 0;
1104                         }
1105                         set {
1106                                 flags |= Flags.Unchecked;
1107                         }
1108                 }
1109
1110                 //
1111                 // The statements in this block
1112                 //
1113                 ArrayList statements;
1114                 int num_statements;
1115
1116                 //
1117                 // An array of Blocks.  We keep track of children just
1118                 // to generate the local variable declarations.
1119                 //
1120                 // Statements and child statements are handled through the
1121                 // statements.
1122                 //
1123                 ArrayList children;
1124                 
1125                 //
1126                 // Labels.  (label, block) pairs.
1127                 //
1128                 Hashtable labels;
1129
1130                 //
1131                 // Keeps track of (name, type) pairs
1132                 //
1133                 Hashtable variables;
1134
1135                 //
1136                 // Keeps track of constants
1137                 Hashtable constants;
1138
1139                 //
1140                 // If this is a switch section, the enclosing switch block.
1141                 //
1142                 Block switch_block;
1143
1144                 static int id;
1145
1146                 int this_id;
1147                 
1148                 public Block (Block parent)
1149                         : this (parent, (Flags) 0, Location.Null, Location.Null)
1150                 { }
1151
1152                 public Block (Block parent, Flags flags)
1153                         : this (parent, flags, Location.Null, Location.Null)
1154                 { }
1155
1156                 public Block (Block parent, Flags flags, Parameters parameters)
1157                         : this (parent, flags, parameters, Location.Null, Location.Null)
1158                 { }
1159
1160                 public Block (Block parent, Location start, Location end)
1161                         : this (parent, (Flags) 0, start, end)
1162                 { }
1163
1164                 public Block (Block parent, Parameters parameters, Location start, Location end)
1165                         : this (parent, (Flags) 0, parameters, start, end)
1166                 { }
1167
1168                 public Block (Block parent, Flags flags, Location start, Location end)
1169                         : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1170                 { }
1171
1172                 public Block (Block parent, Flags flags, Parameters parameters,
1173                               Location start, Location end)
1174                 {
1175                         if (parent != null)
1176                                 parent.AddChild (this);
1177                         
1178                         this.Parent = parent;
1179                         this.flags = flags;
1180                         this.parameters = parameters;
1181                         this.StartLocation = start;
1182                         this.EndLocation = end;
1183                         this.loc = start;
1184                         this_id = id++;
1185                         statements = new ArrayList ();
1186
1187                         if (parent != null && Implicit) {
1188                                 if (parent.child_variable_names == null)
1189                                         parent.child_variable_names = new Hashtable();
1190                                 // share with parent
1191                                 child_variable_names = parent.child_variable_names;
1192                         }
1193                                 
1194                 }
1195
1196                 public Block CreateSwitchBlock (Location start)
1197                 {
1198                         Block new_block = new Block (this, start, start);
1199                         new_block.switch_block = this;
1200                         return new_block;
1201                 }
1202
1203                 public int ID {
1204                         get {
1205                                 return this_id;
1206                         }
1207                 }
1208
1209                 void AddChild (Block b)
1210                 {
1211                         if (children == null)
1212                                 children = new ArrayList ();
1213                         
1214                         children.Add (b);
1215                 }
1216
1217                 public void SetEndLocation (Location loc)
1218                 {
1219                         EndLocation = loc;
1220                 }
1221
1222                 /// <summary>
1223                 ///   Adds a label to the current block. 
1224                 /// </summary>
1225                 ///
1226                 /// <returns>
1227                 ///   false if the name already exists in this block. true
1228                 ///   otherwise.
1229                 /// </returns>
1230                 ///
1231                 public bool AddLabel (string name, LabeledStatement target, Location loc)
1232                 {
1233                         if (switch_block != null)
1234                                 return switch_block.AddLabel (name, target, loc);
1235
1236                         Block cur = this;
1237                         while (cur != null) {
1238                                 if (cur.DoLookupLabel (name) != null) {
1239                                         Report.Error (
1240                                                 140, loc, "The label '{0}' is a duplicate",
1241                                                 name);
1242                                         return false;
1243                                 }
1244
1245                                 if (!Implicit)
1246                                         break;
1247
1248                                 cur = cur.Parent;
1249                         }
1250
1251                         while (cur != null) {
1252                                 if (cur.DoLookupLabel (name) != null) {
1253                                         Report.Error (
1254                                                 158, loc,
1255                                                 "The label '{0}' shadows another label " +
1256                                                 "by the same name in a containing scope.",
1257                                                 name);
1258                                         return false;
1259                                 }
1260
1261                                 if (children != null) {
1262                                         foreach (Block b in children) {
1263                                                 LabeledStatement s = b.DoLookupLabel (name);
1264                                                 if (s == null)
1265                                                         continue;
1266
1267                                                 Report.Error (
1268                                                         158, s.Location,
1269                                                         "The label '{0}' shadows another " +
1270                                                         "label by the same name in a " +
1271                                                         "containing scope.",
1272                                                         name);
1273                                                 return false;
1274                                         }
1275                                 }
1276
1277
1278                                 cur = cur.Parent;
1279                         }
1280
1281                         if (labels == null)
1282                                 labels = new Hashtable ();
1283
1284                         labels.Add (name, target);
1285                         return true;
1286                 }
1287
1288                 public LabeledStatement LookupLabel (string name)
1289                 {
1290                         LabeledStatement s = DoLookupLabel (name);
1291                         if (s != null)
1292                                 return s;
1293
1294                         if (children == null)
1295                                 return null;
1296
1297                         foreach (Block child in children) {
1298                                 if (!child.Implicit)
1299                                         continue;
1300
1301                                 s = child.LookupLabel (name);
1302                                 if (s != null)
1303                                         return s;
1304                         }
1305
1306                         return null;
1307                 }
1308
1309                 LabeledStatement DoLookupLabel (string name)
1310                 {
1311                         if (switch_block != null)
1312                                 return switch_block.LookupLabel (name);
1313
1314                         if (labels != null)
1315                                 if (labels.Contains (name))
1316                                         return ((LabeledStatement) labels [name]);
1317
1318                         return null;
1319                 }
1320
1321                 LocalInfo this_variable = null;
1322
1323                 // <summary>
1324                 //   Returns the "this" instance variable of this block.
1325                 //   See AddThisVariable() for more information.
1326                 // </summary>
1327                 public LocalInfo ThisVariable {
1328                         get {
1329                                 if (this_variable != null)
1330                                         return this_variable;
1331                                 else if (Parent != null)
1332                                         return Parent.ThisVariable;
1333                                 else
1334                                         return null;
1335                         }
1336                 }
1337
1338                 Hashtable child_variable_names;
1339
1340                 // <summary>
1341                 //   Marks a variable with name @name as being used in a child block.
1342                 //   If a variable name has been used in a child block, it's illegal to
1343                 //   declare a variable with the same name in the current block.
1344                 // </summary>
1345                 public void AddChildVariableName (string name)
1346                 {
1347                         if (child_variable_names == null)
1348                                 child_variable_names = new Hashtable ();
1349
1350                         if (!child_variable_names.Contains (name))
1351                                 child_variable_names.Add (name, true);
1352                 }
1353
1354                 // <summary>
1355                 //   Checks whether a variable name has already been used in a child block.
1356                 // </summary>
1357                 public bool IsVariableNameUsedInChildBlock (string name)
1358                 {
1359                         if (child_variable_names == null)
1360                                 return false;
1361
1362                         return child_variable_names.Contains (name);
1363                 }
1364
1365                 // <summary>
1366                 //   This is used by non-static `struct' constructors which do not have an
1367                 //   initializer - in this case, the constructor must initialize all of the
1368                 //   struct's fields.  To do this, we add a "this" variable and use the flow
1369                 //   analysis code to ensure that it's been fully initialized before control
1370                 //   leaves the constructor.
1371                 // </summary>
1372                 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1373                 {
1374                         if (this_variable != null)
1375                                 return this_variable;
1376
1377                         if (variables == null)
1378                                 variables = new Hashtable ();
1379
1380                         this_variable = new LocalInfo (tc, this, l);
1381                         this_variable.Used = true;
1382
1383                         variables.Add ("this", this_variable);
1384
1385                         return this_variable;
1386                 }
1387
1388                 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1389                 {
1390                         if (variables == null)
1391                                 variables = new Hashtable ();
1392
1393                         LocalInfo vi = GetLocalInfo (name);
1394                         if (vi != null) {
1395                                 if (vi.Block != this)
1396                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1397                                                       "cannot be declared in this scope since it would " +
1398                                                       "give a different meaning to `" + name + "', which " +
1399                                                       "is already used in a `parent or current' scope to " +
1400                                                       "denote something else");
1401                                 else
1402                                         Report.Error (128, l, "A local variable `" + name + "' is already " +
1403                                                       "defined in this scope");
1404                                 return null;
1405                         }
1406
1407                         if (IsVariableNameUsedInChildBlock (name)) {
1408                                 Report.Error (136, l, "A local variable named `" + name + "' " +
1409                                               "cannot be declared in this scope since it would " +
1410                                               "give a different meaning to `" + name + "', which " +
1411                                               "is already used in a `child' scope to denote something " +
1412                                               "else");
1413                                 return null;
1414                         }
1415
1416                         if (pars != null) {
1417                                 int idx;
1418                                 Parameter p = pars.GetParameterByName (name, out idx);
1419                                 if (p != null) {
1420                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1421                                                       "cannot be declared in this scope since it would " +
1422                                                       "give a different meaning to `" + name + "', which " +
1423                                                       "is already used in a `parent or current' scope to " +
1424                                                       "denote something else");
1425                                         return null;
1426                                 }
1427                         }
1428
1429                         vi = new LocalInfo (type, name, this, l);
1430
1431                         variables.Add (name, vi);
1432
1433                         // Mark 'name' as "used by a child block" in every surrounding block
1434                         Block cur = this;
1435                         while (cur != null && cur.Implicit) 
1436                                 cur = cur.Parent;
1437                         if (cur != null)
1438                                 for (Block par = cur.Parent; par != null; par = par.Parent)
1439                                         par.AddChildVariableName (name);
1440
1441                         if ((flags & Flags.VariablesInitialized) != 0)
1442                                 throw new Exception ();
1443
1444                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
1445                         return vi;
1446                 }
1447
1448                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1449                 {
1450                         if (AddVariable (type, name, pars, l) == null)
1451                                 return false;
1452                         
1453                         if (constants == null)
1454                                 constants = new Hashtable ();
1455
1456                         constants.Add (name, value);
1457                         return true;
1458                 }
1459
1460                 public Hashtable Variables {
1461                         get {
1462                                 return variables;
1463                         }
1464                 }
1465
1466                 public LocalInfo GetLocalInfo (string name)
1467                 {
1468                         for (Block b = this; b != null; b = b.Parent) {
1469                                 if (b.variables != null) {
1470                                         LocalInfo ret = b.variables [name] as LocalInfo;
1471                                         if (ret != null)
1472                                                 return ret;
1473                                 }
1474                         }
1475                         return null;
1476                 }
1477
1478                 public Expression GetVariableType (string name)
1479                 {
1480                         LocalInfo vi = GetLocalInfo (name);
1481
1482                         if (vi != null)
1483                                 return vi.Type;
1484
1485                         return null;
1486                 }
1487
1488                 public Expression GetConstantExpression (string name)
1489                 {
1490                         for (Block b = this; b != null; b = b.Parent) {
1491                                 if (b.constants != null) {
1492                                         Expression ret = b.constants [name] as Expression;
1493                                         if (ret != null)
1494                                                 return ret;
1495                                 }
1496                         }
1497                         return null;
1498                 }
1499                 
1500                 /// <summary>
1501                 ///   True if the variable named @name is a constant
1502                 ///  </summary>
1503                 public bool IsConstant (string name)
1504                 {
1505                         Expression e = null;
1506                         
1507                         e = GetConstantExpression (name);
1508                         
1509                         return e != null;
1510                 }
1511                 
1512                 Parameters parameters = null;
1513                 public Parameters Parameters {
1514                         get {
1515                                 Block b = this;
1516                                 while (b.Parent != null)
1517                                         b = b.Parent;
1518                                 return b.parameters;
1519                         }
1520                 }
1521
1522                 /// <returns>
1523                 ///   A list of labels that were not used within this block
1524                 /// </returns>
1525                 public string [] GetUnreferenced ()
1526                 {
1527                         // FIXME: Implement me
1528                         return null;
1529                 }
1530
1531                 public void AddStatement (Statement s)
1532                 {
1533                         statements.Add (s);
1534                         flags |= Flags.BlockUsed;
1535                 }
1536
1537                 public bool Used {
1538                         get {
1539                                 return (flags & Flags.BlockUsed) != 0;
1540                         }
1541                 }
1542
1543                 public void Use ()
1544                 {
1545                         flags |= Flags.BlockUsed;
1546                 }
1547
1548                 public bool HasRet {
1549                         get {
1550                                 return (flags & Flags.HasRet) != 0;
1551                         }
1552                 }
1553
1554                 public bool IsDestructor {
1555                         get {
1556                                 return (flags & Flags.IsDestructor) != 0;
1557                         }
1558                 }
1559
1560                 public void SetDestructor ()
1561                 {
1562                         flags |= Flags.IsDestructor;
1563                 }
1564
1565                 VariableMap param_map, local_map;
1566
1567                 public VariableMap ParameterMap {
1568                         get {
1569                                 if ((flags & Flags.VariablesInitialized) == 0)
1570                                         throw new Exception ();
1571
1572                                 return param_map;
1573                         }
1574                 }
1575
1576                 public VariableMap LocalMap {
1577                         get {
1578                                 if ((flags & Flags.VariablesInitialized) == 0)
1579                                         throw new Exception ();
1580
1581                                 return local_map;
1582                         }
1583                 }
1584
1585                 public bool LiftVariable (LocalInfo local_info)
1586                 {
1587                         return false;
1588                 }
1589                 
1590                 /// <summary>
1591                 ///   Emits the variable declarations and labels.
1592                 /// </summary>
1593                 /// <remarks>
1594                 ///   tc: is our typecontainer (to resolve type references)
1595                 ///   ig: is the code generator:
1596                 /// </remarks>
1597                 public void EmitMeta (EmitContext ec, InternalParameters ip)
1598                 {
1599                         ILGenerator ig = ec.ig;
1600
1601                         //
1602                         // Compute the VariableMap's.
1603                         //
1604                         // Unfortunately, we don't know the type when adding variables with
1605                         // AddVariable(), so we need to compute this info here.
1606                         //
1607
1608                         LocalInfo[] locals;
1609                         if (variables != null) {
1610                                 foreach (LocalInfo li in variables.Values)
1611                                         li.Resolve (ec);
1612
1613                                 locals = new LocalInfo [variables.Count];
1614                                 variables.Values.CopyTo (locals, 0);
1615                         } else
1616                                 locals = new LocalInfo [0];
1617
1618                         if (Parent != null)
1619                                 local_map = new VariableMap (Parent.LocalMap, locals);
1620                         else
1621                                 local_map = new VariableMap (locals);
1622
1623                         param_map = new VariableMap (ip);
1624                         flags |= Flags.VariablesInitialized;
1625
1626                         bool old_check_state = ec.ConstantCheckState;
1627                         ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1628                         bool remap_locals = ec.RemapToProxy;
1629                                 
1630                         //
1631                         // Process this block variables
1632                         //
1633                         if (variables != null){
1634                                 foreach (DictionaryEntry de in variables){
1635                                         string name = (string) de.Key;
1636                                         LocalInfo vi = (LocalInfo) de.Value;
1637                                         
1638                                         if (vi.VariableType == null)
1639                                                 continue;
1640
1641                                         Type variable_type = vi.VariableType;
1642
1643                                         if (variable_type.IsPointer){
1644                                                 //
1645                                                 // Am not really convinced that this test is required (Microsoft does it)
1646                                                 // but the fact is that you would not be able to use the pointer variable
1647                                                 // *anyways*
1648                                                 //
1649                                                 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1650                                                                                   vi.Location))
1651                                                         continue;
1652                                         }
1653
1654                                         if (remap_locals)
1655                                                 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1656                                         else
1657                                                 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1658
1659                                         if (constants == null)
1660                                                 continue;
1661
1662                                         Expression cv = (Expression) constants [name];
1663                                         if (cv == null)
1664                                                 continue;
1665
1666                                         ec.CurrentBlock = this;
1667                                         Expression e = cv.Resolve (ec);
1668                                         if (e == null)
1669                                                 continue;
1670
1671                                         Constant ce = e as Constant;
1672                                         if (ce == null){
1673                                                 Report.Error (133, vi.Location,
1674                                                               "The expression being assigned to `" +
1675                                                               name + "' must be constant (" + e + ")");
1676                                                 continue;
1677                                         }
1678
1679                                         if (e.Type != variable_type){
1680                                                 e = Const.ChangeType (vi.Location, ce, variable_type);
1681                                                 if (e == null)
1682                                                         continue;
1683                                         }
1684
1685                                         constants.Remove (name);
1686                                         constants.Add (name, e);
1687                                 }
1688                         }
1689                         ec.ConstantCheckState = old_check_state;
1690
1691                         //
1692                         // Now, handle the children
1693                         //
1694                         if (children != null){
1695                                 foreach (Block b in children)
1696                                         b.EmitMeta (ec, ip);
1697                         }
1698                 }
1699
1700                 void UsageWarning (FlowBranching.UsageVector vector)
1701                 {
1702                         string name;
1703
1704                         if (variables != null){
1705                                 foreach (DictionaryEntry de in variables){
1706                                         LocalInfo vi = (LocalInfo) de.Value;
1707                                         
1708                                         if (vi.Used)
1709                                                 continue;
1710                                         
1711                                         name = (string) de.Key;
1712
1713                                         if (vector.IsAssigned (vi.VariableInfo)){
1714                                                 Report.Warning (
1715                                                         219, vi.Location, "The variable `" + name +
1716                                                         "' is assigned but its value is never used");
1717                                         } else {
1718                                                 Report.Warning (
1719                                                         168, vi.Location, "The variable `" +
1720                                                         name +
1721                                                         "' is declared but never used");
1722                                         } 
1723                                 }
1724                         }
1725                 }
1726
1727                 public override bool Resolve (EmitContext ec)
1728                 {
1729                         Block prev_block = ec.CurrentBlock;
1730                         bool ok = true;
1731
1732                         int errors = Report.Errors;
1733
1734                         ec.CurrentBlock = this;
1735                         ec.StartFlowBranching (this);
1736
1737                         Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1738
1739                         bool unreachable = false, warning_shown = false;
1740
1741                         int statement_count = statements.Count;
1742                         for (int ix = 0; ix < statement_count; ix++){
1743                                 Statement s = (Statement) statements [ix];
1744
1745                                 if (unreachable && !(s is LabeledStatement)) {
1746                                         if (s == EmptyStatement.Value)
1747                                                 s.loc = EndLocation;
1748
1749                                         if (!s.ResolveUnreachable (ec, !warning_shown))
1750                                                 ok = false;
1751
1752                                         if (s != EmptyStatement.Value)
1753                                                 warning_shown = true;
1754                                         else
1755                                                 s.loc = Location.Null;
1756
1757                                         statements [ix] = EmptyStatement.Value;
1758                                         continue;
1759                                 }
1760
1761                                 if (s.Resolve (ec) == false) {
1762                                         ok = false;
1763                                         statements [ix] = EmptyStatement.Value;
1764                                         continue;
1765                                 }
1766
1767                                 num_statements = ix + 1;
1768
1769                                 if (s is LabeledStatement)
1770                                         unreachable = false;
1771                                 else
1772                                         unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1773                         }
1774
1775                         Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1776                                       ec.CurrentBranching, statement_count, num_statements);
1777
1778
1779                         FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1780
1781                         ec.CurrentBlock = prev_block;
1782
1783                         // If we're a non-static `struct' constructor which doesn't have an
1784                         // initializer, then we must initialize all of the struct's fields.
1785                         if ((this_variable != null) &&
1786                             (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1787                             !this_variable.IsThisAssigned (ec, loc))
1788                                 ok = false;
1789
1790                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1791                                 foreach (LabeledStatement label in labels.Values)
1792                                         if (!label.HasBeenReferenced)
1793                                                 Report.Warning (164, label.Location,
1794                                                                 "This label has not been referenced");
1795                         }
1796
1797                         Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1798
1799                         if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1800                             (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1801                             (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1802                                 flags |= Flags.HasRet;
1803
1804                         if (ok && (errors == Report.Errors)) {
1805                                 if (RootContext.WarningLevel >= 3)
1806                                         UsageWarning (vector);
1807                         }
1808
1809                         return ok;
1810                 }
1811                 
1812                 protected override void DoEmit (EmitContext ec)
1813                 {
1814                         for (int ix = 0; ix < num_statements; ix++){
1815                                 Statement s = (Statement) statements [ix];
1816
1817                                 // Check whether we are the last statement in a
1818                                 // top-level block.
1819
1820                                 if ((Parent == null) && (ix+1 == num_statements))
1821                                         ec.IsLastStatement = true;
1822                                 else
1823                                         ec.IsLastStatement = false;
1824
1825                                 s.Emit (ec);
1826                         }
1827                 }
1828
1829                 public override void Emit (EmitContext ec)
1830                 {
1831                         Block prev_block = ec.CurrentBlock;
1832
1833                         ec.CurrentBlock = this;
1834
1835                         bool emit_debug_info = (CodeGen.SymbolWriter != null);
1836                         bool is_lexical_block = !Implicit && (Parent != null);
1837
1838                         if (emit_debug_info) {
1839                                 if (is_lexical_block)
1840                                         ec.ig.BeginScope ();
1841
1842                                 if (variables != null) {
1843                                         foreach (DictionaryEntry de in variables) {
1844                                                 string name = (string) de.Key;
1845                                                 LocalInfo vi = (LocalInfo) de.Value;
1846
1847                                                 if (vi.LocalBuilder == null)
1848                                                         continue;
1849
1850                                                 vi.LocalBuilder.SetLocalSymInfo (name);
1851                                         }
1852                                 }
1853                         }
1854
1855                         ec.Mark (StartLocation, true);
1856                         DoEmit (ec);
1857                         ec.Mark (EndLocation, true); 
1858
1859                         if (emit_debug_info && is_lexical_block)
1860                                 ec.ig.EndScope ();
1861
1862                         ec.CurrentBlock = prev_block;
1863                 }
1864         }
1865
1866         //
1867         // 
1868         public class ToplevelBlock : Block {
1869                 public ToplevelBlock (Parameters parameters, Location start) :
1870                         base (null, parameters, start, Location.Null)
1871                 {
1872                 }
1873
1874                 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1875                         base (null, flags, parameters, start, Location.Null)
1876                 {
1877                 }
1878         }
1879         
1880         public class SwitchLabel {
1881                 Expression label;
1882                 object converted;
1883                 public Location loc;
1884                 public Label ILLabel;
1885                 public Label ILLabelCode;
1886
1887                 //
1888                 // if expr == null, then it is the default case.
1889                 //
1890                 public SwitchLabel (Expression expr, Location l)
1891                 {
1892                         label = expr;
1893                         loc = l;
1894                 }
1895
1896                 public Expression Label {
1897                         get {
1898                                 return label;
1899                         }
1900                 }
1901
1902                 public object Converted {
1903                         get {
1904                                 return converted;
1905                         }
1906                 }
1907
1908                 //
1909                 // Resolves the expression, reduces it to a literal if possible
1910                 // and then converts it to the requested type.
1911                 //
1912                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1913                 {
1914                         ILLabel = ec.ig.DefineLabel ();
1915                         ILLabelCode = ec.ig.DefineLabel ();
1916
1917                         if (label == null)
1918                                 return true;
1919                         
1920                         Expression e = label.Resolve (ec);
1921
1922                         if (e == null)
1923                                 return false;
1924
1925                         if (!(e is Constant)){
1926                                 Report.Error (150, loc, "A constant value is expected, got: " + e);
1927                                 return false;
1928                         }
1929
1930                         if (e is StringConstant || e is NullLiteral){
1931                                 if (required_type == TypeManager.string_type){
1932                                         converted = e;
1933                                         ILLabel = ec.ig.DefineLabel ();
1934                                         return true;
1935                                 }
1936                         }
1937
1938                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1939                         if (converted == null)
1940                                 return false;
1941
1942                         return true;
1943                 }
1944         }
1945
1946         public class SwitchSection {
1947                 // An array of SwitchLabels.
1948                 public readonly ArrayList Labels;
1949                 public readonly Block Block;
1950                 
1951                 public SwitchSection (ArrayList labels, Block block)
1952                 {
1953                         Labels = labels;
1954                         Block = block;
1955                 }
1956         }
1957         
1958         public class Switch : Statement {
1959                 public readonly ArrayList Sections;
1960                 public Expression Expr;
1961
1962                 /// <summary>
1963                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
1964                 /// </summary>
1965                 public Hashtable Elements;
1966
1967                 /// <summary>
1968                 ///   The governing switch type
1969                 /// </summary>
1970                 public Type SwitchType;
1971
1972                 //
1973                 // Computed
1974                 //
1975                 bool got_default;
1976                 Label default_target;
1977                 Expression new_expr;
1978
1979                 //
1980                 // The types allowed to be implicitly cast from
1981                 // on the governing type
1982                 //
1983                 static Type [] allowed_types;
1984                 
1985                 public Switch (Expression e, ArrayList sects, Location l)
1986                 {
1987                         Expr = e;
1988                         Sections = sects;
1989                         loc = l;
1990                 }
1991
1992                 public bool GotDefault {
1993                         get {
1994                                 return got_default;
1995                         }
1996                 }
1997
1998                 public Label DefaultTarget {
1999                         get {
2000                                 return default_target;
2001                         }
2002                 }
2003
2004                 //
2005                 // Determines the governing type for a switch.  The returned
2006                 // expression might be the expression from the switch, or an
2007                 // expression that includes any potential conversions to the
2008                 // integral types or to string.
2009                 //
2010                 Expression SwitchGoverningType (EmitContext ec, Type t)
2011                 {
2012                         if (t == TypeManager.int32_type ||
2013                             t == TypeManager.uint32_type ||
2014                             t == TypeManager.char_type ||
2015                             t == TypeManager.byte_type ||
2016                             t == TypeManager.sbyte_type ||
2017                             t == TypeManager.ushort_type ||
2018                             t == TypeManager.short_type ||
2019                             t == TypeManager.uint64_type ||
2020                             t == TypeManager.int64_type ||
2021                             t == TypeManager.string_type ||
2022                                 t == TypeManager.bool_type ||
2023                                 t.IsSubclassOf (TypeManager.enum_type))
2024                                 return Expr;
2025
2026                         if (allowed_types == null){
2027                                 allowed_types = new Type [] {
2028                                         TypeManager.sbyte_type,
2029                                         TypeManager.byte_type,
2030                                         TypeManager.short_type,
2031                                         TypeManager.ushort_type,
2032                                         TypeManager.int32_type,
2033                                         TypeManager.uint32_type,
2034                                         TypeManager.int64_type,
2035                                         TypeManager.uint64_type,
2036                                         TypeManager.char_type,
2037                                         TypeManager.bool_type,
2038                                         TypeManager.string_type
2039                                 };
2040                         }
2041
2042                         //
2043                         // Try to find a *user* defined implicit conversion.
2044                         //
2045                         // If there is no implicit conversion, or if there are multiple
2046                         // conversions, we have to report an error
2047                         //
2048                         Expression converted = null;
2049                         foreach (Type tt in allowed_types){
2050                                 Expression e;
2051                                 
2052                                 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2053                                 if (e == null)
2054                                         continue;
2055
2056                                 if (converted != null){
2057                                         Report.Error (-12, loc, "More than one conversion to an integral " +
2058                                                       " type exists for type `" +
2059                                                       TypeManager.CSharpName (Expr.Type)+"'");
2060                                         return null;
2061                                 } else
2062                                         converted = e;
2063                         }
2064                         return converted;
2065                 }
2066
2067                 void error152 (string n)
2068                 {
2069                         Report.Error (
2070                                 152, "The label `" + n + ":' " +
2071                                 "is already present on this switch statement");
2072                 }
2073                 
2074                 //
2075                 // Performs the basic sanity checks on the switch statement
2076                 // (looks for duplicate keys and non-constant expressions).
2077                 //
2078                 // It also returns a hashtable with the keys that we will later
2079                 // use to compute the switch tables
2080                 //
2081                 bool CheckSwitch (EmitContext ec)
2082                 {
2083                         Type compare_type;
2084                         bool error = false;
2085                         Elements = new Hashtable ();
2086                                 
2087                         got_default = false;
2088
2089                         if (TypeManager.IsEnumType (SwitchType)){
2090                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2091                         } else
2092                                 compare_type = SwitchType;
2093                         
2094                         foreach (SwitchSection ss in Sections){
2095                                 foreach (SwitchLabel sl in ss.Labels){
2096                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
2097                                                 error = true;
2098                                                 continue;
2099                                         }
2100
2101                                         if (sl.Label == null){
2102                                                 if (got_default){
2103                                                         error152 ("default");
2104                                                         error = true;
2105                                                 }
2106                                                 got_default = true;
2107                                                 continue;
2108                                         }
2109                                         
2110                                         object key = sl.Converted;
2111
2112                                         if (key is Constant)
2113                                                 key = ((Constant) key).GetValue ();
2114
2115                                         if (key == null)
2116                                                 key = NullLiteral.Null;
2117                                         
2118                                         string lname = null;
2119                                         if (compare_type == TypeManager.uint64_type){
2120                                                 ulong v = (ulong) key;
2121
2122                                                 if (Elements.Contains (v))
2123                                                         lname = v.ToString ();
2124                                                 else
2125                                                         Elements.Add (v, sl);
2126                                         } else if (compare_type == TypeManager.int64_type){
2127                                                 long v = (long) key;
2128
2129                                                 if (Elements.Contains (v))
2130                                                         lname = v.ToString ();
2131                                                 else
2132                                                         Elements.Add (v, sl);
2133                                         } else if (compare_type == TypeManager.uint32_type){
2134                                                 uint v = (uint) key;
2135
2136                                                 if (Elements.Contains (v))
2137                                                         lname = v.ToString ();
2138                                                 else
2139                                                         Elements.Add (v, sl);
2140                                         } else if (compare_type == TypeManager.char_type){
2141                                                 char v = (char) key;
2142                                                 
2143                                                 if (Elements.Contains (v))
2144                                                         lname = v.ToString ();
2145                                                 else
2146                                                         Elements.Add (v, sl);
2147                                         } else if (compare_type == TypeManager.byte_type){
2148                                                 byte v = (byte) key;
2149                                                 
2150                                                 if (Elements.Contains (v))
2151                                                         lname = v.ToString ();
2152                                                 else
2153                                                         Elements.Add (v, sl);
2154                                         } else if (compare_type == TypeManager.sbyte_type){
2155                                                 sbyte v = (sbyte) key;
2156                                                 
2157                                                 if (Elements.Contains (v))
2158                                                         lname = v.ToString ();
2159                                                 else
2160                                                         Elements.Add (v, sl);
2161                                         } else if (compare_type == TypeManager.short_type){
2162                                                 short v = (short) key;
2163                                                 
2164                                                 if (Elements.Contains (v))
2165                                                         lname = v.ToString ();
2166                                                 else
2167                                                         Elements.Add (v, sl);
2168                                         } else if (compare_type == TypeManager.ushort_type){
2169                                                 ushort v = (ushort) key;
2170                                                 
2171                                                 if (Elements.Contains (v))
2172                                                         lname = v.ToString ();
2173                                                 else
2174                                                         Elements.Add (v, sl);
2175                                         } else if (compare_type == TypeManager.string_type){
2176                                                 if (key is NullLiteral){
2177                                                         if (Elements.Contains (NullLiteral.Null))
2178                                                                 lname = "null";
2179                                                         else
2180                                                                 Elements.Add (NullLiteral.Null, null);
2181                                                 } else {
2182                                                         string s = (string) key;
2183
2184                                                         if (Elements.Contains (s))
2185                                                                 lname = s;
2186                                                         else
2187                                                                 Elements.Add (s, sl);
2188                                                 }
2189                                         } else if (compare_type == TypeManager.int32_type) {
2190                                                 int v = (int) key;
2191
2192                                                 if (Elements.Contains (v))
2193                                                         lname = v.ToString ();
2194                                                 else
2195                                                         Elements.Add (v, sl);
2196                                         } else if (compare_type == TypeManager.bool_type) {
2197                                                 bool v = (bool) key;
2198
2199                                                 if (Elements.Contains (v))
2200                                                         lname = v.ToString ();
2201                                                 else
2202                                                         Elements.Add (v, sl);
2203                                         }
2204                                         else
2205                                         {
2206                                                 throw new Exception ("Unknown switch type!" +
2207                                                                      SwitchType + " " + compare_type);
2208                                         }
2209
2210                                         if (lname != null){
2211                                                 error152 ("case + " + lname);
2212                                                 error = true;
2213                                         }
2214                                 }
2215                         }
2216                         if (error)
2217                                 return false;
2218
2219                         return true;
2220                 }
2221
2222                 void EmitObjectInteger (ILGenerator ig, object k)
2223                 {
2224                         if (k is int)
2225                                 IntConstant.EmitInt (ig, (int) k);
2226                         else if (k is Constant) {
2227                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2228                         } 
2229                         else if (k is uint)
2230                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2231                         else if (k is long)
2232                         {
2233                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2234                                 {
2235                                         IntConstant.EmitInt (ig, (int) (long) k);
2236                                         ig.Emit (OpCodes.Conv_I8);
2237                                 }
2238                                 else
2239                                         LongConstant.EmitLong (ig, (long) k);
2240                         }
2241                         else if (k is ulong)
2242                         {
2243                                 if ((ulong) k < (1L<<32))
2244                                 {
2245                                         IntConstant.EmitInt (ig, (int) (long) k);
2246                                         ig.Emit (OpCodes.Conv_U8);
2247                                 }
2248                                 else
2249                                 {
2250                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2251                                 }
2252                         }
2253                         else if (k is char)
2254                                 IntConstant.EmitInt (ig, (int) ((char) k));
2255                         else if (k is sbyte)
2256                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2257                         else if (k is byte)
2258                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2259                         else if (k is short)
2260                                 IntConstant.EmitInt (ig, (int) ((short) k));
2261                         else if (k is ushort)
2262                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2263                         else if (k is bool)
2264                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2265                         else
2266                                 throw new Exception ("Unhandled case");
2267                 }
2268                 
2269                 // structure used to hold blocks of keys while calculating table switch
2270                 class KeyBlock : IComparable
2271                 {
2272                         public KeyBlock (long _nFirst)
2273                         {
2274                                 nFirst = nLast = _nFirst;
2275                         }
2276                         public long nFirst;
2277                         public long nLast;
2278                         public ArrayList rgKeys = null;
2279                         // how many items are in the bucket
2280                         public int Size = 1;
2281                         public int Length
2282                         {
2283                                 get { return (int) (nLast - nFirst + 1); }
2284                         }
2285                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2286                         {
2287                                 return kbLast.nLast - kbFirst.nFirst + 1;
2288                         }
2289                         public int CompareTo (object obj)
2290                         {
2291                                 KeyBlock kb = (KeyBlock) obj;
2292                                 int nLength = Length;
2293                                 int nLengthOther = kb.Length;
2294                                 if (nLengthOther == nLength)
2295                                         return (int) (kb.nFirst - nFirst);
2296                                 return nLength - nLengthOther;
2297                         }
2298                 }
2299
2300                 /// <summary>
2301                 /// This method emits code for a lookup-based switch statement (non-string)
2302                 /// Basically it groups the cases into blocks that are at least half full,
2303                 /// and then spits out individual lookup opcodes for each block.
2304                 /// It emits the longest blocks first, and short blocks are just
2305                 /// handled with direct compares.
2306                 /// </summary>
2307                 /// <param name="ec"></param>
2308                 /// <param name="val"></param>
2309                 /// <returns></returns>
2310                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2311                 {
2312                         int cElements = Elements.Count;
2313                         object [] rgKeys = new object [cElements];
2314                         Elements.Keys.CopyTo (rgKeys, 0);
2315                         Array.Sort (rgKeys);
2316
2317                         // initialize the block list with one element per key
2318                         ArrayList rgKeyBlocks = new ArrayList ();
2319                         foreach (object key in rgKeys)
2320                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2321
2322                         KeyBlock kbCurr;
2323                         // iteratively merge the blocks while they are at least half full
2324                         // there's probably a really cool way to do this with a tree...
2325                         while (rgKeyBlocks.Count > 1)
2326                         {
2327                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2328                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2329                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2330                                 {
2331                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2332                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2333                                         {
2334                                                 // merge blocks
2335                                                 kbCurr.nLast = kb.nLast;
2336                                                 kbCurr.Size += kb.Size;
2337                                         }
2338                                         else
2339                                         {
2340                                                 // start a new block
2341                                                 rgKeyBlocksNew.Add (kbCurr);
2342                                                 kbCurr = kb;
2343                                         }
2344                                 }
2345                                 rgKeyBlocksNew.Add (kbCurr);
2346                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2347                                         break;
2348                                 rgKeyBlocks = rgKeyBlocksNew;
2349                         }
2350
2351                         // initialize the key lists
2352                         foreach (KeyBlock kb in rgKeyBlocks)
2353                                 kb.rgKeys = new ArrayList ();
2354
2355                         // fill the key lists
2356                         int iBlockCurr = 0;
2357                         if (rgKeyBlocks.Count > 0) {
2358                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2359                                 foreach (object key in rgKeys)
2360                                 {
2361                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2362                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
2363                                         if (fNextBlock)
2364                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2365                                         kbCurr.rgKeys.Add (key);
2366                                 }
2367                         }
2368
2369                         // sort the blocks so we can tackle the largest ones first
2370                         rgKeyBlocks.Sort ();
2371
2372                         // okay now we can start...
2373                         ILGenerator ig = ec.ig;
2374                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
2375                         Label lblDefault = ig.DefineLabel ();
2376
2377                         Type typeKeys = null;
2378                         if (rgKeys.Length > 0)
2379                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
2380
2381                         Type compare_type;
2382                         
2383                         if (TypeManager.IsEnumType (SwitchType))
2384                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2385                         else
2386                                 compare_type = SwitchType;
2387                         
2388                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2389                         {
2390                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2391                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2392                                 if (kb.Length <= 2)
2393                                 {
2394                                         foreach (object key in kb.rgKeys)
2395                                         {
2396                                                 ig.Emit (OpCodes.Ldloc, val);
2397                                                 EmitObjectInteger (ig, key);
2398                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2399                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
2400                                         }
2401                                 }
2402                                 else
2403                                 {
2404                                         // TODO: if all the keys in the block are the same and there are
2405                                         //       no gaps/defaults then just use a range-check.
2406                                         if (compare_type == TypeManager.int64_type ||
2407                                                 compare_type == TypeManager.uint64_type)
2408                                         {
2409                                                 // TODO: optimize constant/I4 cases
2410
2411                                                 // check block range (could be > 2^31)
2412                                                 ig.Emit (OpCodes.Ldloc, val);
2413                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2414                                                 ig.Emit (OpCodes.Blt, lblDefault);
2415                                                 ig.Emit (OpCodes.Ldloc, val);
2416                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2417                                                 ig.Emit (OpCodes.Bgt, lblDefault);
2418
2419                                                 // normalize range
2420                                                 ig.Emit (OpCodes.Ldloc, val);
2421                                                 if (kb.nFirst != 0)
2422                                                 {
2423                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2424                                                         ig.Emit (OpCodes.Sub);
2425                                                 }
2426                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
2427                                         }
2428                                         else
2429                                         {
2430                                                 // normalize range
2431                                                 ig.Emit (OpCodes.Ldloc, val);
2432                                                 int nFirst = (int) kb.nFirst;
2433                                                 if (nFirst > 0)
2434                                                 {
2435                                                         IntConstant.EmitInt (ig, nFirst);
2436                                                         ig.Emit (OpCodes.Sub);
2437                                                 }
2438                                                 else if (nFirst < 0)
2439                                                 {
2440                                                         IntConstant.EmitInt (ig, -nFirst);
2441                                                         ig.Emit (OpCodes.Add);
2442                                                 }
2443                                         }
2444
2445                                         // first, build the list of labels for the switch
2446                                         int iKey = 0;
2447                                         int cJumps = kb.Length;
2448                                         Label [] rgLabels = new Label [cJumps];
2449                                         for (int iJump = 0; iJump < cJumps; iJump++)
2450                                         {
2451                                                 object key = kb.rgKeys [iKey];
2452                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2453                                                 {
2454                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
2455                                                         rgLabels [iJump] = sl.ILLabel;
2456                                                         iKey++;
2457                                                 }
2458                                                 else
2459                                                         rgLabels [iJump] = lblDefault;
2460                                         }
2461                                         // emit the switch opcode
2462                                         ig.Emit (OpCodes.Switch, rgLabels);
2463                                 }
2464
2465                                 // mark the default for this block
2466                                 if (iBlock != 0)
2467                                         ig.MarkLabel (lblDefault);
2468                         }
2469
2470                         // TODO: find the default case and emit it here,
2471                         //       to prevent having to do the following jump.
2472                         //       make sure to mark other labels in the default section
2473
2474                         // the last default just goes to the end
2475                         ig.Emit (OpCodes.Br, lblDefault);
2476
2477                         // now emit the code for the sections
2478                         bool fFoundDefault = false;
2479                         foreach (SwitchSection ss in Sections)
2480                         {
2481                                 foreach (SwitchLabel sl in ss.Labels)
2482                                 {
2483                                         ig.MarkLabel (sl.ILLabel);
2484                                         ig.MarkLabel (sl.ILLabelCode);
2485                                         if (sl.Label == null)
2486                                         {
2487                                                 ig.MarkLabel (lblDefault);
2488                                                 fFoundDefault = true;
2489                                         }
2490                                 }
2491                                 ss.Block.Emit (ec);
2492                                 //ig.Emit (OpCodes.Br, lblEnd);
2493                         }
2494                         
2495                         if (!fFoundDefault) {
2496                                 ig.MarkLabel (lblDefault);
2497                         }
2498                         ig.MarkLabel (lblEnd);
2499                 }
2500                 //
2501                 // This simple emit switch works, but does not take advantage of the
2502                 // `switch' opcode. 
2503                 // TODO: remove non-string logic from here
2504                 // TODO: binary search strings?
2505                 //
2506                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2507                 {
2508                         ILGenerator ig = ec.ig;
2509                         Label end_of_switch = ig.DefineLabel ();
2510                         Label next_test = ig.DefineLabel ();
2511                         Label null_target = ig.DefineLabel ();
2512                         bool default_found = false;
2513                         bool first_test = true;
2514                         bool pending_goto_end = false;
2515                         bool null_found;
2516                         bool default_at_end = false;
2517                         
2518                         ig.Emit (OpCodes.Ldloc, val);
2519                         
2520                         if (Elements.Contains (NullLiteral.Null)){
2521                                 ig.Emit (OpCodes.Brfalse, null_target);
2522                         } else
2523                                 ig.Emit (OpCodes.Brfalse, default_target);
2524                         
2525                         ig.Emit (OpCodes.Ldloc, val);
2526                         ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2527                         ig.Emit (OpCodes.Stloc, val);
2528                 
2529                         int section_count = Sections.Count;
2530                         for (int section = 0; section < section_count; section++){
2531                                 SwitchSection ss = (SwitchSection) Sections [section];
2532                                 Label sec_begin = ig.DefineLabel ();
2533
2534                                 if (pending_goto_end)
2535                                         ig.Emit (OpCodes.Br, end_of_switch);
2536
2537                                 int label_count = ss.Labels.Count;
2538                                 bool mark_default = false;
2539                                 null_found = false;
2540                                 for (int label = 0; label < label_count; label++){
2541                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2542                                         ig.MarkLabel (sl.ILLabel);
2543                                         
2544                                         if (!first_test){
2545                                                 ig.MarkLabel (next_test);
2546                                                 next_test = ig.DefineLabel ();
2547                                         }
2548                                         //
2549                                         // If we are the default target
2550                                         //
2551                                         if (sl.Label == null){
2552                                                 if (label+1 == label_count)
2553                                                         default_at_end = true;
2554                                                 mark_default = true;
2555                                                 default_found = true;
2556                                         } else {
2557                                                 object lit = sl.Converted;
2558
2559                                                 if (lit is NullLiteral){
2560                                                         null_found = true;
2561                                                         if (label_count == 1)
2562                                                                 ig.Emit (OpCodes.Br, next_test);
2563                                                         continue;
2564                                                                               
2565                                                 }
2566                                                 StringConstant str = (StringConstant) lit;
2567                                                 
2568                                                 ig.Emit (OpCodes.Ldloc, val);
2569                                                 ig.Emit (OpCodes.Ldstr, str.Value);
2570                                                 if (label_count == 1)
2571                                                         ig.Emit (OpCodes.Bne_Un, next_test);
2572                                                 else {
2573                                                         if (label+1 == label_count)
2574                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
2575                                                         else
2576                                                                 ig.Emit (OpCodes.Beq, sec_begin);
2577                                                 }
2578                                         }
2579                                 }
2580                                 if (null_found)
2581                                         ig.MarkLabel (null_target);
2582                                 ig.MarkLabel (sec_begin);
2583                                 foreach (SwitchLabel sl in ss.Labels)
2584                                         ig.MarkLabel (sl.ILLabelCode);
2585
2586                                 if (mark_default)
2587                                         ig.MarkLabel (default_target);
2588                                 ss.Block.Emit (ec);
2589                                 pending_goto_end = !ss.Block.HasRet;
2590                                 first_test = false;
2591                         }
2592                         ig.MarkLabel (next_test);
2593                         if (default_found){
2594                                 if (!default_at_end)
2595                                         ig.Emit (OpCodes.Br, default_target);
2596                         } else 
2597                                 ig.MarkLabel (default_target);
2598                         ig.MarkLabel (end_of_switch);
2599                 }
2600
2601                 public override bool Resolve (EmitContext ec)
2602                 {
2603                         Expr = Expr.Resolve (ec);
2604                         if (Expr == null)
2605                                 return false;
2606
2607                         new_expr = SwitchGoverningType (ec, Expr.Type);
2608                         if (new_expr == null){
2609                                 Report.Error (151, loc, "An integer type or string was expected for switch");
2610                                 return false;
2611                         }
2612
2613                         // Validate switch.
2614                         SwitchType = new_expr.Type;
2615
2616                         if (!CheckSwitch (ec))
2617                                 return false;
2618
2619                         Switch old_switch = ec.Switch;
2620                         ec.Switch = this;
2621                         ec.Switch.SwitchType = SwitchType;
2622
2623                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2624                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2625
2626                         bool first = true;
2627                         foreach (SwitchSection ss in Sections){
2628                                 if (!first)
2629                                         ec.CurrentBranching.CreateSibling (
2630                                                 null, FlowBranching.SiblingType.SwitchSection);
2631                                 else
2632                                         first = false;
2633
2634                                 if (ss.Block.Resolve (ec) != true)
2635                                         return false;
2636                         }
2637
2638
2639                         if (!got_default)
2640                                 ec.CurrentBranching.CreateSibling (
2641                                         null, FlowBranching.SiblingType.SwitchSection);
2642
2643                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2644                         ec.Switch = old_switch;
2645
2646                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2647                                       reachability);
2648
2649                         return true;
2650                 }
2651                 
2652                 protected override void DoEmit (EmitContext ec)
2653                 {
2654                         // Store variable for comparission purposes
2655                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2656                         new_expr.Emit (ec);
2657                         ec.ig.Emit (OpCodes.Stloc, value);
2658
2659                         ILGenerator ig = ec.ig;
2660
2661                         default_target = ig.DefineLabel ();
2662
2663                         //
2664                         // Setup the codegen context
2665                         //
2666                         Label old_end = ec.LoopEnd;
2667                         Switch old_switch = ec.Switch;
2668                         
2669                         ec.LoopEnd = ig.DefineLabel ();
2670                         ec.Switch = this;
2671
2672                         // Emit Code.
2673                         if (SwitchType == TypeManager.string_type)
2674                                 SimpleSwitchEmit (ec, value);
2675                         else
2676                                 TableSwitchEmit (ec, value);
2677
2678                         // Restore context state. 
2679                         ig.MarkLabel (ec.LoopEnd);
2680
2681                         //
2682                         // Restore the previous context
2683                         //
2684                         ec.LoopEnd = old_end;
2685                         ec.Switch = old_switch;
2686                 }
2687         }
2688
2689         public class Lock : Statement {
2690                 Expression expr;
2691                 Statement Statement;
2692                         
2693                 public Lock (Expression expr, Statement stmt, Location l)
2694                 {
2695                         this.expr = expr;
2696                         Statement = stmt;
2697                         loc = l;
2698                 }
2699
2700                 public override bool Resolve (EmitContext ec)
2701                 {
2702                         expr = expr.Resolve (ec);
2703                         if (expr == null)
2704                                 return false;
2705
2706                         if (expr.Type.IsValueType){
2707                                 Error (185, "lock statement requires the expression to be " +
2708                                        " a reference type (type is: `{0}'",
2709                                        TypeManager.CSharpName (expr.Type));
2710                                 return false;
2711                         }
2712
2713                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2714                         bool ok = Statement.Resolve (ec);
2715                         ec.EndFlowBranching ();
2716
2717                         return ok;
2718                 }
2719                 
2720                 protected override void DoEmit (EmitContext ec)
2721                 {
2722                         Type type = expr.Type;
2723                         
2724                         ILGenerator ig = ec.ig;
2725                         LocalBuilder temp = ig.DeclareLocal (type);
2726                                 
2727                         expr.Emit (ec);
2728                         ig.Emit (OpCodes.Dup);
2729                         ig.Emit (OpCodes.Stloc, temp);
2730                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2731
2732                         // try
2733                         ig.BeginExceptionBlock ();
2734                         Label finish = ig.DefineLabel ();
2735                         Statement.Emit (ec);
2736                         // ig.Emit (OpCodes.Leave, finish);
2737
2738                         ig.MarkLabel (finish);
2739                         
2740                         // finally
2741                         ig.BeginFinallyBlock ();
2742                         ig.Emit (OpCodes.Ldloc, temp);
2743                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2744                         ig.EndExceptionBlock ();
2745                 }
2746         }
2747
2748         public class Unchecked : Statement {
2749                 public readonly Block Block;
2750                 
2751                 public Unchecked (Block b)
2752                 {
2753                         Block = b;
2754                         b.Unchecked = true;
2755                 }
2756
2757                 public override bool Resolve (EmitContext ec)
2758                 {
2759                         bool previous_state = ec.CheckState;
2760                         bool previous_state_const = ec.ConstantCheckState;
2761
2762                         ec.CheckState = false;
2763                         ec.ConstantCheckState = false;
2764                         bool ret = Block.Resolve (ec);
2765                         ec.CheckState = previous_state;
2766                         ec.ConstantCheckState = previous_state_const;
2767
2768                         return ret;
2769                 }
2770                 
2771                 protected override void DoEmit (EmitContext ec)
2772                 {
2773                         bool previous_state = ec.CheckState;
2774                         bool previous_state_const = ec.ConstantCheckState;
2775                         
2776                         ec.CheckState = false;
2777                         ec.ConstantCheckState = false;
2778                         Block.Emit (ec);
2779                         ec.CheckState = previous_state;
2780                         ec.ConstantCheckState = previous_state_const;
2781                 }
2782         }
2783
2784         public class Checked : Statement {
2785                 public readonly Block Block;
2786                 
2787                 public Checked (Block b)
2788                 {
2789                         Block = b;
2790                         b.Unchecked = false;
2791                 }
2792
2793                 public override bool Resolve (EmitContext ec)
2794                 {
2795                         bool previous_state = ec.CheckState;
2796                         bool previous_state_const = ec.ConstantCheckState;
2797                         
2798                         ec.CheckState = true;
2799                         ec.ConstantCheckState = true;
2800                         bool ret = Block.Resolve (ec);
2801                         ec.CheckState = previous_state;
2802                         ec.ConstantCheckState = previous_state_const;
2803
2804                         return ret;
2805                 }
2806
2807                 protected override void DoEmit (EmitContext ec)
2808                 {
2809                         bool previous_state = ec.CheckState;
2810                         bool previous_state_const = ec.ConstantCheckState;
2811                         
2812                         ec.CheckState = true;
2813                         ec.ConstantCheckState = true;
2814                         Block.Emit (ec);
2815                         ec.CheckState = previous_state;
2816                         ec.ConstantCheckState = previous_state_const;
2817                 }
2818         }
2819
2820         public class Unsafe : Statement {
2821                 public readonly Block Block;
2822
2823                 public Unsafe (Block b)
2824                 {
2825                         Block = b;
2826                 }
2827
2828                 public override bool Resolve (EmitContext ec)
2829                 {
2830                         bool previous_state = ec.InUnsafe;
2831                         bool val;
2832                         
2833                         ec.InUnsafe = true;
2834                         val = Block.Resolve (ec);
2835                         ec.InUnsafe = previous_state;
2836
2837                         return val;
2838                 }
2839                 
2840                 protected override void DoEmit (EmitContext ec)
2841                 {
2842                         bool previous_state = ec.InUnsafe;
2843                         
2844                         ec.InUnsafe = true;
2845                         Block.Emit (ec);
2846                         ec.InUnsafe = previous_state;
2847                 }
2848         }
2849
2850         // 
2851         // Fixed statement
2852         //
2853         public class Fixed : Statement {
2854                 Expression type;
2855                 ArrayList declarators;
2856                 Statement statement;
2857                 Type expr_type;
2858                 FixedData[] data;
2859                 bool has_ret;
2860
2861                 struct FixedData {
2862                         public bool is_object;
2863                         public LocalInfo vi;
2864                         public Expression expr;
2865                         public Expression converted;
2866                 }                       
2867
2868                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2869                 {
2870                         this.type = type;
2871                         declarators = decls;
2872                         statement = stmt;
2873                         loc = l;
2874                 }
2875
2876                 public override bool Resolve (EmitContext ec)
2877                 {
2878                         if (!ec.InUnsafe){
2879                                 Expression.UnsafeError (loc);
2880                                 return false;
2881                         }
2882                         
2883                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2884                         if (expr_type == null)
2885                                 return false;
2886
2887                         if (ec.RemapToProxy){
2888                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2889                                 return false;
2890                         }
2891                         
2892                         data = new FixedData [declarators.Count];
2893
2894                         if (!expr_type.IsPointer){
2895                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2896                                 return false;
2897                         }
2898                         
2899                         int i = 0;
2900                         foreach (Pair p in declarators){
2901                                 LocalInfo vi = (LocalInfo) p.First;
2902                                 Expression e = (Expression) p.Second;
2903
2904                                 vi.VariableInfo = null;
2905                                 vi.ReadOnly = true;
2906
2907                                 //
2908                                 // The rules for the possible declarators are pretty wise,
2909                                 // but the production on the grammar is more concise.
2910                                 //
2911                                 // So we have to enforce these rules here.
2912                                 //
2913                                 // We do not resolve before doing the case 1 test,
2914                                 // because the grammar is explicit in that the token &
2915                                 // is present, so we need to test for this particular case.
2916                                 //
2917
2918                                 if (e is Cast){
2919                                         Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2920                                         return false;
2921                                 }
2922                                 
2923                                 //
2924                                 // Case 1: & object.
2925                                 //
2926                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2927                                         Expression child = ((Unary) e).Expr;
2928
2929                                         vi.MakePinned ();
2930                                         if (child is ParameterReference || child is LocalVariableReference){
2931                                                 Report.Error (
2932                                                         213, loc, 
2933                                                         "No need to use fixed statement for parameters or " +
2934                                                         "local variable declarations (address is already " +
2935                                                         "fixed)");
2936                                                 return false;
2937                                         }
2938
2939                                         ec.InFixedInitializer = true;
2940                                         e = e.Resolve (ec);
2941                                         ec.InFixedInitializer = false;
2942                                         if (e == null)
2943                                                 return false;
2944
2945                                         child = ((Unary) e).Expr;
2946                                         
2947                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
2948                                                 return false;
2949
2950                                         data [i].is_object = true;
2951                                         data [i].expr = e;
2952                                         data [i].converted = null;
2953                                         data [i].vi = vi;
2954                                         i++;
2955
2956                                         continue;
2957                                 }
2958
2959                                 ec.InFixedInitializer = true;
2960                                 e = e.Resolve (ec);
2961                                 ec.InFixedInitializer = false;
2962                                 if (e == null)
2963                                         return false;
2964
2965                                 //
2966                                 // Case 2: Array
2967                                 //
2968                                 if (e.Type.IsArray){
2969                                         Type array_type = TypeManager.GetElementType (e.Type);
2970                                         
2971                                         vi.MakePinned ();
2972                                         //
2973                                         // Provided that array_type is unmanaged,
2974                                         //
2975                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
2976                                                 return false;
2977
2978                                         //
2979                                         // and T* is implicitly convertible to the
2980                                         // pointer type given in the fixed statement.
2981                                         //
2982                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
2983                                         
2984                                         Expression converted = Convert.ImplicitConversionRequired (
2985                                                 ec, array_ptr, vi.VariableType, loc);
2986                                         if (converted == null)
2987                                                 return false;
2988
2989                                         data [i].is_object = false;
2990                                         data [i].expr = e;
2991                                         data [i].converted = converted;
2992                                         data [i].vi = vi;
2993                                         i++;
2994
2995                                         continue;
2996                                 }
2997
2998                                 //
2999                                 // Case 3: string
3000                                 //
3001                                 if (e.Type == TypeManager.string_type){
3002                                         data [i].is_object = false;
3003                                         data [i].expr = e;
3004                                         data [i].converted = null;
3005                                         data [i].vi = vi;
3006                                         i++;
3007                                         continue;
3008                                 }
3009
3010                                 //
3011                                 // For other cases, flag a `this is already fixed expression'
3012                                 //
3013                                 if (e is LocalVariableReference || e is ParameterReference ||
3014                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3015                                     
3016                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3017                                         return false;
3018                                 }
3019
3020                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3021                                 return false;
3022                         }
3023
3024                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3025
3026                         if (!statement.Resolve (ec)) {
3027                                 ec.KillFlowBranching ();
3028                                 return false;
3029                         }
3030
3031                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3032                         has_ret = reachability.IsUnreachable;
3033
3034                         return true;
3035                 }
3036                 
3037                 protected override void DoEmit (EmitContext ec)
3038                 {
3039                         ILGenerator ig = ec.ig;
3040
3041                         LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3042                         
3043                         for (int i = 0; i < data.Length; i++) {
3044                                 LocalInfo vi = data [i].vi;
3045
3046                                 //
3047                                 // Case 1: & object.
3048                                 //
3049                                 if (data [i].is_object) {
3050                                         //
3051                                         // Store pointer in pinned location
3052                                         //
3053                                         data [i].expr.Emit (ec);
3054                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3055                                         clear_list [i] = vi.LocalBuilder;
3056                                         continue;
3057                                 }
3058
3059                                 //
3060                                 // Case 2: Array
3061                                 //
3062                                 if (data [i].expr.Type.IsArray){
3063                                         //
3064                                         // Store pointer in pinned location
3065                                         //
3066                                         data [i].converted.Emit (ec);
3067                                         
3068                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3069                                         clear_list [i] = vi.LocalBuilder;
3070                                         continue;
3071                                 }
3072
3073                                 //
3074                                 // Case 3: string
3075                                 //
3076                                 if (data [i].expr.Type == TypeManager.string_type){
3077                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3078                                         TypeManager.MakePinned (pinned_string);
3079                                         clear_list [i] = pinned_string;
3080                                         
3081                                         data [i].expr.Emit (ec);
3082                                         ig.Emit (OpCodes.Stloc, pinned_string);
3083
3084                                         Expression sptr = new StringPtr (pinned_string, loc);
3085                                         Expression converted = Convert.ImplicitConversionRequired (
3086                                                 ec, sptr, vi.VariableType, loc);
3087                                         
3088                                         if (converted == null)
3089                                                 continue;
3090
3091                                         converted.Emit (ec);
3092                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3093                                 }
3094                         }
3095
3096                         statement.Emit (ec);
3097
3098                         if (has_ret)
3099                                 return;
3100
3101                         //
3102                         // Clear the pinned variable
3103                         //
3104                         for (int i = 0; i < data.Length; i++) {
3105                                 if (data [i].is_object || data [i].expr.Type.IsArray) {
3106                                         ig.Emit (OpCodes.Ldc_I4_0);
3107                                         ig.Emit (OpCodes.Conv_U);
3108                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3109                                 } else if (data [i].expr.Type == TypeManager.string_type){
3110                                         ig.Emit (OpCodes.Ldnull);
3111                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3112                                 }
3113                         }
3114                 }
3115         }
3116         
3117         public class Catch {
3118                 public readonly string Name;
3119                 public readonly Block  Block;
3120                 public readonly Location Location;
3121
3122                 Expression type_expr;
3123                 Type type;
3124                 
3125                 public Catch (Expression type, string name, Block block, Location l)
3126                 {
3127                         type_expr = type;
3128                         Name = name;
3129                         Block = block;
3130                         Location = l;
3131                 }
3132
3133                 public Type CatchType {
3134                         get {
3135                                 return type;
3136                         }
3137                 }
3138
3139                 public bool IsGeneral {
3140                         get {
3141                                 return type_expr == null;
3142                         }
3143                 }
3144
3145                 public bool Resolve (EmitContext ec)
3146                 {
3147                         if (type_expr != null) {
3148                                 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3149                                 if (type == null)
3150                                         return false;
3151
3152                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3153                                         Report.Error (155, Location,
3154                                                       "The type caught or thrown must be derived " +
3155                                                       "from System.Exception");
3156                                         return false;
3157                                 }
3158                         } else
3159                                 type = null;
3160
3161                         if (!Block.Resolve (ec))
3162                                 return false;
3163
3164                         return true;
3165                 }
3166         }
3167
3168         public class Try : Statement {
3169                 public readonly Block Fini, Block;
3170                 public readonly ArrayList Specific;
3171                 public readonly Catch General;
3172                 
3173                 //
3174                 // specific, general and fini might all be null.
3175                 //
3176                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3177                 {
3178                         if (specific == null && general == null){
3179                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3180                         }
3181                         
3182                         this.Block = block;
3183                         this.Specific = specific;
3184                         this.General = general;
3185                         this.Fini = fini;
3186                         loc = l;
3187                 }
3188
3189                 public override bool Resolve (EmitContext ec)
3190                 {
3191                         bool ok = true;
3192                         
3193                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3194
3195                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3196
3197                         if (!Block.Resolve (ec))
3198                                 ok = false;
3199
3200                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3201
3202                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3203
3204                         foreach (Catch c in Specific){
3205                                 ec.CurrentBranching.CreateSibling (
3206                                         c.Block, FlowBranching.SiblingType.Catch);
3207
3208                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3209
3210                                 if (c.Name != null) {
3211                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3212                                         if (vi == null)
3213                                                 throw new Exception ();
3214
3215                                         vi.VariableInfo = null;
3216                                 }
3217
3218                                 if (!c.Resolve (ec))
3219                                         ok = false;
3220                         }
3221
3222                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3223
3224                         if (General != null){
3225                                 ec.CurrentBranching.CreateSibling (
3226                                         General.Block, FlowBranching.SiblingType.Catch);
3227
3228                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3229
3230                                 if (!General.Resolve (ec))
3231                                         ok = false;
3232                         }
3233
3234                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3235
3236                         if (Fini != null) {
3237                                 if (ok)
3238                                         ec.CurrentBranching.CreateSibling (
3239                                                 Fini, FlowBranching.SiblingType.Finally);
3240
3241                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3242
3243                                 if (!Fini.Resolve (ec))
3244                                         ok = false;
3245                         }
3246
3247                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3248
3249                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3250
3251                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3252
3253                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3254                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3255                                 // to the end of the finally block.  This is a problem if `returns'
3256                                 // is true since we may jump to a point after the end of the method.
3257                                 // As a workaround, emit an explicit ret here.
3258                                 ec.NeedReturnLabel ();
3259                         }
3260
3261                         return ok;
3262                 }
3263                 
3264                 protected override void DoEmit (EmitContext ec)
3265                 {
3266                         ILGenerator ig = ec.ig;
3267                         Label finish = ig.DefineLabel ();;
3268
3269                         ig.BeginExceptionBlock ();
3270                         Block.Emit (ec);
3271
3272                         //
3273                         // System.Reflection.Emit provides this automatically:
3274                         // ig.Emit (OpCodes.Leave, finish);
3275
3276                         foreach (Catch c in Specific){
3277                                 LocalInfo vi;
3278                                 
3279                                 ig.BeginCatchBlock (c.CatchType);
3280
3281                                 if (c.Name != null){
3282                                         vi = c.Block.GetLocalInfo (c.Name);
3283                                         if (vi == null)
3284                                                 throw new Exception ("Variable does not exist in this block");
3285
3286                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3287                                 } else
3288                                         ig.Emit (OpCodes.Pop);
3289                                 
3290                                 c.Block.Emit (ec);
3291                         }
3292
3293                         if (General != null){
3294                                 ig.BeginCatchBlock (TypeManager.object_type);
3295                                 ig.Emit (OpCodes.Pop);
3296                                 General.Block.Emit (ec);
3297                         }
3298
3299                         ig.MarkLabel (finish);
3300                         if (Fini != null){
3301                                 ig.BeginFinallyBlock ();
3302                                 Fini.Emit (ec);
3303                         }
3304                         
3305                         ig.EndExceptionBlock ();
3306                 }
3307         }
3308
3309         public class Using : Statement {
3310                 object expression_or_block;
3311                 Statement Statement;
3312                 ArrayList var_list;
3313                 Expression expr;
3314                 Type expr_type;
3315                 Expression conv;
3316                 Expression [] converted_vars;
3317                 ExpressionStatement [] assign;
3318                 
3319                 public Using (object expression_or_block, Statement stmt, Location l)
3320                 {
3321                         this.expression_or_block = expression_or_block;
3322                         Statement = stmt;
3323                         loc = l;
3324                 }
3325
3326                 //
3327                 // Resolves for the case of using using a local variable declaration.
3328                 //
3329                 bool ResolveLocalVariableDecls (EmitContext ec)
3330                 {
3331                         bool need_conv = false;
3332                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3333                         int i = 0;
3334
3335                         if (expr_type == null)
3336                                 return false;
3337
3338                         //
3339                         // The type must be an IDisposable or an implicit conversion
3340                         // must exist.
3341                         //
3342                         converted_vars = new Expression [var_list.Count];
3343                         assign = new ExpressionStatement [var_list.Count];
3344                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3345                                 foreach (DictionaryEntry e in var_list){
3346                                         Expression var = (Expression) e.Key;
3347
3348                                         var = var.ResolveLValue (ec, new EmptyExpression ());
3349                                         if (var == null)
3350                                                 return false;
3351                                         
3352                                         converted_vars [i] = Convert.ImplicitConversionRequired (
3353                                                 ec, var, TypeManager.idisposable_type, loc);
3354
3355                                         if (converted_vars [i] == null)
3356                                                 return false;
3357                                         i++;
3358                                 }
3359                                 need_conv = true;
3360                         }
3361
3362                         i = 0;
3363                         foreach (DictionaryEntry e in var_list){
3364                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3365                                 Expression new_expr = (Expression) e.Value;
3366                                 Expression a;
3367
3368                                 a = new Assign (var, new_expr, loc);
3369                                 a = a.Resolve (ec);
3370                                 if (a == null)
3371                                         return false;
3372
3373                                 if (!need_conv)
3374                                         converted_vars [i] = var;
3375                                 assign [i] = (ExpressionStatement) a;
3376                                 i++;
3377                         }
3378
3379                         return true;
3380                 }
3381
3382                 bool ResolveExpression (EmitContext ec)
3383                 {
3384                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3385                                 conv = Convert.ImplicitConversionRequired (
3386                                         ec, expr, TypeManager.idisposable_type, loc);
3387
3388                                 if (conv == null)
3389                                         return false;
3390                         }
3391
3392                         return true;
3393                 }
3394                 
3395                 //
3396                 // Emits the code for the case of using using a local variable declaration.
3397                 //
3398                 bool EmitLocalVariableDecls (EmitContext ec)
3399                 {
3400                         ILGenerator ig = ec.ig;
3401                         int i = 0;
3402
3403                         for (i = 0; i < assign.Length; i++) {
3404                                 assign [i].EmitStatement (ec);
3405                                 
3406                                 ig.BeginExceptionBlock ();
3407                         }
3408                         Statement.Emit (ec);
3409
3410                         var_list.Reverse ();
3411                         foreach (DictionaryEntry e in var_list){
3412                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3413                                 Label skip = ig.DefineLabel ();
3414                                 i--;
3415                                 
3416                                 ig.BeginFinallyBlock ();
3417
3418                                 if (!var.Type.IsValueType) {
3419                                         var.Emit (ec);
3420                                         ig.Emit (OpCodes.Brfalse, skip);
3421                                         converted_vars [i].Emit (ec);
3422                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3423                                 } else {
3424                                         Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3425
3426                                         if (!(ml is MethodGroupExpr)) {
3427                                                 var.Emit (ec);
3428                                                 ig.Emit (OpCodes.Box, var.Type);
3429                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3430                                         } else {
3431                                                 MethodInfo mi = null;
3432
3433                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3434                                                         if (mk.GetParameters().Length == 0) {
3435                                                                 mi = mk;
3436                                                                 break;
3437                                                         }
3438                                                 }
3439
3440                                                 if (mi == null) {
3441                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3442                                                         return false;
3443                                                 }
3444
3445                                                 var.AddressOf (ec, AddressOp.Load);
3446                                                 ig.Emit (OpCodes.Call, mi);
3447                                         }
3448                                 }
3449
3450                                 ig.MarkLabel (skip);
3451                                 ig.EndExceptionBlock ();
3452                         }
3453
3454                         return false;
3455                 }
3456
3457                 bool EmitExpression (EmitContext ec)
3458                 {
3459                         //
3460                         // Make a copy of the expression and operate on that.
3461                         //
3462                         ILGenerator ig = ec.ig;
3463                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3464                         if (conv != null)
3465                                 conv.Emit (ec);
3466                         else
3467                                 expr.Emit (ec);
3468                         ig.Emit (OpCodes.Stloc, local_copy);
3469
3470                         ig.BeginExceptionBlock ();
3471                         Statement.Emit (ec);
3472                         
3473                         Label skip = ig.DefineLabel ();
3474                         ig.BeginFinallyBlock ();
3475                         ig.Emit (OpCodes.Ldloc, local_copy);
3476                         ig.Emit (OpCodes.Brfalse, skip);
3477                         ig.Emit (OpCodes.Ldloc, local_copy);
3478                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3479                         ig.MarkLabel (skip);
3480                         ig.EndExceptionBlock ();
3481
3482                         return false;
3483                 }
3484                 
3485                 public override bool Resolve (EmitContext ec)
3486                 {
3487                         if (expression_or_block is DictionaryEntry){
3488                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3489                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3490
3491                                 if (!ResolveLocalVariableDecls (ec))
3492                                         return false;
3493
3494                         } else if (expression_or_block is Expression){
3495                                 expr = (Expression) expression_or_block;
3496
3497                                 expr = expr.Resolve (ec);
3498                                 if (expr == null)
3499                                         return false;
3500
3501                                 expr_type = expr.Type;
3502
3503                                 if (!ResolveExpression (ec))
3504                                         return false;
3505                         }
3506
3507                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3508
3509                         bool ok = Statement.Resolve (ec);
3510
3511                         if (!ok) {
3512                                 ec.KillFlowBranching ();
3513                                 return false;
3514                         }
3515                                         
3516                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3517
3518                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3519                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3520                                 // to the end of the finally block.  This is a problem if `returns'
3521                                 // is true since we may jump to a point after the end of the method.
3522                                 // As a workaround, emit an explicit ret here.
3523                                 ec.NeedReturnLabel ();
3524                         }
3525
3526                         return true;
3527                 }
3528                 
3529                 protected override void DoEmit (EmitContext ec)
3530                 {
3531                         if (expression_or_block is DictionaryEntry)
3532                                 EmitLocalVariableDecls (ec);
3533                         else if (expression_or_block is Expression)
3534                                 EmitExpression (ec);
3535                 }
3536         }
3537
3538         /// <summary>
3539         ///   Implementation of the foreach C# statement
3540         /// </summary>
3541         public class Foreach : Statement {
3542                 Expression type;
3543                 Expression variable;
3544                 Expression expr;
3545                 Statement statement;
3546                 ForeachHelperMethods hm;
3547                 Expression empty, conv;
3548                 Type array_type, element_type;
3549                 Type var_type;
3550                 
3551                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3552                                 Statement stmt, Location l)
3553                 {
3554                         this.type = type;
3555                         this.variable = var;
3556                         this.expr = expr;
3557                         statement = stmt;
3558                         loc = l;
3559                 }
3560                 
3561                 public override bool Resolve (EmitContext ec)
3562                 {
3563                         expr = expr.Resolve (ec);
3564                         if (expr == null)
3565                                 return false;
3566
3567                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
3568                         if (var_type == null)
3569                                 return false;
3570                         
3571                         //
3572                         // We need an instance variable.  Not sure this is the best
3573                         // way of doing this.
3574                         //
3575                         // FIXME: When we implement propertyaccess, will those turn
3576                         // out to return values in ExprClass?  I think they should.
3577                         //
3578                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3579                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3580                                 error1579 (expr.Type);
3581                                 return false;
3582                         }
3583
3584                         if (expr.Type.IsArray) {
3585                                 array_type = expr.Type;
3586                                 element_type = TypeManager.GetElementType (array_type);
3587
3588                                 empty = new EmptyExpression (element_type);
3589                         } else {
3590                                 hm = ProbeCollectionType (ec, expr.Type);
3591                                 if (hm == null){
3592                                         error1579 (expr.Type);
3593                                         return false;
3594                                 }                       
3595
3596                                 array_type = expr.Type;
3597                                 element_type = hm.element_type;
3598
3599                                 empty = new EmptyExpression (hm.element_type);
3600                         }
3601
3602                         bool ok = true;
3603
3604                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3605                         ec.CurrentBranching.CreateSibling ();
3606
3607                         //
3608                         //
3609                         // FIXME: maybe we can apply the same trick we do in the
3610                         // array handling to avoid creating empty and conv in some cases.
3611                         //
3612                         // Although it is not as important in this case, as the type
3613                         // will not likely be object (what the enumerator will return).
3614                         //
3615                         conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3616                         if (conv == null)
3617                                 ok = false;
3618
3619                         variable = variable.ResolveLValue (ec, empty);
3620                         if (variable == null)
3621                                 ok = false;
3622
3623                         bool disposable = (hm != null) && hm.is_disposable;
3624                         if (disposable)
3625                                 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3626
3627                         if (!statement.Resolve (ec))
3628                                 ok = false;
3629
3630                         if (disposable)
3631                                 ec.EndFlowBranching ();
3632
3633                         ec.EndFlowBranching ();
3634
3635                         return ok;
3636                 }
3637                 
3638                 //
3639                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3640                 //
3641                 static MethodInfo FetchMethodMoveNext (Type t)
3642                 {
3643                         MemberList move_next_list;
3644                         
3645                         move_next_list = TypeContainer.FindMembers (
3646                                 t, MemberTypes.Method,
3647                                 BindingFlags.Public | BindingFlags.Instance,
3648                                 Type.FilterName, "MoveNext");
3649                         if (move_next_list.Count == 0)
3650                                 return null;
3651
3652                         foreach (MemberInfo m in move_next_list){
3653                                 MethodInfo mi = (MethodInfo) m;
3654                                 Type [] args;
3655                                 
3656                                 args = TypeManager.GetArgumentTypes (mi);
3657                                 if (args != null && args.Length == 0){
3658                                         if (mi.ReturnType == TypeManager.bool_type)
3659                                                 return mi;
3660                                 }
3661                         }
3662                         return null;
3663                 }
3664                 
3665                 //
3666                 // Retrieves a `public T get_Current ()' method from the Type `t'
3667                 //
3668                 static MethodInfo FetchMethodGetCurrent (Type t)
3669                 {
3670                         MemberList get_current_list;
3671
3672                         get_current_list = TypeContainer.FindMembers (
3673                                 t, MemberTypes.Method,
3674                                 BindingFlags.Public | BindingFlags.Instance,
3675                                 Type.FilterName, "get_Current");
3676                         if (get_current_list.Count == 0)
3677                                 return null;
3678
3679                         foreach (MemberInfo m in get_current_list){
3680                                 MethodInfo mi = (MethodInfo) m;
3681                                 Type [] args;
3682
3683                                 args = TypeManager.GetArgumentTypes (mi);
3684                                 if (args != null && args.Length == 0)
3685                                         return mi;
3686                         }
3687                         return null;
3688                 }
3689
3690                 // 
3691                 // This struct records the helper methods used by the Foreach construct
3692                 //
3693                 class ForeachHelperMethods {
3694                         public EmitContext ec;
3695                         public MethodInfo get_enumerator;
3696                         public MethodInfo move_next;
3697                         public MethodInfo get_current;
3698                         public Type element_type;
3699                         public Type enumerator_type;
3700                         public bool is_disposable;
3701
3702                         public ForeachHelperMethods (EmitContext ec)
3703                         {
3704                                 this.ec = ec;
3705                                 this.element_type = TypeManager.object_type;
3706                                 this.enumerator_type = TypeManager.ienumerator_type;
3707                                 this.is_disposable = true;
3708                         }
3709                 }
3710                 
3711                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3712                 {
3713                         if (m == null)
3714                                 return false;
3715                         
3716                         if (!(m is MethodInfo))
3717                                 return false;
3718                         
3719                         if (m.Name != "GetEnumerator")
3720                                 return false;
3721
3722                         MethodInfo mi = (MethodInfo) m;
3723                         Type [] args = TypeManager.GetArgumentTypes (mi);
3724                         if (args != null){
3725                                 if (args.Length != 0)
3726                                         return false;
3727                         }
3728                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3729                         EmitContext ec = hm.ec;
3730
3731                         //
3732                         // Check whether GetEnumerator is accessible to us
3733                         //
3734                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3735
3736                         Type declaring = mi.DeclaringType;
3737                         if (prot == MethodAttributes.Private){
3738                                 if (declaring != ec.ContainerType)
3739                                         return false;
3740                         } else if (prot == MethodAttributes.FamANDAssem){
3741                                 // If from a different assembly, false
3742                                 if (!(mi is MethodBuilder))
3743                                         return false;
3744                                 //
3745                                 // Are we being invoked from the same class, or from a derived method?
3746                                 //
3747                                 if (ec.ContainerType != declaring){
3748                                         if (!ec.ContainerType.IsSubclassOf (declaring))
3749                                                 return false;
3750                                 }
3751                         } else if (prot == MethodAttributes.FamORAssem){
3752                                 if (!(mi is MethodBuilder ||
3753                                       ec.ContainerType == declaring ||
3754                                       ec.ContainerType.IsSubclassOf (declaring)))
3755                                         return false;
3756                         } if (prot == MethodAttributes.Family){
3757                                 if (!(ec.ContainerType == declaring ||
3758                                       ec.ContainerType.IsSubclassOf (declaring)))
3759                                         return false;
3760                         }
3761
3762                         if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3763                                 //
3764                                 // Apply the same optimization as MS: skip the GetEnumerator
3765                                 // returning an IEnumerator, and use the one returning a 
3766                                 // CharEnumerator instead. This allows us to avoid the 
3767                                 // try-finally block and the boxing.
3768                                 //
3769                                 return false;
3770
3771                         //
3772                         // Ok, we can access it, now make sure that we can do something
3773                         // with this `GetEnumerator'
3774                         //
3775                         
3776                         Type return_type = mi.ReturnType;
3777                         if (mi.ReturnType == TypeManager.ienumerator_type ||
3778                             TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3779                             (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3780                                 
3781                                 //
3782                                 // If it is not an interface, lets try to find the methods ourselves.
3783                                 // For example, if we have:
3784                                 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3785                                 // We can avoid the iface call. This is a runtime perf boost.
3786                                 // even bigger if we have a ValueType, because we avoid the cost
3787                                 // of boxing.
3788                                 //
3789                                 // We have to make sure that both methods exist for us to take
3790                                 // this path. If one of the methods does not exist, we will just
3791                                 // use the interface. Sadly, this complex if statement is the only
3792                                 // way I could do this without a goto
3793                                 //
3794                                 
3795                                 if (return_type.IsInterface ||
3796                                     (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3797                                     (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3798                                         
3799                                         hm.move_next = TypeManager.bool_movenext_void;
3800                                         hm.get_current = TypeManager.object_getcurrent_void;
3801                                         return true;    
3802                                 }
3803
3804                         } else {
3805
3806                                 //
3807                                 // Ok, so they dont return an IEnumerable, we will have to
3808                                 // find if they support the GetEnumerator pattern.
3809                                 //
3810                                 
3811                                 hm.move_next = FetchMethodMoveNext (return_type);
3812                                 if (hm.move_next == null)
3813                                         return false;
3814                                 
3815                                 hm.get_current = FetchMethodGetCurrent (return_type);
3816                                 if (hm.get_current == null)
3817                                         return false;
3818                         }
3819                         
3820                         hm.element_type = hm.get_current.ReturnType;
3821                         hm.enumerator_type = return_type;
3822                         hm.is_disposable = !hm.enumerator_type.IsSealed ||
3823                                 TypeManager.ImplementsInterface (
3824                                         hm.enumerator_type, TypeManager.idisposable_type);
3825
3826                         return true;
3827                 }
3828                 
3829                 /// <summary>
3830                 ///   This filter is used to find the GetEnumerator method
3831                 ///   on which IEnumerator operates
3832                 /// </summary>
3833                 static MemberFilter FilterEnumerator;
3834                 
3835                 static Foreach ()
3836                 {
3837                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3838                 }
3839
3840                 void error1579 (Type t)
3841                 {
3842                         Report.Error (1579, loc,
3843                                       "foreach statement cannot operate on variables of type `" +
3844                                       t.FullName + "' because that class does not provide a " +
3845                                       " GetEnumerator method or it is inaccessible");
3846                 }
3847
3848                 static bool TryType (Type t, ForeachHelperMethods hm)
3849                 {
3850                         MemberList mi;
3851                         
3852                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3853                                                         BindingFlags.Public | BindingFlags.NonPublic |
3854                                                         BindingFlags.Instance | BindingFlags.DeclaredOnly,
3855                                                         FilterEnumerator, hm);
3856
3857                         if (mi.Count == 0)
3858                                 return false;
3859
3860                         hm.get_enumerator = (MethodInfo) mi [0];
3861                         return true;    
3862                 }
3863                 
3864                 //
3865                 // Looks for a usable GetEnumerator in the Type, and if found returns
3866                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3867                 //
3868                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3869                 {
3870                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3871
3872                         for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3873                                 if (TryType (tt, hm))
3874                                         return hm;
3875                                 tt = tt.BaseType;
3876                         }
3877
3878                         //
3879                         // Now try to find the method in the interfaces
3880                         //
3881                         while (t != null){
3882                                 Type [] ifaces = t.GetInterfaces ();
3883
3884                                 foreach (Type i in ifaces){
3885                                         if (TryType (i, hm))
3886                                                 return hm;
3887                                 }
3888                                 
3889                                 //
3890                                 // Since TypeBuilder.GetInterfaces only returns the interface
3891                                 // types for this type, we have to keep looping, but once
3892                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3893                                 // done, because it returns all the types
3894                                 //
3895                                 if ((t is TypeBuilder))
3896                                         t = t.BaseType;
3897                                 else
3898                                         break;
3899                         } 
3900
3901                         return null;
3902                 }
3903
3904                 //
3905                 // FIXME: possible optimization.
3906                 // We might be able to avoid creating `empty' if the type is the sam
3907                 //
3908                 bool EmitCollectionForeach (EmitContext ec)
3909                 {
3910                         ILGenerator ig = ec.ig;
3911                         VariableStorage enumerator;
3912
3913                         enumerator = new VariableStorage (ec, hm.enumerator_type);
3914                         enumerator.EmitThis ();
3915                         //
3916                         // Instantiate the enumerator
3917                         //
3918                         if (expr.Type.IsValueType){
3919                                 if (expr is IMemoryLocation){
3920                                         IMemoryLocation ml = (IMemoryLocation) expr;
3921
3922                                         Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
3923
3924                                         if (!(ml1 is MethodGroupExpr)) {
3925                                                 expr.Emit(ec);
3926                                                 ec.ig.Emit(OpCodes.Box, expr.Type);
3927                                         } else {
3928                                                 ml.AddressOf (ec, AddressOp.Load);
3929                                         }
3930                                 } else
3931                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
3932                                                              " does not implement IMemoryLocation");
3933                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3934                         } else {
3935                                 expr.Emit (ec);
3936                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3937                         }
3938                         enumerator.EmitStore ();
3939
3940                         //
3941                         // Protect the code in a try/finalize block, so that
3942                         // if the beast implement IDisposable, we get rid of it
3943                         //
3944                         if (hm.is_disposable)
3945                                 ig.BeginExceptionBlock ();
3946                         
3947                         Label end_try = ig.DefineLabel ();
3948                         
3949                         ig.MarkLabel (ec.LoopBegin);
3950                         
3951                         enumerator.EmitCall (hm.move_next);
3952                         
3953                         ig.Emit (OpCodes.Brfalse, end_try);
3954                         if (ec.InIterator)
3955                                 ec.EmitThis ();
3956                         
3957                         enumerator.EmitCall (hm.get_current);
3958
3959                         if (ec.InIterator){
3960                                 conv.Emit (ec);
3961                                 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3962                         } else 
3963                                 ((IAssignMethod)variable).EmitAssign (ec, conv);
3964                                 
3965                         statement.Emit (ec);
3966                         ig.Emit (OpCodes.Br, ec.LoopBegin);
3967                         ig.MarkLabel (end_try);
3968                         
3969                         // The runtime provides this for us.
3970                         // ig.Emit (OpCodes.Leave, end);
3971
3972                         //
3973                         // Now the finally block
3974                         //
3975                         if (hm.is_disposable) {
3976                                 Label call_dispose = ig.DefineLabel ();
3977                                 ig.BeginFinallyBlock ();
3978                                 
3979                                 enumerator.EmitThis ();
3980                                 enumerator.EmitLoad ();
3981                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3982                                 ig.Emit (OpCodes.Dup);
3983                                 ig.Emit (OpCodes.Brtrue_S, call_dispose);
3984                                 ig.Emit (OpCodes.Pop);
3985                                 ig.Emit (OpCodes.Endfinally);
3986                                 
3987                                 ig.MarkLabel (call_dispose);
3988                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3989                                 
3990
3991                                 // The runtime generates this anyways.
3992                                 // ig.Emit (OpCodes.Endfinally);
3993
3994                                 ig.EndExceptionBlock ();
3995                         }
3996
3997                         ig.MarkLabel (ec.LoopEnd);
3998                         return false;
3999                 }
4000
4001                 //
4002                 // FIXME: possible optimization.
4003                 // We might be able to avoid creating `empty' if the type is the sam
4004                 //
4005                 bool EmitArrayForeach (EmitContext ec)
4006                 {
4007                         int rank = array_type.GetArrayRank ();
4008                         ILGenerator ig = ec.ig;
4009
4010                         VariableStorage copy = new VariableStorage (ec, array_type);
4011                         
4012                         //
4013                         // Make our copy of the array
4014                         //
4015                         copy.EmitThis ();
4016                         expr.Emit (ec);
4017                         copy.EmitStore ();
4018                         
4019                         if (rank == 1){
4020                                 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4021
4022                                 Label loop, test;
4023
4024                                 counter.EmitThis ();
4025                                 ig.Emit (OpCodes.Ldc_I4_0);
4026                                 counter.EmitStore ();
4027                                 test = ig.DefineLabel ();
4028                                 ig.Emit (OpCodes.Br, test);
4029
4030                                 loop = ig.DefineLabel ();
4031                                 ig.MarkLabel (loop);
4032
4033                                 if (ec.InIterator)
4034                                         ec.EmitThis ();
4035                                 
4036                                 copy.EmitThis ();
4037                                 copy.EmitLoad ();
4038                                 counter.EmitThis ();
4039                                 counter.EmitLoad ();
4040
4041                                 //
4042                                 // Load the value, we load the value using the underlying type,
4043                                 // then we use the variable.EmitAssign to load using the proper cast.
4044                                 //
4045                                 ArrayAccess.EmitLoadOpcode (ig, element_type);
4046                                 if (ec.InIterator){
4047                                         conv.Emit (ec);
4048                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4049                                 } else 
4050                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4051
4052                                 statement.Emit (ec);
4053
4054                                 ig.MarkLabel (ec.LoopBegin);
4055                                 counter.EmitThis ();
4056                                 counter.EmitThis ();
4057                                 counter.EmitLoad ();
4058                                 ig.Emit (OpCodes.Ldc_I4_1);
4059                                 ig.Emit (OpCodes.Add);
4060                                 counter.EmitStore ();
4061
4062                                 ig.MarkLabel (test);
4063                                 counter.EmitThis ();
4064                                 counter.EmitLoad ();
4065                                 copy.EmitThis ();
4066                                 copy.EmitLoad ();
4067                                 ig.Emit (OpCodes.Ldlen);
4068                                 ig.Emit (OpCodes.Conv_I4);
4069                                 ig.Emit (OpCodes.Blt, loop);
4070                         } else {
4071                                 VariableStorage [] dim_len   = new VariableStorage [rank];
4072                                 VariableStorage [] dim_count = new VariableStorage [rank];
4073                                 Label [] loop = new Label [rank];
4074                                 Label [] test = new Label [rank];
4075                                 int dim;
4076                                 
4077                                 for (dim = 0; dim < rank; dim++){
4078                                         dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4079                                         dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4080                                         test [dim] = ig.DefineLabel ();
4081                                         loop [dim] = ig.DefineLabel ();
4082                                 }
4083                                         
4084                                 for (dim = 0; dim < rank; dim++){
4085                                         dim_len [dim].EmitThis ();
4086                                         copy.EmitThis ();
4087                                         copy.EmitLoad ();
4088                                         IntLiteral.EmitInt (ig, dim);
4089                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4090                                         dim_len [dim].EmitStore ();
4091                                         
4092                                 }
4093
4094                                 for (dim = 0; dim < rank; dim++){
4095                                         dim_count [dim].EmitThis ();
4096                                         ig.Emit (OpCodes.Ldc_I4_0);
4097                                         dim_count [dim].EmitStore ();
4098                                         ig.Emit (OpCodes.Br, test [dim]);
4099                                         ig.MarkLabel (loop [dim]);
4100                                 }
4101
4102                                 if (ec.InIterator)
4103                                         ec.EmitThis ();
4104                                 copy.EmitThis ();
4105                                 copy.EmitLoad ();
4106                                 for (dim = 0; dim < rank; dim++){
4107                                         dim_count [dim].EmitThis ();
4108                                         dim_count [dim].EmitLoad ();
4109                                 }
4110
4111                                 //
4112                                 // FIXME: Maybe we can cache the computation of `get'?
4113                                 //
4114                                 Type [] args = new Type [rank];
4115                                 MethodInfo get;
4116
4117                                 for (int i = 0; i < rank; i++)
4118                                         args [i] = TypeManager.int32_type;
4119
4120                                 ModuleBuilder mb = CodeGen.Module.Builder;
4121                                 get = mb.GetArrayMethod (
4122                                         array_type, "Get",
4123                                         CallingConventions.HasThis| CallingConventions.Standard,
4124                                         var_type, args);
4125                                 ig.Emit (OpCodes.Call, get);
4126                                 if (ec.InIterator){
4127                                         conv.Emit (ec);
4128                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4129                                 } else 
4130                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4131                                 statement.Emit (ec);
4132                                 ig.MarkLabel (ec.LoopBegin);
4133                                 for (dim = rank - 1; dim >= 0; dim--){
4134                                         dim_count [dim].EmitThis ();
4135                                         dim_count [dim].EmitThis ();
4136                                         dim_count [dim].EmitLoad ();
4137                                         ig.Emit (OpCodes.Ldc_I4_1);
4138                                         ig.Emit (OpCodes.Add);
4139                                         dim_count [dim].EmitStore ();
4140
4141                                         ig.MarkLabel (test [dim]);
4142                                         dim_count [dim].EmitThis ();
4143                                         dim_count [dim].EmitLoad ();
4144                                         dim_len [dim].EmitThis ();
4145                                         dim_len [dim].EmitLoad ();
4146                                         ig.Emit (OpCodes.Blt, loop [dim]);
4147                                 }
4148                         }
4149                         ig.MarkLabel (ec.LoopEnd);
4150                         
4151                         return false;
4152                 }
4153                 
4154                 protected override void DoEmit (EmitContext ec)
4155                 {
4156                         ILGenerator ig = ec.ig;
4157                         
4158                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4159                         ec.LoopBegin = ig.DefineLabel ();
4160                         ec.LoopEnd = ig.DefineLabel ();
4161                         
4162                         if (hm != null)
4163                                 EmitCollectionForeach (ec);
4164                         else
4165                                 EmitArrayForeach (ec);
4166                         
4167                         ec.LoopBegin = old_begin;
4168                         ec.LoopEnd = old_end;
4169                 }
4170         }
4171 }