2004-05-24 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / mcs / statement.cs
index e54773726e2aab1cfe62372cad5f3ab71a4a6fd6..203e61d58bf9c0fc51f3aeecf25aaeace77b483e 100755 (executable)
@@ -21,89 +21,86 @@ namespace Mono.CSharp {
        public abstract class Statement {
                public Location loc;
                
-               ///
-               /// Resolves the statement, true means that all sub-statements
-               /// did resolve ok.
-               //
+               /// <summary>
+               ///   Resolves the statement, true means that all sub-statements
+               ///   did resolve ok.
+               //  </summary>
                public virtual bool Resolve (EmitContext ec)
                {
                        return true;
                }
+
+               /// <summary>
+               ///   We already know that the statement is unreachable, but we still
+               ///   need to resolve it to catch errors.
+               /// </summary>
+               public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
+               {
+                       //
+                       // This conflicts with csc's way of doing this, but IMHO it's
+                       // the right thing to do.
+                       //
+                       // If something is unreachable, we still check whether it's
+                       // correct.  This means that you cannot use unassigned variables
+                       // in unreachable code, for instance.
+                       //
+
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
+                       bool ok = Resolve (ec);
+                       ec.KillFlowBranching ();
+
+                       if (!ok)
+                               return false;
+
+                       if (warn)
+                               Report.Warning (162, loc, "Unreachable code detected");
+                       return true;
+               }
                
                /// <summary>
                ///   Return value indicates whether all code paths emitted return.
                /// </summary>
-               protected abstract bool DoEmit (EmitContext ec);
+               protected abstract void DoEmit (EmitContext ec);
 
                /// <summary>
-               ///   Return value indicates whether all code paths emitted return.
+               ///   Utility wrapper routine for Error, just to beautify the code
                /// </summary>
-               public virtual bool Emit (EmitContext ec)
+               public void Error (int error, string format, params object[] args)
                {
-                       ec.Mark (loc, true);
-                       return DoEmit (ec);
+                       Error (error, String.Format (format, args));
                }
-               
-               /// <remarks>
-               ///    Encapsulates the emission of a boolean test and jumping to a
-               ///    destination.
-               ///
-               ///    This will emit the bool expression in `bool_expr' and if
-               ///    `target_is_for_true' is true, then the code will generate a 
-               ///    brtrue to the target.   Otherwise a brfalse. 
-               /// </remarks>
-               public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
-                                                      Label target, bool target_is_for_true)
-               {
-                       ILGenerator ig = ec.ig;
-                       
-                       bool invert = false;
-                       if (bool_expr is Unary){
-                               Unary u = (Unary) bool_expr;
-                               
-                               if (u.Oper == Unary.Operator.LogicalNot){
-                                       invert = true;
-
-                                       u.EmitLogicalNot (ec);
-                               }
-                       } else if (bool_expr is Binary){
-                               Binary b = (Binary) bool_expr;
-
-                               if (b.EmitBranchable (ec, target, target_is_for_true))
-                                       return;
-                       }
-
-                       if (!invert)
-                               bool_expr.Emit (ec);
 
-                       if (target_is_for_true){
-                               if (invert)
-                                       ig.Emit (OpCodes.Brfalse, target);
-                               else
-                                       ig.Emit (OpCodes.Brtrue, target);
-                       } else {
-                               if (invert)
-                                       ig.Emit (OpCodes.Brtrue, target);
-                               else
-                                       ig.Emit (OpCodes.Brfalse, target);
-                       }
+               public void Error (int error, string s)
+               {
+                       if (!Location.IsNull (loc))
+                               Report.Error (error, loc, s);
+                       else
+                               Report.Error (error, s);
                }
 
-               public static void Warning_DeadCodeFound (Location loc)
+               /// <summary>
+               ///   Return value indicates whether all code paths emitted return.
+               /// </summary>
+               public virtual void Emit (EmitContext ec)
                {
-                       Report.Warning (162, loc, "Unreachable code detected");
-               }
+                       ec.Mark (loc, true);
+                       DoEmit (ec);
+               }               
        }
 
-       public class EmptyStatement : Statement {
+       public sealed class EmptyStatement : Statement {
+               
+               private EmptyStatement () {}
+               
+               public static readonly EmptyStatement Value = new EmptyStatement ();
+               
                public override bool Resolve (EmitContext ec)
                {
                        return true;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
-                       return false;
                }
        }
        
@@ -111,6 +108,8 @@ namespace Mono.CSharp {
                Expression expr;
                public Statement TrueStatement;
                public Statement FalseStatement;
+
+               bool is_true_ret;
                
                public If (Expression expr, Statement trueStatement, Location l)
                {
@@ -138,57 +137,76 @@ namespace Mono.CSharp {
                        if (expr == null){
                                return false;
                        }
+
+                       //
+                       // Dead code elimination
+                       //
+                       if (expr is BoolConstant){
+                               bool take = ((BoolConstant) expr).Value;
+
+                               if (take){
+                                       if (!TrueStatement.Resolve (ec))
+                                               return false;
+
+                                       if ((FalseStatement != null) &&
+                                           !FalseStatement.ResolveUnreachable (ec, true))
+                                               return false;
+                                       FalseStatement = null;
+                               } else {
+                                       if (!TrueStatement.ResolveUnreachable (ec, true))
+                                               return false;
+                                       TrueStatement = null;
+
+                                       if ((FalseStatement != null) &&
+                                           !FalseStatement.Resolve (ec))
+                                               return false;
+                               }
+
+                               return true;
+                       }
                        
-                       ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
                        
-                       if (!TrueStatement.Resolve (ec)) {
-                               ec.KillFlowBranching ();
-                               return false;
-                       }
+                       bool ok = TrueStatement.Resolve (ec);
 
-                       ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
+                       is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
 
-                       if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
-                               ec.KillFlowBranching ();
-                               return false;
-                       }
+                       ec.CurrentBranching.CreateSibling ();
+
+                       if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
+                               ok = false;
                                        
                        ec.EndFlowBranching ();
 
                        Report.Debug (1, "END IF BLOCK", loc);
 
-                       return true;
+                       return ok;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
                        Label false_target = ig.DefineLabel ();
                        Label end;
-                       bool is_true_ret, is_false_ret;
 
                        //
-                       // Dead code elimination
+                       // If we're a boolean expression, Resolve() already
+                       // eliminated dead code for us.
                        //
                        if (expr is BoolConstant){
                                bool take = ((BoolConstant) expr).Value;
 
-                               if (take){
-                                       if (FalseStatement != null){
-                                               Warning_DeadCodeFound (FalseStatement.loc);
-                                       }
-                                       return TrueStatement.Emit (ec);
-                               } else {
-                                       Warning_DeadCodeFound (TrueStatement.loc);
-                                       if (FalseStatement != null)
-                                               return FalseStatement.Emit (ec);
-                               }
+                               if (take)
+                                       TrueStatement.Emit (ec);
+                               else if (FalseStatement != null)
+                                       FalseStatement.Emit (ec);
+
+                               return;
                        }
                        
-                       EmitBoolExpression (ec, expr, false_target, false);
-
-                       is_true_ret = TrueStatement.Emit (ec);
-                       is_false_ret = is_true_ret;
+                       expr.EmitBranchable (ec, false_target, false);
+                       
+                       TrueStatement.Emit (ec);
 
                        if (FalseStatement != null){
                                bool branch_emitted = false;
@@ -200,23 +218,20 @@ namespace Mono.CSharp {
                                }
 
                                ig.MarkLabel (false_target);
-                               is_false_ret = FalseStatement.Emit (ec);
+                               FalseStatement.Emit (ec);
 
                                if (branch_emitted)
                                        ig.MarkLabel (end);
                        } else {
                                ig.MarkLabel (false_target);
-                               is_false_ret = false;
                        }
-
-                       return is_true_ret && is_false_ret;
                }
        }
 
        public class Do : Statement {
                public Expression expr;
                public readonly Statement  EmbeddedStatement;
-               bool infinite, may_return;
+               bool infinite;
                
                public Do (Statement statement, Expression boolExpr, Location l)
                {
@@ -229,7 +244,7 @@ namespace Mono.CSharp {
                {
                        bool ok = true;
 
-                       ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
 
                        if (!EmbeddedStatement.Resolve (ec))
                                ok = false;
@@ -245,25 +260,20 @@ namespace Mono.CSharp {
                        }
 
                        ec.CurrentBranching.Infinite = infinite;
-                       FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
-                       may_return = returns != FlowBranching.FlowReturns.Never;
+                       ec.EndFlowBranching ();
 
                        return ok;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
                        Label loop = ig.DefineLabel ();
                        Label old_begin = ec.LoopBegin;
                        Label old_end = ec.LoopEnd;
-                       bool  old_inloop = ec.InLoop;
-                       int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
                        
                        ec.LoopBegin = ig.DefineLabel ();
                        ec.LoopEnd = ig.DefineLabel ();
-                       ec.InLoop = true;
-                       ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
                                
                        ig.MarkLabel (loop);
                        EmbeddedStatement.Emit (ec);
@@ -278,26 +288,19 @@ namespace Mono.CSharp {
                                if (res)
                                        ec.ig.Emit (OpCodes.Br, loop); 
                        } else
-                               EmitBoolExpression (ec, expr, loop, true);
+                               expr.EmitBranchable (ec, loop, true);
                        
                        ig.MarkLabel (ec.LoopEnd);
 
-                       ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
                        ec.LoopBegin = old_begin;
                        ec.LoopEnd = old_end;
-                       ec.InLoop = old_inloop;
-
-                       if (infinite)
-                               return may_return == false;
-                       else
-                               return false;
                }
        }
 
        public class While : Statement {
                public Expression expr;
                public readonly Statement Statement;
-               bool may_return, empty, infinite;
+               bool infinite, empty;
                
                public While (Expression boolExpr, Statement statement, Location l)
                {
@@ -314,8 +317,6 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return false;
 
-                       ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
-
                        //
                        // Inform whether we are infinite or not
                        //
@@ -323,54 +324,41 @@ namespace Mono.CSharp {
                                BoolConstant bc = (BoolConstant) expr;
 
                                if (bc.Value == false){
-                                       Warning_DeadCodeFound (Statement.loc);
+                                       if (!Statement.ResolveUnreachable (ec, true))
+                                               return false;
                                        empty = true;
+                                       return true;
                                } else
                                        infinite = true;
-                       } else {
-                               //
-                               // We are not infinite, so the loop may or may not be executed.
-                               //
-                               ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
                        }
 
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
+
                        if (!Statement.Resolve (ec))
                                ok = false;
 
-                       if (empty)
-                               ec.KillFlowBranching ();
-                       else {
-                               ec.CurrentBranching.Infinite = infinite;
-                               FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
-                               may_return = returns != FlowBranching.FlowReturns.Never;
-                       }
+                       ec.CurrentBranching.Infinite = infinite;
+                       ec.EndFlowBranching ();
 
                        return ok;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        if (empty)
-                               return false;
+                               return;
 
                        ILGenerator ig = ec.ig;
                        Label old_begin = ec.LoopBegin;
                        Label old_end = ec.LoopEnd;
-                       bool old_inloop = ec.InLoop;
-                       int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
-                       bool ret;
                        
                        ec.LoopBegin = ig.DefineLabel ();
                        ec.LoopEnd = ig.DefineLabel ();
-                       ec.InLoop = true;
-                       ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
 
                        //
                        // Inform whether we are infinite or not
                        //
                        if (expr is BoolConstant){
-                               BoolConstant bc = (BoolConstant) expr;
-
                                ig.MarkLabel (ec.LoopBegin);
                                Statement.Emit (ec);
                                ig.Emit (OpCodes.Br, ec.LoopBegin);
@@ -379,7 +367,6 @@ namespace Mono.CSharp {
                                // Inform that we are infinite (ie, `we return'), only
                                // if we do not `break' inside the code.
                                //
-                               ret = may_return == false;
                                ig.MarkLabel (ec.LoopEnd);
                        } else {
                                Label while_loop = ig.DefineLabel ();
@@ -391,18 +378,13 @@ namespace Mono.CSharp {
                        
                                ig.MarkLabel (ec.LoopBegin);
 
-                               EmitBoolExpression (ec, expr, while_loop, true);
+                               expr.EmitBranchable (ec, while_loop, true);
+                               
                                ig.MarkLabel (ec.LoopEnd);
-
-                               ret = false;
                        }       
 
                        ec.LoopBegin = old_begin;
                        ec.LoopEnd = old_end;
-                       ec.InLoop = old_inloop;
-                       ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
-
-                       return ret;
                }
        }
 
@@ -411,7 +393,7 @@ namespace Mono.CSharp {
                readonly Statement InitStatement;
                readonly Statement Increment;
                readonly Statement Statement;
-               bool may_return, infinite, empty;
+               bool infinite, empty;
                
                public For (Statement initStatement,
                            Expression test,
@@ -443,17 +425,22 @@ namespace Mono.CSharp {
                                        BoolConstant bc = (BoolConstant) Test;
 
                                        if (bc.Value == false){
-                                               Warning_DeadCodeFound (Statement.loc);
+                                               if (!Statement.ResolveUnreachable (ec, true))
+                                                       return false;
+                                               if ((Increment != null) &&
+                                                   !Increment.ResolveUnreachable (ec, false))
+                                                       return false;
                                                empty = true;
+                                               return true;
                                        } else
                                                infinite = true;
                                }
                        } else
                                infinite = true;
 
-                       ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
                        if (!infinite)
-                               ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
+                               ec.CurrentBranching.CreateSibling ();
 
                        if (!Statement.Resolve (ec))
                                ok = false;
@@ -463,45 +450,35 @@ namespace Mono.CSharp {
                                        ok = false;
                        }
 
-                       if (empty)
-                               ec.KillFlowBranching ();
-                       else {
-                               ec.CurrentBranching.Infinite = infinite;
-                               FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
-                               may_return = returns != FlowBranching.FlowReturns.Never;
-                       }
+                       ec.CurrentBranching.Infinite = infinite;
+                       ec.EndFlowBranching ();
 
                        return ok;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        if (empty)
-                               return false;
+                               return;
 
                        ILGenerator ig = ec.ig;
                        Label old_begin = ec.LoopBegin;
                        Label old_end = ec.LoopEnd;
-                       bool old_inloop = ec.InLoop;
-                       int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
                        Label loop = ig.DefineLabel ();
                        Label test = ig.DefineLabel ();
                        
-                       if (InitStatement != null)
-                               if (! (InitStatement is EmptyStatement))
-                                       InitStatement.Emit (ec);
+                       if (InitStatement != null && InitStatement != EmptyStatement.Value)
+                               InitStatement.Emit (ec);
 
                        ec.LoopBegin = ig.DefineLabel ();
                        ec.LoopEnd = ig.DefineLabel ();
-                       ec.InLoop = true;
-                       ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
 
                        ig.Emit (OpCodes.Br, test);
                        ig.MarkLabel (loop);
                        Statement.Emit (ec);
 
                        ig.MarkLabel (ec.LoopBegin);
-                       if (!(Increment is EmptyStatement))
+                       if (Increment != EmptyStatement.Value)
                                Increment.Emit (ec);
 
                        ig.MarkLabel (test);
@@ -511,35 +488,21 @@ namespace Mono.CSharp {
                        //
                        if (Test != null){
                                //
-                               // The Resolve code already catches the case for Test == BoolConstant (false)
-                               // so we know that this is true
+                               // The Resolve code already catches the case for
+                               // Test == BoolConstant (false) so we know that
+                               // this is true
                                //
                                if (Test is BoolConstant)
                                        ig.Emit (OpCodes.Br, loop);
                                else
-                                       EmitBoolExpression (ec, Test, loop, true);
+                                       Test.EmitBranchable (ec, loop, true);
+                               
                        } else
                                ig.Emit (OpCodes.Br, loop);
                        ig.MarkLabel (ec.LoopEnd);
 
                        ec.LoopBegin = old_begin;
                        ec.LoopEnd = old_end;
-                       ec.InLoop = old_inloop;
-                       ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
-                       
-                       //
-                       // Inform whether we are infinite or not
-                       //
-                       if (Test != null){
-                               if (Test is BoolConstant){
-                                       BoolConstant bc = (BoolConstant) Test;
-
-                                       if (bc.Value)
-                                               return may_return == false;
-                               }
-                               return false;
-                       } else
-                               return may_return == false;
                }
        }
        
@@ -558,13 +521,9 @@ namespace Mono.CSharp {
                        return expr != null;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       
                        expr.EmitStatement (ec);
-
-                       return false;
                }
 
                public override string ToString ()
@@ -585,76 +544,70 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               bool in_exc;
+
                public override bool Resolve (EmitContext ec)
                {
-                       if (Expr != null){
+                       if (ec.ReturnType == null){
+                               if (Expr != null){
+                                       Error (127, "Return with a value not allowed here");
+                                       return false;
+                               }
+                       } else {
+                               if (Expr == null){
+                                       Error (126, "An object of type `{0}' is expected " +
+                                              "for the return statement",
+                                              TypeManager.CSharpName (ec.ReturnType));
+                                       return false;
+                               }
+
                                Expr = Expr.Resolve (ec);
                                if (Expr == null)
                                        return false;
+
+                               if (Expr.Type != ec.ReturnType) {
+                                       Expr = Convert.ImplicitConversionRequired (
+                                               ec, Expr, ec.ReturnType, loc);
+                                       if (Expr == null)
+                                               return false;
+                               }
                        }
 
                        if (ec.InIterator){
-                               Report.Error (-206, loc, "Return statement not allowed inside iterators");
+                               Error (-206, "Return statement not allowed inside iterators");
                                return false;
                        }
                                
                        FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
 
-                       if (ec.CurrentBranching.InTryBlock ())
+                       if (ec.CurrentBranching.InTryOrCatch (true)) {
                                ec.CurrentBranching.AddFinallyVector (vector);
-                       else
+                               in_exc = true;
+                       } else if (ec.CurrentBranching.InFinally (true)) {
+                               Error (157, "Control can not leave the body of the finally block");
+                               return false;
+                       } else
                                vector.CheckOutParameters (ec.CurrentBranching);
 
-                       vector.Returns = FlowBranching.FlowReturns.Always;
-                       vector.Breaks = FlowBranching.FlowReturns.Always;
+                       ec.CurrentBranching.CurrentUsageVector.Return ();
                        return true;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
-                       if (ec.InFinally){
-                               Report.Error (157, loc, "Control can not leave the body of the finally block");
-                               return false;
-                       }
-                       
-                       if (ec.ReturnType == null){
-                               if (Expr != null){
-                                       Report.Error (127, loc, "Return with a value not allowed here");
-                                       return true;
-                               }
-                       } else {
-                               if (Expr == null){
-                                       Report.Error (126, loc, "An object of type `" +
-                                                     TypeManager.CSharpName (ec.ReturnType) + "' is " +
-                                                     "expected for the return statement");
-                                       return true;
-                               }
-
-                               if (Expr.Type != ec.ReturnType)
-                                       Expr = Convert.ImplicitConversionRequired (
-                                               ec, Expr, ec.ReturnType, loc);
-
-                               if (Expr == null)
-                                       return true;
-
+                       if (Expr != null) {
                                Expr.Emit (ec);
 
-                               if (ec.InTry || ec.InCatch)
+                               if (in_exc)
                                        ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
                        }
 
-                       if (ec.InTry || ec.InCatch) {
-                               if (!ec.HasReturnLabel) {
-                                       ec.ReturnLabel = ec.ig.DefineLabel ();
-                                       ec.HasReturnLabel = true;
-                               }
+                       if (in_exc) {
+                               ec.NeedReturnLabel ();
                                ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
                        } else {
                                ec.ig.Emit (OpCodes.Ret);
-                               ec.NeedExplicitReturn = false;
                        }
-
-                       return true; 
                }
        }
 
@@ -665,20 +618,15 @@ namespace Mono.CSharp {
                
                public override bool Resolve (EmitContext ec)
                {
-                       label = block.LookupLabel (target);
-                       if (label == null){
-                               Report.Error (
-                                       159, loc,
-                                       "No such label `" + target + "' in this scope");
+                       label = ec.CurrentBranching.LookupLabel (target, loc);
+                       if (label == null)
                                return false;
-                       }
 
                        // If this is a forward goto.
                        if (!label.IsDefined)
                                label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
 
-                       ec.CurrentBranching.CurrentUsageVector.Breaks = FlowBranching.FlowReturns.Always;
-                       ec.CurrentBranching.CurrentUsageVector.Returns = FlowBranching.FlowReturns.Always;
+                       ec.CurrentBranching.CurrentUsageVector.Goto ();
 
                        return true;
                }
@@ -696,27 +644,23 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        Label l = label.LabelTarget (ec);
                        ec.ig.Emit (OpCodes.Br, l);
-                       
-                       return false;
                }
        }
 
        public class LabeledStatement : Statement {
                public readonly Location Location;
-               string label_name;
                bool defined;
                bool referenced;
                Label label;
 
-               ArrayList vectors;
+               FlowBranching.UsageVector vectors;
                
                public LabeledStatement (string label_name, Location l)
                {
-                       this.label_name = label_name;
                        this.Location = l;
                }
 
@@ -744,32 +688,24 @@ namespace Mono.CSharp {
 
                public void AddUsageVector (FlowBranching.UsageVector vector)
                {
-                       if (vectors == null)
-                               vectors = new ArrayList ();
-
-                       vectors.Add (vector.Clone ());
+                       vector = vector.Clone ();
+                       vector.Next = vectors;
+                       vectors = vector;
                }
 
                public override bool Resolve (EmitContext ec)
                {
-                       if (vectors != null)
-                               ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
-                       else {
-                               ec.CurrentBranching.CurrentUsageVector.Breaks = FlowBranching.FlowReturns.Never;
-                               ec.CurrentBranching.CurrentUsageVector.Returns = FlowBranching.FlowReturns.Never;
-                       }
+                       ec.CurrentBranching.Label (vectors);
 
                        referenced = true;
 
                        return true;
                }
 
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        LabelTarget (ec);
                        ec.ig.MarkLabel (label);
-
-                       return false;
                }
        }
        
@@ -786,24 +722,22 @@ namespace Mono.CSharp {
 
                public override bool Resolve (EmitContext ec)
                {
-                       ec.CurrentBranching.CurrentUsageVector.Breaks = FlowBranching.FlowReturns.Always;
-                       ec.CurrentBranching.CurrentUsageVector.Returns = FlowBranching.FlowReturns.Always;
+                       ec.CurrentBranching.CurrentUsageVector.Goto ();
                        return true;
                }
 
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        if (ec.Switch == null){
                                Report.Error (153, loc, "goto default is only valid in a switch statement");
-                               return false;
+                               return;
                        }
 
                        if (!ec.Switch.GotDefault){
                                Report.Error (159, loc, "No default target on switch statement");
-                               return false;
+                               return;
                        }
                        ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
-                       return false;
                }
        }
 
@@ -853,15 +787,13 @@ namespace Mono.CSharp {
 
                        label = sl.ILLabelCode;
 
-                       ec.CurrentBranching.CurrentUsageVector.Breaks = FlowBranching.FlowReturns.Unreachable;
-                       ec.CurrentBranching.CurrentUsageVector.Returns = FlowBranching.FlowReturns.Always;
+                       ec.CurrentBranching.CurrentUsageVector.Goto ();
                        return true;
                }
 
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        ec.ig.Emit (OpCodes.Br, label);
-                       return true;
                }
        }
        
@@ -876,6 +808,9 @@ namespace Mono.CSharp {
 
                public override bool Resolve (EmitContext ec)
                {
+                       bool in_catch = ec.CurrentBranching.InCatch ();
+                       ec.CurrentBranching.CurrentUsageVector.Throw ();
+
                        if (expr != null){
                                expr = expr.Resolve (ec);
                                if (expr == null)
@@ -894,37 +829,30 @@ namespace Mono.CSharp {
                                if ((t != TypeManager.exception_type) &&
                                    !t.IsSubclassOf (TypeManager.exception_type) &&
                                    !(expr is NullLiteral)) {
-                                       Report.Error (155, loc,
-                                                     "The type caught or thrown must be derived " +
-                                                     "from System.Exception");
+                                       Error (155,
+                                              "The type caught or thrown must be derived " +
+                                              "from System.Exception");
                                        return false;
                                }
+                       } else if (!in_catch) {
+                               Error (156,
+                                      "A throw statement with no argument is only " +
+                                      "allowed in a catch clause");
+                               return false;
                        }
 
-                       ec.CurrentBranching.CurrentUsageVector.Returns = FlowBranching.FlowReturns.Exception;
-                       ec.CurrentBranching.CurrentUsageVector.Breaks = FlowBranching.FlowReturns.Exception;
                        return true;
                }
                        
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
-                       if (expr == null){
-                               if (ec.InCatch)
-                                       ec.ig.Emit (OpCodes.Rethrow);
-                               else {
-                                       Report.Error (
-                                               156, loc,
-                                               "A throw statement with no argument is only " +
-                                               "allowed in a catch clause");
-                               }
-                               return false;
-                       }
-
-                       expr.Emit (ec);
-
-                       ec.ig.Emit (OpCodes.Throw);
+                       if (expr == null)
+                               ec.ig.Emit (OpCodes.Rethrow);
+                       else {
+                               expr.Emit (ec);
 
-                       return true;
+                               ec.ig.Emit (OpCodes.Throw);
+                       }
                }
        }
 
@@ -935,28 +863,39 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               bool crossing_exc;
+
                public override bool Resolve (EmitContext ec)
                {
-                       ec.CurrentBranching.MayLeaveLoop = true;
-                       ec.CurrentBranching.CurrentUsageVector.Breaks = FlowBranching.FlowReturns.Always;
+                       if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
+                               Error (139, "No enclosing loop or switch to continue to");
+                               return false;
+                       } else if (ec.CurrentBranching.InFinally (false)) {
+                               Error (157, "Control can not leave the body of the finally block");
+                               return false;
+                       } else if (ec.CurrentBranching.InTryOrCatch (false))
+                               ec.CurrentBranching.AddFinallyVector (
+                                       ec.CurrentBranching.CurrentUsageVector);
+                       else if (ec.CurrentBranching.InLoop ())
+                               ec.CurrentBranching.AddBreakVector (
+                                       ec.CurrentBranching.CurrentUsageVector);
+
+                       crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
+
+                       ec.CurrentBranching.CurrentUsageVector.Break ();
                        return true;
                }
 
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
 
-                       if (ec.InLoop == false && ec.Switch == null){
-                               Report.Error (139, loc, "No enclosing loop or switch to continue to");
-                               return false;
-                       }
-
-                       if (ec.InTry || ec.InCatch)
+                       if (crossing_exc)
                                ig.Emit (OpCodes.Leave, ec.LoopEnd);
-                       else
+                       else {
+                               ec.NeedReturnLabel ();
                                ig.Emit (OpCodes.Br, ec.LoopEnd);
-
-                       return false;
+                       }
                }
        }
 
@@ -967,39 +906,33 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               bool crossing_exc;
+
                public override bool Resolve (EmitContext ec)
                {
-                       ec.CurrentBranching.CurrentUsageVector.Breaks = FlowBranching.FlowReturns.Always;
+                       if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
+                               Error (139, "No enclosing loop to continue to");
+                               return false;
+                       } else if (ec.CurrentBranching.InFinally (false)) {
+                               Error (157, "Control can not leave the body of the finally block");
+                               return false;
+                       } else if (ec.CurrentBranching.InTryOrCatch (false))
+                               ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
+
+                       crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
+
+                       ec.CurrentBranching.CurrentUsageVector.Goto ();
                        return true;
                }
 
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        Label begin = ec.LoopBegin;
                        
-                       if (!ec.InLoop){
-                               Report.Error (139, loc, "No enclosing loop to continue to");
-                               return false;
-                       } 
-
-                       //
-                       // UGH: Non trivial.  This Br might cross a try/catch boundary
-                       // How can we tell?
-                       //
-                       // while () {
-                       //   try { ... } catch { continue; }
-                       // }
-                       //
-                       // From:
-                       // try {} catch { while () { continue; }}
-                       //
-                       if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
+                       if (crossing_exc)
                                ec.ig.Emit (OpCodes.Leave, begin);
-                       else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
-                               throw new Exception ("Should never happen");
                        else
                                ec.ig.Emit (OpCodes.Br, begin);
-                       return false;
                }
        }
 
@@ -1023,17 +956,19 @@ namespace Mono.CSharp {
 
                public VariableInfo VariableInfo;
 
-               public bool Used;
-               public bool Assigned;
-               public bool ReadOnly;
-               bool is_fixed;
+               enum Flags : byte {
+                       Used = 1,
+                       ReadOnly = 2,
+                       Fixed = 4
+               }
+
+               Flags flags;
                
                public LocalInfo (Expression type, string name, Block block, Location l)
                {
                        Type = type;
                        Name = name;
                        Block = block;
-                       LocalBuilder = null;
                        Location = l;
                }
 
@@ -1041,20 +976,26 @@ namespace Mono.CSharp {
                {
                        VariableType = tc.TypeBuilder;
                        Block = block;
-                       LocalBuilder = null;
                        Location = l;
                }
 
                public bool IsThisAssigned (EmitContext ec, Location loc)
                {
-                       VariableInfo vi = Block.GetVariableInfo (this);
-                       if (vi == null)
+                       if (VariableInfo == null)
                                throw new Exception ();
 
-                       if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (vi))
+                       if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
                                return true;
 
-                       return vi.TypeInfo.IsFullyInitialized (ec.CurrentBranching, vi, loc);
+                       return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
+               }
+
+               public bool IsAssigned (EmitContext ec)
+               {
+                       if (VariableInfo == null)
+                               throw new Exception ();
+
+                       return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
                }
 
                public bool Resolve (DeclSpace decl)
@@ -1062,6 +1003,12 @@ namespace Mono.CSharp {
                        if (VariableType == null)
                                VariableType = decl.ResolveType (Type, false, Location);
 
+                       if (VariableType == TypeManager.void_type) {
+                               Report.Error (1547, Location,
+                                             "Keyword 'void' cannot be used in this context");
+                               return false;
+                       }
+
                        if (VariableType == null)
                                return false;
 
@@ -1071,12 +1018,12 @@ namespace Mono.CSharp {
                public void MakePinned ()
                {
                        TypeManager.MakePinned (LocalBuilder);
-                       is_fixed = true;
+                       flags |= Flags.Fixed;
                }
 
                public bool IsFixed {
                        get {
-                               if (is_fixed || TypeManager.IsValueType (VariableType))
+                               if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
                                        return true;
 
                                return false;
@@ -1088,6 +1035,27 @@ namespace Mono.CSharp {
                        return String.Format ("LocalInfo ({0},{1},{2},{3})",
                                              Name, Type, VariableInfo, Location);
                }
+
+               public bool Used {
+                       get {
+                               return (flags & Flags.Used) != 0;
+                       }
+                       set {
+                               flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
+                       }
+               }
+
+               public bool ReadOnly {
+                       get {
+                               return (flags & Flags.ReadOnly) != 0;
+                       }
+                       set {
+                               flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
+                       }
+               }
+
+               
+               
        }
                
        /// <summary>
@@ -1100,6 +1068,9 @@ namespace Mono.CSharp {
        ///
        ///   Implicit blocks are used as labels or to introduce variable
        ///   declarations.
+       ///
+       ///   Top-level blocks derive from Block, and they are called ToplevelBlock
+       ///   they contain extra information that is not necessary on normal blocks.
        /// </remarks>
        public class Block : Statement {
                public readonly Block     Parent;
@@ -1112,7 +1083,8 @@ namespace Mono.CSharp {
                        Unchecked = 2,
                        BlockUsed = 4,
                        VariablesInitialized = 8,
-                       HasRet = 16
+                       HasRet = 16,
+                       IsDestructor = 32       
                }
                Flags flags;
 
@@ -1135,6 +1107,7 @@ namespace Mono.CSharp {
                // The statements in this block
                //
                ArrayList statements;
+               int num_statements;
 
                //
                // An array of Blocks.  We keep track of children just
@@ -1206,6 +1179,14 @@ namespace Mono.CSharp {
                        this.loc = start;
                        this_id = id++;
                        statements = new ArrayList ();
+
+                       if (parent != null && Implicit) {
+                               if (parent.child_variable_names == null)
+                                       parent.child_variable_names = new Hashtable();
+                               // share with parent
+                               child_variable_names = parent.child_variable_names;
+                       }
+                               
                }
 
                public Block CreateSwitchBlock (Location start)
@@ -1243,32 +1224,92 @@ namespace Mono.CSharp {
                ///   otherwise.
                /// </returns>
                ///
-               public bool AddLabel (string name, LabeledStatement target)
+               public bool AddLabel (string name, LabeledStatement target, Location loc)
                {
                        if (switch_block != null)
-                               return switch_block.AddLabel (name, target);
+                               return switch_block.AddLabel (name, target, loc);
+
+                       Block cur = this;
+                       while (cur != null) {
+                               if (cur.DoLookupLabel (name) != null) {
+                                       Report.Error (
+                                               140, loc, "The label '{0}' is a duplicate",
+                                               name);
+                                       return false;
+                               }
+
+                               if (!Implicit)
+                                       break;
+
+                               cur = cur.Parent;
+                       }
+
+                       while (cur != null) {
+                               if (cur.DoLookupLabel (name) != null) {
+                                       Report.Error (
+                                               158, loc,
+                                               "The label '{0}' shadows another label " +
+                                               "by the same name in a containing scope.",
+                                               name);
+                                       return false;
+                               }
+
+                               if (children != null) {
+                                       foreach (Block b in children) {
+                                               LabeledStatement s = b.DoLookupLabel (name);
+                                               if (s == null)
+                                                       continue;
+
+                                               Report.Error (
+                                                       158, s.Location,
+                                                       "The label '{0}' shadows another " +
+                                                       "label by the same name in a " +
+                                                       "containing scope.",
+                                                       name);
+                                               return false;
+                                       }
+                               }
+
+
+                               cur = cur.Parent;
+                       }
 
                        if (labels == null)
                                labels = new Hashtable ();
-                       if (labels.Contains (name))
-                               return false;
-                       
+
                        labels.Add (name, target);
                        return true;
                }
 
                public LabeledStatement LookupLabel (string name)
+               {
+                       LabeledStatement s = DoLookupLabel (name);
+                       if (s != null)
+                               return s;
+
+                       if (children == null)
+                               return null;
+
+                       foreach (Block child in children) {
+                               if (!child.Implicit)
+                                       continue;
+
+                               s = child.LookupLabel (name);
+                               if (s != null)
+                                       return s;
+                       }
+
+                       return null;
+               }
+
+               LabeledStatement DoLookupLabel (string name)
                {
                        if (switch_block != null)
                                return switch_block.LookupLabel (name);
 
-                       if (labels != null){
+                       if (labels != null)
                                if (labels.Contains (name))
                                        return ((LabeledStatement) labels [name]);
-                       }
-
-                       if (Parent != null)
-                               return Parent.LookupLabel (name);
 
                        return null;
                }
@@ -1306,28 +1347,6 @@ namespace Mono.CSharp {
                                child_variable_names.Add (name, true);
                }
 
-               // <summary>
-               //   Marks all variables from block @block and all its children as being
-               //   used in a child block.
-               // </summary>
-               public void AddChildVariableNames (Block block)
-               {
-                       if (block.Variables != null) {
-                               foreach (string name in block.Variables.Keys)
-                                       AddChildVariableName (name);
-                       }
-
-                       if (block.children != null) {
-                               foreach (Block child in block.children)
-                                       AddChildVariableNames (child);
-                       }
-
-                       if (block.child_variable_names != null) {
-                               foreach (string name in block.child_variable_names.Keys)
-                                       AddChildVariableName (name);
-                       }
-               }
-
                // <summary>
                //   Checks whether a variable name has already been used in a child block.
                // </summary>
@@ -1355,6 +1374,7 @@ namespace Mono.CSharp {
                                variables = new Hashtable ();
 
                        this_variable = new LocalInfo (tc, this, l);
+                       this_variable.Used = true;
 
                        variables.Add ("this", this_variable);
 
@@ -1390,7 +1410,7 @@ namespace Mono.CSharp {
                        }
 
                        if (pars != null) {
-                               int idx = 0;
+                               int idx;
                                Parameter p = pars.GetParameterByName (name, out idx);
                                if (p != null) {
                                        Report.Error (136, l, "A local variable named `" + name + "' " +
@@ -1401,11 +1421,19 @@ namespace Mono.CSharp {
                                        return null;
                                }
                        }
-                       
+
                        vi = new LocalInfo (type, name, this, l);
 
                        variables.Add (name, vi);
 
+                       // Mark 'name' as "used by a child block" in every surrounding block
+                       Block cur = this;
+                       while (cur != null && cur.Implicit) 
+                               cur = cur.Parent;
+                       if (cur != null)
+                               for (Block par = cur.Parent; par != null; par = par.Parent)
+                                       par.AddChildVariableName (name);
+
                        if ((flags & Flags.VariablesInitialized) != 0)
                                throw new Exception ();
 
@@ -1433,26 +1461,16 @@ namespace Mono.CSharp {
 
                public LocalInfo GetLocalInfo (string name)
                {
-                       if (variables != null) {
-                               object temp;
-                               temp = variables [name];
-
-                               if (temp != null){
-                                       return (LocalInfo) temp;
+                       for (Block b = this; b != null; b = b.Parent) {
+                               if (b.variables != null) {
+                                       LocalInfo ret = b.variables [name] as LocalInfo;
+                                       if (ret != null)
+                                               return ret;
                                }
                        }
-
-                       if (Parent != null)
-                               return Parent.GetLocalInfo (name);
-
                        return null;
                }
 
-               public VariableInfo GetVariableInfo (LocalInfo li)
-               {
-                       return li.VariableInfo;
-               }
-
                public Expression GetVariableType (string name)
                {
                        LocalInfo vi = GetLocalInfo (name);
@@ -1465,17 +1483,13 @@ namespace Mono.CSharp {
 
                public Expression GetConstantExpression (string name)
                {
-                       if (constants != null) {
-                               object temp;
-                               temp = constants [name];
-                               
-                               if (temp != null)
-                                       return (Expression) temp;
+                       for (Block b = this; b != null; b = b.Parent) {
+                               if (b.constants != null) {
+                                       Expression ret = b.constants [name] as Expression;
+                                       if (ret != null)
+                                               return ret;
+                               }
                        }
-                       
-                       if (Parent != null)
-                               return Parent.GetConstantExpression (name);
-
                        return null;
                }
                
@@ -1491,22 +1505,13 @@ namespace Mono.CSharp {
                        return e != null;
                }
                
-               /// <summary>
-               ///   Use to fetch the statement associated with this label
-               /// </summary>
-               public Statement this [string name] {
-                       get {
-                               return (Statement) labels [name];
-                       }
-               }
-
                Parameters parameters = null;
                public Parameters Parameters {
                        get {
-                               if (Parent != null)
-                                       return Parent.Parameters;
-
-                               return parameters;
+                               Block b = this;
+                               while (b.Parent != null)
+                                       b = b.Parent;
+                               return b.parameters;
                        }
                }
 
@@ -1536,6 +1541,23 @@ namespace Mono.CSharp {
                        flags |= Flags.BlockUsed;
                }
 
+               public bool HasRet {
+                       get {
+                               return (flags & Flags.HasRet) != 0;
+                       }
+               }
+
+               public bool IsDestructor {
+                       get {
+                               return (flags & Flags.IsDestructor) != 0;
+                       }
+               }
+
+               public void SetDestructor ()
+               {
+                       flags |= Flags.IsDestructor;
+               }
+
                VariableMap param_map, local_map;
 
                public VariableMap ParameterMap {
@@ -1556,6 +1578,11 @@ namespace Mono.CSharp {
                        }
                }
 
+               public bool LiftVariable (LocalInfo local_info)
+               {
+                       return false;
+               }
+               
                /// <summary>
                ///   Emits the variable declarations and labels.
                /// </summary>
@@ -1565,7 +1592,6 @@ namespace Mono.CSharp {
                /// </remarks>
                public void EmitMeta (EmitContext ec, InternalParameters ip)
                {
-                       DeclSpace ds = ec.DeclSpace;
                        ILGenerator ig = ec.ig;
 
                        //
@@ -1638,13 +1664,20 @@ namespace Mono.CSharp {
                                        if (e == null)
                                                continue;
 
-                                       if (!(e is Constant)){
+                                       Constant ce = e as Constant;
+                                       if (ce == null){
                                                Report.Error (133, vi.Location,
                                                              "The expression being assigned to `" +
                                                              name + "' must be constant (" + e + ")");
                                                continue;
                                        }
 
+                                       if (e.Type != variable_type){
+                                               e = Const.ChangeType (vi.Location, ce, variable_type);
+                                               if (e == null)
+                                                       continue;
+                                       }
+
                                        constants.Remove (name);
                                        constants.Add (name, e);
                                }
@@ -1660,10 +1693,10 @@ namespace Mono.CSharp {
                        }
                }
 
-               public void UsageWarning ()
+               void UsageWarning (FlowBranching.UsageVector vector)
                {
                        string name;
-                       
+
                        if (variables != null){
                                foreach (DictionaryEntry de in variables){
                                        LocalInfo vi = (LocalInfo) de.Value;
@@ -1672,8 +1705,8 @@ namespace Mono.CSharp {
                                                continue;
                                        
                                        name = (string) de.Key;
-                                               
-                                       if (vi.Assigned){
+
+                                       if (vector.IsAssigned (vi.VariableInfo)){
                                                Report.Warning (
                                                        219, vi.Location, "The variable `" + name +
                                                        "' is assigned but its value is never used");
@@ -1685,10 +1718,6 @@ namespace Mono.CSharp {
                                        } 
                                }
                        }
-
-                       if (children != null)
-                               foreach (Block b in children)
-                                       b.UsageWarning ();
                }
 
                public override bool Resolve (EmitContext ec)
@@ -1696,47 +1725,61 @@ namespace Mono.CSharp {
                        Block prev_block = ec.CurrentBlock;
                        bool ok = true;
 
+                       int errors = Report.Errors;
+
                        ec.CurrentBlock = this;
                        ec.StartFlowBranching (this);
 
-                       Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
+                       Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
 
-                       ArrayList new_statements = new ArrayList ();
                        bool unreachable = false, warning_shown = false;
 
-                       foreach (Statement s in statements){
+                       int statement_count = statements.Count;
+                       for (int ix = 0; ix < statement_count; ix++){
+                               Statement s = (Statement) statements [ix];
+
                                if (unreachable && !(s is LabeledStatement)) {
-                                       if (!warning_shown && !(s is EmptyStatement)) {
+                                       if (s == EmptyStatement.Value)
+                                               s.loc = EndLocation;
+
+                                       if (!s.ResolveUnreachable (ec, !warning_shown))
+                                               ok = false;
+
+                                       if (s != EmptyStatement.Value)
                                                warning_shown = true;
-                                               Warning_DeadCodeFound (s.loc);
-                                       }
+                                       else
+                                               s.loc = Location.Null;
 
+                                       statements [ix] = EmptyStatement.Value;
                                        continue;
                                }
 
                                if (s.Resolve (ec) == false) {
                                        ok = false;
+                                       statements [ix] = EmptyStatement.Value;
                                        continue;
                                }
 
+                               num_statements = ix + 1;
+
                                if (s is LabeledStatement)
                                        unreachable = false;
                                else
-                                       unreachable = ! ec.CurrentBranching.IsReachable ();
-
-                               new_statements.Add (s);
+                                       unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
                        }
 
-                       statements = new_statements;
+                       Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
+                                     ec.CurrentBranching, statement_count, num_statements);
 
-                       Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
 
-                       FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
+                       FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
+
                        ec.CurrentBlock = prev_block;
 
                        // If we're a non-static `struct' constructor which doesn't have an
                        // initializer, then we must initialize all of the struct's fields.
-                       if ((this_variable != null) && (returns != FlowBranching.FlowReturns.Exception) &&
+                       if ((this_variable != null) &&
+                           (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
                            !this_variable.IsThisAssigned (ec, loc))
                                ok = false;
 
@@ -1747,23 +1790,39 @@ namespace Mono.CSharp {
                                                                "This label has not been referenced");
                        }
 
-                       if ((returns == FlowBranching.FlowReturns.Always) ||
-                           (returns == FlowBranching.FlowReturns.Exception) ||
-                           (returns == FlowBranching.FlowReturns.Unreachable))
+                       Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
+
+                       if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
+                           (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
+                           (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
                                flags |= Flags.HasRet;
 
+                       if (ok && (errors == Report.Errors)) {
+                               if (RootContext.WarningLevel >= 3)
+                                       UsageWarning (vector);
+                       }
+
                        return ok;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
-                       foreach (Statement s in statements)
-                               s.Emit (ec);
+                       for (int ix = 0; ix < num_statements; ix++){
+                               Statement s = (Statement) statements [ix];
+
+                               // Check whether we are the last statement in a
+                               // top-level block.
+
+                               if ((Parent == null) && (ix+1 == num_statements))
+                                       ec.IsLastStatement = true;
+                               else
+                                       ec.IsLastStatement = false;
 
-                       return (flags & Flags.HasRet) != 0;
+                               s.Emit (ec);
+                       }
                }
 
-               public override bool Emit (EmitContext ec)
+               public override void Emit (EmitContext ec)
                {
                        Block prev_block = ec.CurrentBlock;
 
@@ -1790,18 +1849,30 @@ namespace Mono.CSharp {
                        }
 
                        ec.Mark (StartLocation, true);
-                       bool retval = DoEmit (ec);
+                       DoEmit (ec);
                        ec.Mark (EndLocation, true); 
 
                        if (emit_debug_info && is_lexical_block)
                                ec.ig.EndScope ();
 
                        ec.CurrentBlock = prev_block;
-
-                       return retval;
                }
        }
 
+       //
+       // 
+       public class ToplevelBlock : Block {
+               public ToplevelBlock (Parameters parameters, Location start) :
+                       base (null, parameters, start, Location.Null)
+               {
+               }
+
+               public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
+                       base (null, flags, parameters, start, Location.Null)
+               {
+               }
+       }
+       
        public class SwitchLabel {
                Expression label;
                object converted;
@@ -2140,7 +2211,7 @@ namespace Mono.CSharp {
                        }
                        if (error)
                                return false;
-                       
+
                        return true;
                }
 
@@ -2201,6 +2272,8 @@ namespace Mono.CSharp {
                        public long nFirst;
                        public long nLast;
                        public ArrayList rgKeys = null;
+                       // how many items are in the bucket
+                       public int Size = 1;
                        public int Length
                        {
                                get { return (int) (nLast - nFirst + 1); }
@@ -2230,7 +2303,7 @@ namespace Mono.CSharp {
                /// <param name="ec"></param>
                /// <param name="val"></param>
                /// <returns></returns>
-               bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
+               void TableSwitchEmit (EmitContext ec, LocalBuilder val)
                {
                        int cElements = Elements.Count;
                        object [] rgKeys = new object [cElements];
@@ -2252,10 +2325,11 @@ namespace Mono.CSharp {
                                for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
                                {
                                        KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
-                                       if ((kbCurr.Length + kb.Length) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
+                                       if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
                                        {
                                                // merge blocks
                                                kbCurr.nLast = kb.nLast;
+                                               kbCurr.Size += kb.Size;
                                        }
                                        else
                                        {
@@ -2300,6 +2374,13 @@ namespace Mono.CSharp {
                        if (rgKeys.Length > 0)
                                typeKeys = rgKeys [0].GetType ();       // used for conversions
 
+                       Type compare_type;
+                       
+                       if (TypeManager.IsEnumType (SwitchType))
+                               compare_type = TypeManager.EnumToUnderlying (SwitchType);
+                       else
+                               compare_type = SwitchType;
+                       
                        for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
                        {
                                KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
@@ -2318,8 +2399,8 @@ namespace Mono.CSharp {
                                {
                                        // TODO: if all the keys in the block are the same and there are
                                        //       no gaps/defaults then just use a range-check.
-                                       if (SwitchType == TypeManager.int64_type ||
-                                               SwitchType == TypeManager.uint64_type)
+                                       if (compare_type == TypeManager.int64_type ||
+                                               compare_type == TypeManager.uint64_type)
                                        {
                                                // TODO: optimize constant/I4 cases
 
@@ -2328,7 +2409,7 @@ namespace Mono.CSharp {
                                                EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
                                                ig.Emit (OpCodes.Blt, lblDefault);
                                                ig.Emit (OpCodes.Ldloc, val);
-                                               EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
+                                               EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
                                                ig.Emit (OpCodes.Bgt, lblDefault);
 
                                                // normalize range
@@ -2391,7 +2472,6 @@ namespace Mono.CSharp {
 
                        // now emit the code for the sections
                        bool fFoundDefault = false;
-                       bool fAllReturn = true;
                        foreach (SwitchSection ss in Sections)
                        {
                                foreach (SwitchLabel sl in ss.Labels)
@@ -2404,18 +2484,14 @@ namespace Mono.CSharp {
                                                fFoundDefault = true;
                                        }
                                }
-                               bool returns = ss.Block.Emit (ec);
-                               fAllReturn &= returns;
+                               ss.Block.Emit (ec);
                                //ig.Emit (OpCodes.Br, lblEnd);
                        }
                        
                        if (!fFoundDefault) {
                                ig.MarkLabel (lblDefault);
-                               fAllReturn = false;
                        }
                        ig.MarkLabel (lblEnd);
-
-                       return fAllReturn;
                }
                //
                // This simple emit switch works, but does not take advantage of the
@@ -2423,7 +2499,7 @@ namespace Mono.CSharp {
                // TODO: remove non-string logic from here
                // TODO: binary search strings?
                //
-               bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
+               void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
                {
                        ILGenerator ig = ec.ig;
                        Label end_of_switch = ig.DefineLabel ();
@@ -2432,8 +2508,8 @@ namespace Mono.CSharp {
                        bool default_found = false;
                        bool first_test = true;
                        bool pending_goto_end = false;
-                       bool all_return = true;
                        bool null_found;
+                       bool default_at_end = false;
                        
                        ig.Emit (OpCodes.Ldloc, val);
                        
@@ -2455,6 +2531,7 @@ namespace Mono.CSharp {
                                        ig.Emit (OpCodes.Br, end_of_switch);
 
                                int label_count = ss.Labels.Count;
+                               bool mark_default = false;
                                null_found = false;
                                for (int label = 0; label < label_count; label++){
                                        SwitchLabel sl = (SwitchLabel) ss.Labels [label];
@@ -2468,7 +2545,9 @@ namespace Mono.CSharp {
                                        // If we are the default target
                                        //
                                        if (sl.Label == null){
-                                               ig.MarkLabel (default_target);
+                                               if (label+1 == label_count)
+                                                       default_at_end = true;
+                                               mark_default = true;
                                                default_found = true;
                                        } else {
                                                object lit = sl.Converted;
@@ -2500,23 +2579,19 @@ namespace Mono.CSharp {
                                foreach (SwitchLabel sl in ss.Labels)
                                        ig.MarkLabel (sl.ILLabelCode);
 
-                               bool returns = ss.Block.Emit (ec);
-                               if (returns)
-                                       pending_goto_end = false;
-                               else {
-                                       all_return = false;
-                                       pending_goto_end = true;
-                               }
+                               if (mark_default)
+                                       ig.MarkLabel (default_target);
+                               ss.Block.Emit (ec);
+                               pending_goto_end = !ss.Block.HasRet;
                                first_test = false;
                        }
-                       if (!default_found){
-                               ig.MarkLabel (default_target);
-                               all_return = false;
-                       }
                        ig.MarkLabel (next_test);
+                       if (default_found){
+                               if (!default_at_end)
+                                       ig.Emit (OpCodes.Br, default_target);
+                       } else 
+                               ig.MarkLabel (default_target);
                        ig.MarkLabel (end_of_switch);
-
-                       return all_return;
                }
 
                public override bool Resolve (EmitContext ec)
@@ -2541,12 +2616,14 @@ namespace Mono.CSharp {
                        ec.Switch = this;
                        ec.Switch.SwitchType = SwitchType;
 
+                       Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
                        ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
 
                        bool first = true;
                        foreach (SwitchSection ss in Sections){
                                if (!first)
-                                       ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
+                                       ec.CurrentBranching.CreateSibling (
+                                               null, FlowBranching.SiblingType.SwitchSection);
                                else
                                        first = false;
 
@@ -2556,15 +2633,19 @@ namespace Mono.CSharp {
 
 
                        if (!got_default)
-                               ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
+                               ec.CurrentBranching.CreateSibling (
+                                       null, FlowBranching.SiblingType.SwitchSection);
 
-                       ec.EndFlowBranching ();
+                       FlowBranching.Reachability reachability = ec.EndFlowBranching ();
                        ec.Switch = old_switch;
 
+                       Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
+                                     reachability);
+
                        return true;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        // Store variable for comparission purposes
                        LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
@@ -2585,11 +2666,10 @@ namespace Mono.CSharp {
                        ec.Switch = this;
 
                        // Emit Code.
-                       bool all_return;
                        if (SwitchType == TypeManager.string_type)
-                               all_return = SimpleSwitchEmit (ec, value);
+                               SimpleSwitchEmit (ec, value);
                        else
-                               all_return = TableSwitchEmit (ec, value);
+                               TableSwitchEmit (ec, value);
 
                        // Restore context state. 
                        ig.MarkLabel (ec.LoopEnd);
@@ -2599,8 +2679,6 @@ namespace Mono.CSharp {
                        //
                        ec.LoopEnd = old_end;
                        ec.Switch = old_switch;
-                       
-                       return all_return;
                }
        }
 
@@ -2618,21 +2696,27 @@ namespace Mono.CSharp {
                public override bool Resolve (EmitContext ec)
                {
                        expr = expr.Resolve (ec);
-                       return Statement.Resolve (ec) && expr != null;
+                       if (expr == null)
+                               return false;
+
+                       if (expr.Type.IsValueType){
+                               Error (185, "lock statement requires the expression to be " +
+                                      " a reference type (type is: `{0}'",
+                                      TypeManager.CSharpName (expr.Type));
+                               return false;
+                       }
+
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
+                       bool ok = Statement.Resolve (ec);
+                       ec.EndFlowBranching ();
+
+                       return ok;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        Type type = expr.Type;
-                       bool val;
                        
-                       if (type.IsValueType){
-                               Report.Error (185, loc, "lock statement requires the expression to be " +
-                                             " a reference type (type is: `" +
-                                             TypeManager.CSharpName (type) + "'");
-                               return false;
-                       }
-
                        ILGenerator ig = ec.ig;
                        LocalBuilder temp = ig.DeclareLocal (type);
                                
@@ -2642,12 +2726,9 @@ namespace Mono.CSharp {
                        ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
 
                        // try
-                       Label end = ig.BeginExceptionBlock ();
-                       bool old_in_try = ec.InTry;
-                       ec.InTry = true;
+                       ig.BeginExceptionBlock ();
                        Label finish = ig.DefineLabel ();
-                       val = Statement.Emit (ec);
-                       ec.InTry = old_in_try;
+                       Statement.Emit (ec);
                        // ig.Emit (OpCodes.Leave, finish);
 
                        ig.MarkLabel (finish);
@@ -2657,8 +2738,6 @@ namespace Mono.CSharp {
                        ig.Emit (OpCodes.Ldloc, temp);
                        ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
                        ig.EndExceptionBlock ();
-                       
-                       return val;
                }
        }
 
@@ -2685,19 +2764,16 @@ namespace Mono.CSharp {
                        return ret;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        bool previous_state = ec.CheckState;
                        bool previous_state_const = ec.ConstantCheckState;
-                       bool val;
                        
                        ec.CheckState = false;
                        ec.ConstantCheckState = false;
-                       val = Block.Emit (ec);
+                       Block.Emit (ec);
                        ec.CheckState = previous_state;
                        ec.ConstantCheckState = previous_state_const;
-
-                       return val;
                }
        }
 
@@ -2724,19 +2800,16 @@ namespace Mono.CSharp {
                        return ret;
                }
 
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        bool previous_state = ec.CheckState;
                        bool previous_state_const = ec.ConstantCheckState;
-                       bool val;
                        
                        ec.CheckState = true;
                        ec.ConstantCheckState = true;
-                       val = Block.Emit (ec);
+                       Block.Emit (ec);
                        ec.CheckState = previous_state;
                        ec.ConstantCheckState = previous_state_const;
-
-                       return val;
                }
        }
 
@@ -2760,16 +2833,13 @@ namespace Mono.CSharp {
                        return val;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        bool previous_state = ec.InUnsafe;
-                       bool val;
                        
                        ec.InUnsafe = true;
-                       val = Block.Emit (ec);
+                       Block.Emit (ec);
                        ec.InUnsafe = previous_state;
-
-                       return val;
                }
        }
 
@@ -2782,6 +2852,7 @@ namespace Mono.CSharp {
                Statement statement;
                Type expr_type;
                FixedData[] data;
+               bool has_ret;
 
                struct FixedData {
                        public bool is_object;
@@ -2827,6 +2898,7 @@ namespace Mono.CSharp {
                                Expression e = (Expression) p.Second;
 
                                vi.VariableInfo = null;
+                               vi.ReadOnly = true;
 
                                //
                                // The rules for the possible declarators are pretty wise,
@@ -2839,6 +2911,11 @@ namespace Mono.CSharp {
                                // is present, so we need to test for this particular case.
                                //
 
+                               if (e is Cast){
+                                       Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
+                                       return false;
+                               }
+                               
                                //
                                // Case 1: & object.
                                //
@@ -2923,17 +3000,40 @@ namespace Mono.CSharp {
                                        data [i].converted = null;
                                        data [i].vi = vi;
                                        i++;
+                                       continue;
+                               }
+
+                               //
+                               // For other cases, flag a `this is already fixed expression'
+                               //
+                               if (e is LocalVariableReference || e is ParameterReference ||
+                                   Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
+                                   
+                                       Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
+                                       return false;
                                }
+
+                               Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
+                               return false;
+                       }
+
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
+
+                       if (!statement.Resolve (ec)) {
+                               ec.KillFlowBranching ();
+                               return false;
                        }
 
-                       return statement.Resolve (ec);
+                       FlowBranching.Reachability reachability = ec.EndFlowBranching ();
+                       has_ret = reachability.IsUnreachable;
+
+                       return true;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
 
-                       bool is_ret = false;
                        LocalBuilder [] clear_list = new LocalBuilder [data.Length];
                        
                        for (int i = 0; i < data.Length; i++) {
@@ -2989,16 +3089,15 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       is_ret = statement.Emit (ec);
+                       statement.Emit (ec);
+
+                       if (has_ret)
+                               return;
 
-                       if (is_ret)
-                               return is_ret;
                        //
                        // Clear the pinned variable
                        //
                        for (int i = 0; i < data.Length; i++) {
-                               LocalInfo vi = data [i].vi;
-
                                if (data [i].is_object || data [i].expr.Type.IsArray) {
                                        ig.Emit (OpCodes.Ldc_I4_0);
                                        ig.Emit (OpCodes.Conv_U);
@@ -3008,8 +3107,6 @@ namespace Mono.CSharp {
                                        ig.Emit (OpCodes.Stloc, clear_list [i]);
                                }
                        }
-
-                       return is_ret;
                }
        }
        
@@ -3093,20 +3190,17 @@ namespace Mono.CSharp {
 
                        Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
 
-                       bool old_in_try = ec.InTry;
-                       ec.InTry = true;
-
                        if (!Block.Resolve (ec))
                                ok = false;
 
-                       ec.InTry = old_in_try;
-
                        FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
 
                        Report.Debug (1, "START OF CATCH BLOCKS", vector);
 
                        foreach (Catch c in Specific){
-                               ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
+                               ec.CurrentBranching.CreateSibling (
+                                       c.Block, FlowBranching.SiblingType.Catch);
+
                                Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
 
                                if (c.Name != null) {
@@ -3117,107 +3211,64 @@ namespace Mono.CSharp {
                                        vi.VariableInfo = null;
                                }
 
-                               bool old_in_catch = ec.InCatch;
-                               ec.InCatch = true;
-
                                if (!c.Resolve (ec))
                                        ok = false;
-
-                               ec.InCatch = old_in_catch;
-
-                               FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
-
-                               if (!current.AlwaysReturns && !current.AlwaysBreaks)
-                                       vector.AndLocals (current);
-                               else
-                                       vector.Or (current);
                        }
 
                        Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
 
                        if (General != null){
-                               ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
-                               Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
+                               ec.CurrentBranching.CreateSibling (
+                                       General.Block, FlowBranching.SiblingType.Catch);
 
-                               bool old_in_catch = ec.InCatch;
-                               ec.InCatch = true;
+                               Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
 
                                if (!General.Resolve (ec))
                                        ok = false;
-
-                               ec.InCatch = old_in_catch;
-
-                               FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
-
-                               if (!current.AlwaysReturns && !current.AlwaysBreaks)
-                                       vector.AndLocals (current);
-                               else    
-                                       vector.Or (current);
                        }
 
                        Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
 
                        if (Fini != null) {
                                if (ok)
-                                       ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
-                               Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
+                                       ec.CurrentBranching.CreateSibling (
+                                               Fini, FlowBranching.SiblingType.Finally);
 
-                               bool old_in_finally = ec.InFinally;
-                               ec.InFinally = true;
+                               Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
 
                                if (!Fini.Resolve (ec))
                                        ok = false;
-
-                               ec.InFinally = old_in_finally;
                        }
 
-                       FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
+                       FlowBranching.Reachability reachability = ec.EndFlowBranching ();
 
                        FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
 
-                       Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
-
-                       if ((returns == FlowBranching.FlowReturns.Sometimes) || (returns == FlowBranching.FlowReturns.Always)) {
-                               ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
-                       }
-
-                       ec.CurrentBranching.CurrentUsageVector.Or (vector);
+                       Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
 
-                       Report.Debug (1, "END OF TRY", ec.CurrentBranching);
-
-                       if (returns != FlowBranching.FlowReturns.Always) {
+                       if (reachability.Returns != FlowBranching.FlowReturns.Always) {
                                // Unfortunately, System.Reflection.Emit automatically emits a leave
                                // to the end of the finally block.  This is a problem if `returns'
                                // is true since we may jump to a point after the end of the method.
                                // As a workaround, emit an explicit ret here.
-                               ec.NeedExplicitReturn = true;
+                               ec.NeedReturnLabel ();
                        }
 
                        return ok;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
-                       Label end;
                        Label finish = ig.DefineLabel ();;
-                       bool returns;
 
-                       ec.TryCatchLevel++;
-                       end = ig.BeginExceptionBlock ();
-                       bool old_in_try = ec.InTry;
-                       ec.InTry = true;
-                       returns = Block.Emit (ec);
-                       ec.InTry = old_in_try;
+                       ig.BeginExceptionBlock ();
+                       Block.Emit (ec);
 
                        //
                        // System.Reflection.Emit provides this automatically:
                        // ig.Emit (OpCodes.Leave, finish);
 
-                       bool old_in_catch = ec.InCatch;
-                       ec.InCatch = true;
-                       DeclSpace ds = ec.DeclSpace;
-
                        foreach (Catch c in Specific){
                                LocalInfo vi;
                                
@@ -3232,31 +3283,22 @@ namespace Mono.CSharp {
                                } else
                                        ig.Emit (OpCodes.Pop);
                                
-                               if (!c.Block.Emit (ec))
-                                       returns = false;
+                               c.Block.Emit (ec);
                        }
 
                        if (General != null){
                                ig.BeginCatchBlock (TypeManager.object_type);
                                ig.Emit (OpCodes.Pop);
-                               if (!General.Block.Emit (ec))
-                                       returns = false;
+                               General.Block.Emit (ec);
                        }
-                       ec.InCatch = old_in_catch;
 
                        ig.MarkLabel (finish);
                        if (Fini != null){
                                ig.BeginFinallyBlock ();
-                               bool old_in_finally = ec.InFinally;
-                               ec.InFinally = true;
                                Fini.Emit (ec);
-                               ec.InFinally = old_in_finally;
                        }
                        
                        ig.EndExceptionBlock ();
-                       ec.TryCatchLevel--;
-
-                       return returns;
                }
        }
 
@@ -3354,18 +3396,13 @@ namespace Mono.CSharp {
                        ILGenerator ig = ec.ig;
                        int i = 0;
 
-                       bool old_in_try = ec.InTry;
-                       ec.InTry = true;
                        for (i = 0; i < assign.Length; i++) {
                                assign [i].EmitStatement (ec);
                                
                                ig.BeginExceptionBlock ();
                        }
                        Statement.Emit (ec);
-                       ec.InTry = old_in_try;
 
-                       bool old_in_finally = ec.InFinally;
-                       ec.InFinally = true;
                        var_list.Reverse ();
                        foreach (DictionaryEntry e in var_list){
                                LocalVariableReference var = (LocalVariableReference) e.Key;
@@ -3373,15 +3410,42 @@ namespace Mono.CSharp {
                                i--;
                                
                                ig.BeginFinallyBlock ();
-                               
-                               var.Emit (ec);
-                               ig.Emit (OpCodes.Brfalse, skip);
-                               converted_vars [i].Emit (ec);
-                               ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+
+                               if (!var.Type.IsValueType) {
+                                       var.Emit (ec);
+                                       ig.Emit (OpCodes.Brfalse, skip);
+                                       converted_vars [i].Emit (ec);
+                                       ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                               } else {
+                                       Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
+
+                                       if (!(ml is MethodGroupExpr)) {
+                                               var.Emit (ec);
+                                               ig.Emit (OpCodes.Box, var.Type);
+                                               ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                                       } else {
+                                               MethodInfo mi = null;
+
+                                               foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
+                                                       if (mk.GetParameters().Length == 0) {
+                                                               mi = mk;
+                                                               break;
+                                                       }
+                                               }
+
+                                               if (mi == null) {
+                                                       Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
+                                                       return false;
+                                               }
+
+                                               var.AddressOf (ec, AddressOp.Load);
+                                               ig.Emit (OpCodes.Call, mi);
+                                       }
+                               }
+
                                ig.MarkLabel (skip);
                                ig.EndExceptionBlock ();
                        }
-                       ec.InFinally = old_in_finally;
 
                        return false;
                }
@@ -3399,21 +3463,16 @@ namespace Mono.CSharp {
                                expr.Emit (ec);
                        ig.Emit (OpCodes.Stloc, local_copy);
 
-                       bool old_in_try = ec.InTry;
-                       ec.InTry = true;
                        ig.BeginExceptionBlock ();
                        Statement.Emit (ec);
-                       ec.InTry = old_in_try;
                        
                        Label skip = ig.DefineLabel ();
-                       bool old_in_finally = ec.InFinally;
                        ig.BeginFinallyBlock ();
                        ig.Emit (OpCodes.Ldloc, local_copy);
                        ig.Emit (OpCodes.Brfalse, skip);
                        ig.Emit (OpCodes.Ldloc, local_copy);
                        ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
                        ig.MarkLabel (skip);
-                       ec.InFinally = old_in_finally;
                        ig.EndExceptionBlock ();
 
                        return false;
@@ -3439,19 +3498,36 @@ namespace Mono.CSharp {
 
                                if (!ResolveExpression (ec))
                                        return false;
-                       }                       
+                       }
+
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
+
+                       bool ok = Statement.Resolve (ec);
+
+                       if (!ok) {
+                               ec.KillFlowBranching ();
+                               return false;
+                       }
+                                       
+                       FlowBranching.Reachability reachability = ec.EndFlowBranching ();
+
+                       if (reachability.Returns != FlowBranching.FlowReturns.Always) {
+                               // Unfortunately, System.Reflection.Emit automatically emits a leave
+                               // to the end of the finally block.  This is a problem if `returns'
+                               // is true since we may jump to a point after the end of the method.
+                               // As a workaround, emit an explicit ret here.
+                               ec.NeedReturnLabel ();
+                       }
 
-                       return Statement.Resolve (ec);
+                       return true;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        if (expression_or_block is DictionaryEntry)
-                               return EmitLocalVariableDecls (ec);
+                               EmitLocalVariableDecls (ec);
                        else if (expression_or_block is Expression)
-                               return EmitExpression (ec);
-
-                       return false;
+                               EmitExpression (ec);
                }
        }
 
@@ -3511,7 +3587,7 @@ namespace Mono.CSharp {
                                if (hm == null){
                                        error1579 (expr.Type);
                                        return false;
-                               }
+                               }                       
 
                                array_type = expr.Type;
                                element_type = hm.element_type;
@@ -3519,8 +3595,10 @@ namespace Mono.CSharp {
                                empty = new EmptyExpression (hm.element_type);
                        }
 
-                       ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
-                       ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
+                       bool ok = true;
+
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
+                       ec.CurrentBranching.CreateSibling ();
 
                        //
                        //
@@ -3532,18 +3610,25 @@ namespace Mono.CSharp {
                        //
                        conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
                        if (conv == null)
-                               return false;
+                               ok = false;
 
                        variable = variable.ResolveLValue (ec, empty);
                        if (variable == null)
-                               return false;
+                               ok = false;
+
+                       bool disposable = (hm != null) && hm.is_disposable;
+                       if (disposable)
+                               ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
 
                        if (!statement.Resolve (ec))
-                               return false;
+                               ok = false;
 
-                       FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
+                       if (disposable)
+                               ec.EndFlowBranching ();
 
-                       return true;
+                       ec.EndFlowBranching ();
+
+                       return ok;
                }
                
                //
@@ -3578,16 +3663,16 @@ namespace Mono.CSharp {
                //
                static MethodInfo FetchMethodGetCurrent (Type t)
                {
-                       MemberList move_next_list;
-                       
-                       move_next_list = TypeContainer.FindMembers (
+                       MemberList get_current_list;
+
+                       get_current_list = TypeContainer.FindMembers (
                                t, MemberTypes.Method,
                                BindingFlags.Public | BindingFlags.Instance,
                                Type.FilterName, "get_Current");
-                       if (move_next_list.Count == 0)
+                       if (get_current_list.Count == 0)
                                return null;
 
-                       foreach (MemberInfo m in move_next_list){
+                       foreach (MemberInfo m in get_current_list){
                                MethodInfo mi = (MethodInfo) m;
                                Type [] args;
 
@@ -3683,30 +3768,51 @@ namespace Mono.CSharp {
                        // Ok, we can access it, now make sure that we can do something
                        // with this `GetEnumerator'
                        //
-
+                       
+                       Type return_type = mi.ReturnType;
                        if (mi.ReturnType == TypeManager.ienumerator_type ||
-                           TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
-                           (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
-                               if (declaring != TypeManager.string_type) {
+                           TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
+                           (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
+                               
+                               //
+                               // If it is not an interface, lets try to find the methods ourselves.
+                               // For example, if we have:
+                               // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
+                               // We can avoid the iface call. This is a runtime perf boost.
+                               // even bigger if we have a ValueType, because we avoid the cost
+                               // of boxing.
+                               //
+                               // We have to make sure that both methods exist for us to take
+                               // this path. If one of the methods does not exist, we will just
+                               // use the interface. Sadly, this complex if statement is the only
+                               // way I could do this without a goto
+                               //
+                               
+                               if (return_type.IsInterface ||
+                                   (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
+                                   (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
+                                       
                                        hm.move_next = TypeManager.bool_movenext_void;
                                        hm.get_current = TypeManager.object_getcurrent_void;
-                                       return true;
+                                       return true;    
                                }
-                       }
-
-                       //
-                       // Ok, so they dont return an IEnumerable, we will have to
-                       // find if they support the GetEnumerator pattern.
-                       //
-                       Type return_type = mi.ReturnType;
 
-                       hm.move_next = FetchMethodMoveNext (return_type);
-                       if (hm.move_next == null)
-                               return false;
-                       hm.get_current = FetchMethodGetCurrent (return_type);
-                       if (hm.get_current == null)
-                               return false;
+                       } else {
 
+                               //
+                               // Ok, so they dont return an IEnumerable, we will have to
+                               // find if they support the GetEnumerator pattern.
+                               //
+                               
+                               hm.move_next = FetchMethodMoveNext (return_type);
+                               if (hm.move_next == null)
+                                       return false;
+                               
+                               hm.get_current = FetchMethodGetCurrent (return_type);
+                               if (hm.get_current == null)
+                                       return false;
+                       }
+                       
                        hm.element_type = hm.get_current.ReturnType;
                        hm.enumerator_type = return_type;
                        hm.is_disposable = !hm.enumerator_type.IsSealed ||
@@ -3741,7 +3847,7 @@ namespace Mono.CSharp {
                        
                        mi = TypeContainer.FindMembers (t, MemberTypes.Method,
                                                        BindingFlags.Public | BindingFlags.NonPublic |
-                                                       BindingFlags.Instance,
+                                                       BindingFlags.Instance | BindingFlags.DeclaredOnly,
                                                        FilterEnumerator, hm);
 
                        if (mi.Count == 0)
@@ -3759,8 +3865,11 @@ namespace Mono.CSharp {
                {
                        ForeachHelperMethods hm = new ForeachHelperMethods (ec);
 
-                       if (TryType (t, hm))
-                               return hm;
+                       for (Type tt = t; tt != null && tt != TypeManager.object_type;){
+                               if (TryType (tt, hm))
+                                       return hm;
+                               tt = tt.BaseType;
+                       }
 
                        //
                        // Now try to find the method in the interfaces
@@ -3795,14 +3904,9 @@ namespace Mono.CSharp {
                bool EmitCollectionForeach (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
-                       VariableStorage enumerator, disposable;
+                       VariableStorage enumerator;
 
                        enumerator = new VariableStorage (ec, hm.enumerator_type);
-                       if (hm.is_disposable)
-                               disposable = new VariableStorage (ec, TypeManager.idisposable_type);
-                       else
-                               disposable = null;
-
                        enumerator.EmitThis ();
                        //
                        // Instantiate the enumerator
@@ -3811,11 +3915,18 @@ namespace Mono.CSharp {
                                if (expr is IMemoryLocation){
                                        IMemoryLocation ml = (IMemoryLocation) expr;
 
-                                       ml.AddressOf (ec, AddressOp.Load);
+                                       Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
+
+                                       if (!(ml1 is MethodGroupExpr)) {
+                                               expr.Emit(ec);
+                                               ec.ig.Emit(OpCodes.Box, expr.Type);
+                                       } else {
+                                               ml.AddressOf (ec, AddressOp.Load);
+                                       }
                                } else
                                        throw new Exception ("Expr " + expr + " of type " + expr.Type +
                                                             " does not implement IMemoryLocation");
-                               ig.Emit (OpCodes.Call, hm.get_enumerator);
+                               ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
                        } else {
                                expr.Emit (ec);
                                ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
@@ -3826,25 +3937,20 @@ namespace Mono.CSharp {
                        // Protect the code in a try/finalize block, so that
                        // if the beast implement IDisposable, we get rid of it
                        //
-                       Label l;
-                       bool old_in_try = ec.InTry;
-
-                       if (hm.is_disposable) {
-                               l = ig.BeginExceptionBlock ();
-                               ec.InTry = true;
-                       }
+                       if (hm.is_disposable)
+                               ig.BeginExceptionBlock ();
                        
                        Label end_try = ig.DefineLabel ();
                        
                        ig.MarkLabel (ec.LoopBegin);
-                       enumerator.EmitLoad ();
-                       ig.Emit (OpCodes.Callvirt, hm.move_next);
+                       
+                       enumerator.EmitCall (hm.move_next);
+                       
                        ig.Emit (OpCodes.Brfalse, end_try);
                        if (ec.InIterator)
                                ec.EmitThis ();
                        
-                       enumerator.EmitLoad ();
-                       ig.Emit (OpCodes.Callvirt, hm.get_current);
+                       enumerator.EmitCall (hm.get_current);
 
                        if (ec.InIterator){
                                conv.Emit (ec);
@@ -3855,7 +3961,6 @@ namespace Mono.CSharp {
                        statement.Emit (ec);
                        ig.Emit (OpCodes.Br, ec.LoopBegin);
                        ig.MarkLabel (end_try);
-                       ec.InTry = old_in_try;
                        
                        // The runtime provides this for us.
                        // ig.Emit (OpCodes.Leave, end);
@@ -3864,23 +3969,20 @@ namespace Mono.CSharp {
                        // Now the finally block
                        //
                        if (hm.is_disposable) {
-                               Label end_finally = ig.DefineLabel ();
-                               bool old_in_finally = ec.InFinally;
-                               ec.InFinally = true;
+                               Label call_dispose = ig.DefineLabel ();
                                ig.BeginFinallyBlock ();
-
-                               disposable.EmitThis ();
+                               
                                enumerator.EmitThis ();
                                enumerator.EmitLoad ();
                                ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
-                               disposable.EmitStore ();
-                               disposable.EmitLoad ();
-                               ig.Emit (OpCodes.Brfalse, end_finally);
-                               disposable.EmitThis ();
-                               disposable.EmitLoad ();
+                               ig.Emit (OpCodes.Dup);
+                               ig.Emit (OpCodes.Brtrue_S, call_dispose);
+                               ig.Emit (OpCodes.Pop);
+                               ig.Emit (OpCodes.Endfinally);
+                               
+                               ig.MarkLabel (call_dispose);
                                ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
-                               ig.MarkLabel (end_finally);
-                               ec.InFinally = old_in_finally;
+                               
 
                                // The runtime generates this anyways.
                                // ig.Emit (OpCodes.Endfinally);
@@ -4011,7 +4113,7 @@ namespace Mono.CSharp {
                                for (int i = 0; i < rank; i++)
                                        args [i] = TypeManager.int32_type;
 
-                               ModuleBuilder mb = CodeGen.ModuleBuilder;
+                               ModuleBuilder mb = CodeGen.Module.Builder;
                                get = mb.GetArrayMethod (
                                        array_type, "Get",
                                        CallingConventions.HasThis| CallingConventions.Standard,
@@ -4045,31 +4147,21 @@ namespace Mono.CSharp {
                        return false;
                }
                
-               protected override bool DoEmit (EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
-                       bool ret_val;
-                       
                        ILGenerator ig = ec.ig;
                        
                        Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
-                       bool old_inloop = ec.InLoop;
-                       int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
                        ec.LoopBegin = ig.DefineLabel ();
                        ec.LoopEnd = ig.DefineLabel ();
-                       ec.InLoop = true;
-                       ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
                        
                        if (hm != null)
-                               ret_val = EmitCollectionForeach (ec);
+                               EmitCollectionForeach (ec);
                        else
-                               ret_val = EmitArrayForeach (ec);
+                               EmitArrayForeach (ec);
                        
                        ec.LoopBegin = old_begin;
                        ec.LoopEnd = old_end;
-                       ec.InLoop = old_inloop;
-                       ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
-
-                       return ret_val;
                }
        }
 }