Reorder fields to improve object layout since the runtime can't do it for corlib...
[mono.git] / mcs / mcs / iterators.cs
index 44af394776ef23da20be8edd5a2018a605a2d1d6..7e082c3a76d11b85485706a448455ab92caa6a4e 100644 (file)
 //
 
 using System;
-using System.Collections;
-using System.Reflection;
-using System.Reflection.Emit;
+using System.Collections.Generic;
 
-namespace Mono.CSharp {
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
 
-       public class Yield : ResumableStatement {
-               Expression expr;
+namespace Mono.CSharp
+{
+       public abstract class YieldStatement<T> : ResumableStatement where T : StateMachineInitializer
+       {
+               protected Expression expr;
                bool unwind_protect;
-
+               protected T machine_initializer;
                int resume_pc;
 
-               public Yield (Expression expr, Location l)
+               protected YieldStatement (Expression expr, Location l)
                {
                        this.expr = expr;
                        loc = l;
                }
 
-               public static bool CheckContext (EmitContext ec, Location loc)
+               protected override void CloneTo (CloneContext clonectx, Statement t)
                {
-                       for (Block block = ec.CurrentBlock; block != null; block = block.Parent) {
-                               if (!block.Unsafe)
-                                       continue;
+                       var target = (YieldStatement<T>) t;
+                       target.expr = expr.Clone (clonectx);
+               }
 
-                               Report.Error (1629, loc, "Unsafe code may not appear in iterators");
-                               return false;
-                       }
+               protected override void DoEmit (EmitContext ec)
+               {
+                       machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
+               }
 
-                       //
-                       // We can't use `ec.InUnsafe' here because it's allowed to have an iterator
-                       // inside an unsafe class.  See test-martin-29.cs for an example.
-                       //
-                       if (!ec.CurrentAnonymousMethod.IsIterator) {
-                               Report.Error (1621, loc,
-                                             "The yield statement cannot be used inside " +
-                                             "anonymous method blocks");
+               public override bool Resolve (BlockContext bc)
+               {
+                       expr = expr.Resolve (bc);
+                       if (expr == null)
                                return false;
-                       }
+
+                       machine_initializer = bc.CurrentAnonymousMethod as T;
+
+                       if (!bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
+                               unwind_protect = bc.CurrentBranching.AddResumePoint (this, loc, out resume_pc);
 
                        return true;
                }
+       }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+       public class Yield : YieldStatement<Iterator>
+       {
+               public Yield (Expression expr, Location loc)
+                       : base (expr, loc)
                {
-                       expr.MutateHoistedGenericType (storey);
                }
-               
-               public override bool Resolve (EmitContext ec)
+
+               public static bool CheckContext (ResolveContext ec, Location loc)
                {
-                       expr = expr.Resolve (ec);
-                       if (expr == null)
+                       if (!ec.CurrentAnonymousMethod.IsIterator) {
+                               ec.Report.Error (1621, loc,
+                                       "The yield statement cannot be used inside anonymous method blocks");
                                return false;
+                       }
 
-                       Report.Debug (64, "RESOLVE YIELD #1", this, ec, expr, expr.GetType (),
-                                     ec.CurrentAnonymousMethod, ec.CurrentIterator);
+                       return true;
+               }
 
-                       if (!CheckContext (ec, loc))
+               public override bool Resolve (BlockContext bc)
+               {
+                       if (!CheckContext (bc, loc))
+                               return false;
+
+                       if (!base.Resolve (bc))
                                return false;
 
-                       Iterator iterator = ec.CurrentIterator;
-                       if (expr.Type != iterator.OriginalIteratorType) {
-                               expr = Convert.ImplicitConversionRequired (
-                                       ec, expr, iterator.OriginalIteratorType, loc);
+                       var otype = bc.CurrentIterator.OriginalIteratorType;
+                       if (expr.Type != otype) {
+                               expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
                                if (expr == null)
                                        return false;
                        }
 
-                       if (!ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
-                               unwind_protect = ec.CurrentBranching.AddResumePoint (this, loc, out resume_pc);
-
                        return true;
                }
-
-               protected override void DoEmit (EmitContext ec)
-               {
-                       ec.CurrentIterator.MarkYield (ec, expr, resume_pc, unwind_protect, resume_point);
-               }
-
-               protected override void CloneTo (CloneContext clonectx, Statement t)
-               {
-                       Yield target = (Yield) t;
-
-                       target.expr = expr.Clone (clonectx);
-               }
        }
 
-       public class YieldBreak : ExitStatement {
+       public class YieldBreak : ExitStatement
+       {
+               Iterator iterator;
+
                public YieldBreak (Location l)
                {
                        loc = l;
                }
 
-               public override void Error_FinallyClause ()
+               public override void Error_FinallyClause (Report Report)
                {
                        Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
                }
@@ -117,99 +120,95 @@ namespace Mono.CSharp {
                        throw new NotSupportedException ();
                }
 
-               protected override bool DoResolve (EmitContext ec)
+               protected override bool DoResolve (BlockContext ec)
                {
+                       iterator = ec.CurrentIterator;
                        return Yield.CheckContext (ec, loc);
                }
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ec.CurrentIterator.EmitYieldBreak (ec.ig, unwind_protect);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       // nothing to do
+                       iterator.EmitYieldBreak (ec, unwind_protect);
                }
        }
 
-       //
-       // Wraps method block into iterator wrapper block
-       //
-       class IteratorStatement : Statement
+       public abstract class StateMachine : AnonymousMethodStorey
        {
-               Iterator iterator;
-               Block original_block;
-
-               public IteratorStatement (Iterator iterator, Block original_block)
+               public enum State
                {
-                       this.iterator = iterator;
-                       this.original_block = original_block;
-                       this.loc = iterator.Location;
+                       Running = -3, // Used only in CurrentPC, never stored into $PC
+                       Uninitialized = -2,
+                       After = -1,
+                       Start = 0
                }
 
-               protected override void CloneTo (CloneContext clonectx, Statement target)
+               Field disposing_field;
+               Field pc_field;
+               int local_name_idx;
+               StateMachineMethod method;
+
+               protected StateMachine (Block block, TypeContainer parent, MemberBase host, TypeParameter[] tparams, string name)
+                       : base (block, parent, host, tparams, name)
                {
-                       IteratorStatement t = (IteratorStatement) target;
-                       t.original_block = (ExplicitBlock) original_block.Clone (clonectx);
-                       t.iterator = (Iterator) iterator.Clone (clonectx);
                }
 
-               public override bool Resolve (EmitContext ec)
-               {
-                       ec.StartFlowBranching (iterator);
-                       bool ok = original_block.Resolve (ec);
-                       ec.EndFlowBranching ();
-                       return ok;
+               #region Properties
+
+               public Field DisposingField {
+                       get {
+                               return disposing_field;
+                       }
                }
 
-               protected override void DoEmit (EmitContext ec)
-               {
-                       iterator.EmitMoveNext (ec, original_block);
+               public StateMachineMethod StateMachineMethod {
+                       get {
+                               return method;
+                       }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       original_block.MutateHoistedGenericType (storey);
-                       iterator.MutateHoistedGenericType (storey);
+               public Field PC {
+                       get {
+                               return pc_field;
+                       }
                }
-       }
 
-       public class IteratorStorey : AnonymousMethodStorey
-       {
-               class IteratorMethod : Method
+               #endregion
+
+               public void AddEntryMethod (StateMachineMethod method)
                {
-                       readonly IteratorStorey host;
+                       if (this.method != null)
+                               throw new InternalErrorException ();
 
-                       public IteratorMethod (IteratorStorey host, FullNamedExpression returnType, int mod, MemberName name)
-                               : base (host, null, returnType, mod | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
-                                 name, ParametersCompiled.EmptyReadOnlyParameters, null)
-                       {
-                               this.host = host;
+                       this.method = method;
+                       AddMethod (method);
+               }
 
-                               Block = new ToplevelBlock (host.Iterator.Container.Toplevel, ParametersCompiled.EmptyReadOnlyParameters, Location);
-                       }
+               protected override bool DoDefineMembers ()
+               {
+                       pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
+                       disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
 
-                       public override EmitContext CreateEmitContext (ILGenerator ig)
-                       {
-                               EmitContext ec = new EmitContext (
-                                       this, this.ds, ig, MemberType, ModFlags, false);
+                       return base.DoDefineMembers ();
+               }
 
-                               ec.CurrentAnonymousMethod = host.Iterator;
-                               return ec;
-                       }
+               protected override string GetVariableMangledName (LocalVariable local_info)
+               {
+                       return "<" + local_info.Name + ">__" + local_name_idx++.ToString ();
                }
+       }
 
-               class GetEnumeratorMethod : IteratorMethod
+       class IteratorStorey : StateMachine
+       {
+               class GetEnumeratorMethod : StateMachineMethod
                {
                        sealed class GetEnumeratorStatement : Statement
                        {
-                               IteratorStorey host;
-                               IteratorMethod host_method;
+                               readonly IteratorStorey host;
+                               readonly StateMachineMethod host_method;
 
                                Expression new_storey;
 
-                               public GetEnumeratorStatement (IteratorStorey host, IteratorMethod host_method)
+                               public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
                                {
                                        this.host = host;
                                        this.host_method = host_method;
@@ -221,28 +220,28 @@ namespace Mono.CSharp {
                                        throw new NotSupportedException ();
                                }
 
-                               public override bool Resolve (EmitContext ec)
+                               public override bool Resolve (BlockContext ec)
                                {
-                                       TypeExpression storey_type_expr = new TypeExpression (host.TypeBuilder, loc);
-                                       ArrayList init = null;
+                                       TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
+                                       List<Expression> init = null;
                                        if (host.hoisted_this != null) {
-                                               init = new ArrayList (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
+                                               init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
                                                HoistedThis ht = host.hoisted_this;
-                                               FieldExpr from = new FieldExpr (ht.Field.FieldBuilder, loc);
-                                               from.InstanceExpression = CompilerGeneratedThis.Instance;
+                                               FieldExpr from = new FieldExpr (ht.Field, loc);
+                                               from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
                                                init.Add (new ElementInitializer (ht.Field.Name, from, loc));
                                        }
 
                                        if (host.hoisted_params != null) {
                                                if (init == null)
-                                                       init = new ArrayList (host.HoistedParameters.Count);
+                                                       init = new List<Expression> (host.HoistedParameters.Count);
 
                                                for (int i = 0; i < host.hoisted_params.Count; ++i) {
-                                                       HoistedParameter hp = (HoistedParameter) host.hoisted_params [i];
-                                                       HoistedParameter hp_cp = (HoistedParameter) host.hoisted_params_copy [i];
+                                                       HoistedParameter hp = host.hoisted_params [i];
+                                                       HoistedParameter hp_cp = host.hoisted_params_copy [i];
 
-                                                       FieldExpr from = new FieldExpr (hp_cp.Field.FieldBuilder, loc);
-                                                       from.InstanceExpression = CompilerGeneratedThis.Instance;
+                                                       FieldExpr from = new FieldExpr (hp_cp.Field, loc);
+                                                       from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
 
                                                        init.Add (new ElementInitializer (hp.Field.Name, from, loc));
                                                }
@@ -259,56 +258,44 @@ namespace Mono.CSharp {
                                        if (new_storey != null)
                                                new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
 
-                                       if (TypeManager.int_interlocked_compare_exchange == null) {
-                                               Type t = TypeManager.CoreLookupType ("System.Threading", "Interlocked", Kind.Class, true);
-                                               if (t != null) {
-                                                       TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod (
-                                                               t, "CompareExchange", loc, TypeManager.int32_type,
-                                                               TypeManager.int32_type, TypeManager.int32_type);
-                                               }
-                                       }
-
                                        ec.CurrentBranching.CurrentUsageVector.Goto ();
                                        return true;
                                }
 
                                protected override void DoEmit (EmitContext ec)
                                {
-                                       ILGenerator ig = ec.ig;
-                                       Label label_init = ig.DefineLabel ();
+                                       Label label_init = ec.DefineLabel ();
 
-                                       ig.Emit (OpCodes.Ldarg_0);
-                                       ig.Emit (OpCodes.Ldflda, host.PC.FieldBuilder);
-                                       IntConstant.EmitInt (ig, (int) Iterator.State.Start);
-                                       IntConstant.EmitInt (ig, (int) Iterator.State.Uninitialized);
-                                       ig.Emit (OpCodes.Call, TypeManager.int_interlocked_compare_exchange);
+                                       ec.Emit (OpCodes.Ldarg_0);
+                                       ec.Emit (OpCodes.Ldflda, host.PC.Spec);
+                                       ec.EmitInt ((int) State.Start);
+                                       ec.EmitInt ((int) State.Uninitialized);
 
-                                       IntConstant.EmitInt (ig, (int) Iterator.State.Uninitialized);
-                                       ig.Emit (OpCodes.Bne_Un_S, label_init);
+                                       var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
+                                       if (m != null)
+                                               ec.Emit (OpCodes.Call, m);
 
-                                       ig.Emit (OpCodes.Ldarg_0);
-                                       ig.Emit (OpCodes.Ret);
+                                       ec.EmitInt ((int) State.Uninitialized);
+                                       ec.Emit (OpCodes.Bne_Un_S, label_init);
 
-                                       ig.MarkLabel (label_init);
+                                       ec.Emit (OpCodes.Ldarg_0);
+                                       ec.Emit (OpCodes.Ret);
 
-                                       new_storey.Emit (ec);
-                                       ig.Emit (OpCodes.Ret);
-                               }
+                                       ec.MarkLabel (label_init);
 
-                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                               {
-                                       throw new NotSupportedException ();
+                                       new_storey.Emit (ec);
+                                       ec.Emit (OpCodes.Ret);
                                }
                        }
 
                        public GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
-                               : base (host, returnType, 0, name)
+                               : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name)
                        {
                                Block.AddStatement (new GetEnumeratorStatement (host, this));
                        }
                }
 
-               class DisposeMethod : IteratorMethod
+               class DisposeMethod : StateMachineMethod
                {
                        sealed class DisposeMethodStatement : Statement
                        {
@@ -325,28 +312,24 @@ namespace Mono.CSharp {
                                        throw new NotSupportedException ();
                                }
 
-                               public override bool Resolve (EmitContext ec)
+                               public override bool Resolve (BlockContext ec)
                                {
                                        return true;
                                }
 
                                protected override void DoEmit (EmitContext ec)
                                {
+                                       ec.CurrentAnonymousMethod = iterator;
                                        iterator.EmitDispose (ec);
                                }
-
-                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                               {
-                                       throw new NotSupportedException ();
-                               }
                        }
 
                        public DisposeMethod (IteratorStorey host)
-                               : base (host, TypeManager.system_void_expr, Modifiers.PUBLIC, new MemberName ("Dispose", host.Location))
+                               : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
+                                       new MemberName ("Dispose", host.Location))
                        {
                                host.AddMethod (this);
 
-                               Block = new ToplevelBlock (host.Iterator.Container, ParametersCompiled.EmptyReadOnlyParameters, Location);
                                Block.AddStatement (new DisposeMethodStatement (host.Iterator));
                        }
                }
@@ -359,15 +342,16 @@ namespace Mono.CSharp {
                        readonly Method method;
 
                        public DynamicMethodGroupExpr (Method method, Location loc)
-                               : base (null, loc)
+                               : base ((IList<MemberSpec>) null, null, loc)
                        {
                                this.method = method;
+                               eclass = ExprClass.Unresolved;
                        }
 
-                       public override Expression DoResolve (EmitContext ec)
+                       protected override Expression DoResolve (ResolveContext ec)
                        {
-                               Methods = new MethodBase [] { method.MethodBuilder };
-                               type = method.Parent.TypeBuilder;
+                               Methods = new List<MemberSpec> (1) { method.Spec };
+                               type = method.Parent.Definition;
                                InstanceExpression = new CompilerGeneratedThis (type, Location);
                                return base.DoResolve (ec);
                        }
@@ -383,10 +367,10 @@ namespace Mono.CSharp {
                                this.field = field;
                        }
 
-                       public override Expression DoResolve (EmitContext ec)
+                       protected override Expression DoResolve (ResolveContext ec)
                        {
-                               FieldInfo = field.FieldBuilder;
-                               type = TypeManager.TypeToCoreType (FieldInfo.FieldType);
+                               spec = field.Spec;
+                               type = spec.MemberType;
                                InstanceExpression = new CompilerGeneratedThis (type, Location);
                                return base.DoResolve (ec);
                        }
@@ -394,8 +378,9 @@ namespace Mono.CSharp {
 
                public readonly Iterator Iterator;
 
+               List<HoistedParameter> hoisted_params_copy;
+
                TypeExpr iterator_type_expr;
-               Field pc_field;
                Field current_field;
 
                TypeExpr enumerator_type;
@@ -404,57 +389,49 @@ namespace Mono.CSharp {
                TypeExpr generic_enumerator_type;
                TypeExpr generic_enumerable_type;
 
-               ArrayList hoisted_params_copy;
-               int local_name_idx;
-
                public IteratorStorey (Iterator iterator)
-                       : base (iterator.Container.Toplevel, iterator.Host,
-                         iterator.OriginalMethod as MemberBase, iterator.GenericMethod, "Iterator")
+                       : base (iterator.Container.ParametersBlock, iterator.Host,
+                         iterator.OriginalMethod as MemberBase, iterator.GenericMethod == null ? null : iterator.GenericMethod.CurrentTypeParameters, "Iterator")
                {
                        this.Iterator = iterator;
                }
 
-               public Field PC {
-                       get { return pc_field; }
-               }
-
                public Field CurrentField {
                        get { return current_field; }
                }
 
-               public ArrayList HoistedParameters {
+               public IList<HoistedParameter> HoistedParameters {
                        get { return hoisted_params; }
                }
 
-               protected override TypeExpr [] ResolveBaseTypes (out TypeExpr base_class)
+               protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
                {
-                       iterator_type_expr = new TypeExpression (MutateType (Iterator.OriginalIteratorType), Location);
+                       var mtype = Iterator.OriginalIteratorType;
+                       if (Mutator != null)
+                               mtype = Mutator.Mutate (mtype);
+
+                       iterator_type_expr = new TypeExpression (mtype, Location);
                        generic_args = new TypeArguments (iterator_type_expr);
 
-                       ArrayList list = new ArrayList ();
+                       var list = new List<FullNamedExpression> ();
                        if (Iterator.IsEnumerable) {
-                               enumerable_type = new TypeExpression (
-                                       TypeManager.ienumerable_type, Location);
+                               enumerable_type = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
                                list.Add (enumerable_type);
 
-                               if (TypeManager.generic_ienumerable_type != null) {
-                                       generic_enumerable_type = new GenericTypeExpr (
-                                               TypeManager.generic_ienumerable_type,
-                                               generic_args, Location);
+                               if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
+                                       generic_enumerable_type = new GenericTypeExpr (Module.PredefinedTypes.IEnumerableGeneric.TypeSpec, generic_args, Location);
                                        list.Add (generic_enumerable_type);
                                }
                        }
 
-                       enumerator_type = new TypeExpression (
-                               TypeManager.ienumerator_type, Location);
+                       enumerator_type = new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location);
                        list.Add (enumerator_type);
 
-                       list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
+                       list.Add (new TypeExpression (Compiler.BuiltinTypes.IDisposable, Location));
 
-                       if (TypeManager.generic_ienumerator_type != null) {
-                               generic_enumerator_type = new GenericTypeExpr (
-                                       TypeManager.generic_ienumerator_type,
-                                       generic_args, Location);
+                       var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
+                       if (ienumerator_generic.Define ()) {
+                               generic_enumerator_type = new GenericTypeExpr (ienumerator_generic.TypeSpec, generic_args, Location);
                                list.Add (generic_enumerator_type);
                        }
 
@@ -463,14 +440,8 @@ namespace Mono.CSharp {
                        return base.ResolveBaseTypes (out base_class);
                }
 
-               protected override string GetVariableMangledName (LocalInfo local_info)
+               protected override bool DoDefineMembers ()
                {
-                       return "<" + local_info.Name + ">__" + local_name_idx++.ToString ();
-               }
-
-               public void DefineIteratorMembers ()
-               {
-                       pc_field = AddCompilerGeneratedField ("$PC", TypeManager.system_int32_expr);
                        current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
 
                        if (hoisted_params != null) {
@@ -481,7 +452,7 @@ namespace Mono.CSharp {
                                //
                                // TODO: Do it for assigned/modified parameters only
                                //
-                               hoisted_params_copy = new ArrayList (hoisted_params.Count);
+                               hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
                                foreach (HoistedParameter hp in hoisted_params) {
                                        hoisted_params_copy.Add (new HoistedParameter (hp, "<$>" + hp.Field.Name));
                                }
@@ -501,7 +472,7 @@ namespace Mono.CSharp {
                                name = new MemberName (name, "GetEnumerator", Location);
 
                                if (generic_enumerator_type != null) {
-                                       Method get_enumerator = new IteratorMethod (this, enumerator_type, 0, name);
+                                       Method get_enumerator = new StateMachineMethod (this, null, enumerator_type, 0, name);
 
                                        name = new MemberName (name.Left.Left, "Generic", Location);
                                        name = new MemberName (name, "IEnumerable", generic_args, Location);
@@ -520,12 +491,8 @@ namespace Mono.CSharp {
                                        AddMethod (new GetEnumeratorMethod (this, enumerator_type, name));
                                }
                        }
-               }
 
-               protected override void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
-               {
-                       base.EmitHoistedParameters (ec, hoisted);
-                       base.EmitHoistedParameters (ec, hoisted_params_copy);
+                       return base.DoDefineMembers ();
                }
 
                void Define_Current (bool is_generic)
@@ -541,260 +508,365 @@ namespace Mono.CSharp {
                                type = iterator_type_expr;
                        } else {
                                name = new MemberName (name, "IEnumerator");
-                               type = TypeManager.system_object_expr;
+                               type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
                        }
 
                        name = new MemberName (name, "Current", Location);
 
-                       ToplevelBlock get_block = new ToplevelBlock (Location);
+                       ToplevelBlock get_block = new ToplevelBlock (Compiler, Location);
                        get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
                                
-                       Accessor getter = new Accessor (get_block, 0, null, null, Location);
+                       Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN, name, null);
+                       current.Get = new Property.GetMethod (current, 0, null, Location);
+                       current.Get.Block = get_block;
 
-                       Property current = new Property (
-                               this, type, Modifiers.DEBUGGER_HIDDEN, name, null, getter, null, false);
                        AddProperty (current);
                }
 
                void Define_Reset ()
                {
                        Method reset = new Method (
-                               this, null, TypeManager.system_void_expr,
+                               this, null, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
                                Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
                                new MemberName ("Reset", Location),
                                ParametersCompiled.EmptyReadOnlyParameters, null);
                        AddMethod (reset);
 
-                       reset.Block = new ToplevelBlock (Location);
+                       reset.Block = new ToplevelBlock (Compiler, Location);
 
-                       Type ex_type = TypeManager.CoreLookupType ("System", "NotSupportedException", Kind.Class, true);
+                       TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
                        if (ex_type == null)
                                return;
 
                        reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
                }
+
+               protected override void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
+               {
+                       base.EmitHoistedParameters (ec, hoisted);
+                       base.EmitHoistedParameters (ec, hoisted_params_copy);
+               }
        }
 
-       //
-       // Iterators are implemented as hidden anonymous block
-       //
-       public class Iterator : AnonymousExpression {
-               public readonly IMethodData OriginalMethod;
-               AnonymousMethodMethod method;
+       public class StateMachineMethod : Method
+       {
+               readonly StateMachineInitializer expr;
+
+               public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
+                       : base (host, null, returnType, mod | Modifiers.COMPILER_GENERATED,
+                         name, ParametersCompiled.EmptyReadOnlyParameters, null)
+               {
+                       this.expr = expr;
+                       Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
+               }
+
+               public override EmitContext CreateEmitContext (ILGenerator ig)
+               {
+                       EmitContext ec = new EmitContext (this, ig, MemberType);
+                       ec.CurrentAnonymousMethod = expr;
+                       return ec;
+               }
+       }
+
+       public abstract class StateMachineInitializer : AnonymousExpression
+       {
+               sealed class MoveNextBodyStatement : Statement
+               {
+                       readonly StateMachineInitializer state_machine;
+
+                       public MoveNextBodyStatement (StateMachineInitializer stateMachine)
+                       {
+                               this.state_machine = stateMachine;
+                               this.loc = stateMachine.Location;
+                       }
+
+                       protected override void CloneTo (CloneContext clonectx, Statement target)
+                       {
+                               throw new NotSupportedException ();
+                       }
+
+                       public override bool Resolve (BlockContext ec)
+                       {
+                               return true;
+                       }
+
+                       protected override void DoEmit (EmitContext ec)
+                       {
+                               state_machine.EmitMoveNext (ec);
+                       }
+               }
+
                public readonly TypeContainer Host;
-               public readonly bool IsEnumerable;
+               protected StateMachine storey;
 
                //
-               // The state as we generate the iterator
+               // The state as we generate the machine
                //
-               Label move_next_ok, move_next_error;
-               LocalBuilder skip_finally, current_pc;
+               Label move_next_ok;
+               protected Label move_next_error;
+               protected LocalBuilder skip_finally, current_pc;
+               List<ResumableStatement> resume_points;
 
-               public LocalBuilder SkipFinally {
-                       get { return skip_finally; }
+               protected StateMachineInitializer (ParametersBlock block, TypeContainer host, TypeSpec returnType)
+                       : base (block, returnType, block.StartLocation)
+               {
+                       this.Host = host;
                }
 
-               public LocalBuilder CurrentPC {
-                       get { return current_pc; }
+               public override AnonymousMethodStorey Storey {
+                       get {
+                               return storey;
+                       }
                }
 
-               public Block Container {
-                       get { return OriginalMethod.Block; }
+               public int AddResumePoint (ResumableStatement stmt)
+               {
+                       if (resume_points == null)
+                               resume_points = new List<ResumableStatement> ();
+
+                       resume_points.Add (stmt);
+                       return resume_points.Count;
                }
 
-               public GenericMethod GenericMethod {
-                       get { return OriginalMethod.GenericMethod; }
+               public override Expression CreateExpressionTree (ResolveContext ec)
+               {
+                       throw new NotSupportedException ("ET");
                }
 
-               public readonly Type OriginalIteratorType;
+               protected override Expression DoResolve (ResolveContext ec)
+               {
+                       storey = (StateMachine) block.TopBlock.AnonymousMethodStorey;
+
+                       BlockContext ctx = new BlockContext (ec, block, ReturnType);
+                       ctx.CurrentAnonymousMethod = this;
 
-               readonly IteratorStorey IteratorHost;
+                       ctx.StartFlowBranching (this, ec.CurrentBranching);
+                       Block.Resolve (ctx);
+                       ctx.EndFlowBranching ();
 
-               public enum State {
-                       Running = -3, // Used only in CurrentPC, never stored into $PC
-                       Uninitialized = -2,
-                       After = -1,
-                       Start = 0
+                       var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
+                       move_next.Block.AddStatement (new MoveNextBodyStatement (this));
+                       storey.AddEntryMethod (move_next);
+
+                       eclass = ExprClass.Value;
+                       return this;
                }
 
-               public void EmitYieldBreak (ILGenerator ig, bool unwind_protect)
+               public override void Emit (EmitContext ec)
                {
-                       ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
+                       //
+                       // Load Iterator storey instance
+                       //
+                       storey.Instance.Emit (ec);
                }
 
-               void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
+               public void EmitDispose (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
+                       Label end = ec.DefineLabel ();
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
+                       Label[] labels = null;
+                       int n_resume_points = resume_points == null ? 0 : resume_points.Count;
+                       for (int i = 0; i < n_resume_points; ++i) {
+                               ResumableStatement s = resume_points[i];
+                               Label ret = s.PrepareForDispose (ec, end);
+                               if (ret.Equals (end) && labels == null)
+                                       continue;
+                               if (labels == null) {
+                                       labels = new Label[resume_points.Count + 1];
+                                       for (int j = 0; j <= i; ++j)
+                                               labels[j] = end;
+                               }
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
+                               labels[i + 1] = ret;
+                       }
+
+                       if (labels != null) {
+                               current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
+                               ec.Emit (OpCodes.Ldarg_0);
+                               ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
+                               ec.Emit (OpCodes.Stloc, current_pc);
+                       }
+
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt (1);
+                       ec.Emit (OpCodes.Stfld, storey.DisposingField.Spec);
+
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt ((int) IteratorStorey.State.After);
+                       ec.Emit (OpCodes.Stfld, storey.PC.Spec);
+
+                       if (labels != null) {
+                               //SymbolWriter.StartIteratorDispatcher (ec.ig);
+                               ec.Emit (OpCodes.Ldloc, current_pc);
+                               ec.Emit (OpCodes.Switch, labels);
+                               //SymbolWriter.EndIteratorDispatcher (ec.ig);
+
+                               foreach (ResumableStatement s in resume_points)
+                                       s.EmitForDispose (ec, current_pc, end, true);
+                       }
+
+                       ec.MarkLabel (end);
+               }
+
+               void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
+               {
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
+
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt ((int) IteratorStorey.State.After);
+                       ec.Emit (OpCodes.Stfld, storey.PC.Spec);
 
                        // We only care if the PC is zero (start executing) or non-zero (don't do anything)
-                       ig.Emit (OpCodes.Brtrue, move_next_error);
+                       ec.Emit (OpCodes.Brtrue, move_next_error);
 
-                       SymbolWriter.StartIteratorBody (ec.ig);
+                       SymbolWriter.StartIteratorBody (ec);
                        original_block.Emit (ec);
-                       SymbolWriter.EndIteratorBody (ec.ig);
+                       SymbolWriter.EndIteratorBody (ec);
 
-                       ig.MarkLabel (move_next_error);
-                       ig.Emit (OpCodes.Ldc_I4_0);
-                       ig.Emit (OpCodes.Ret);
+                       ec.MarkLabel (move_next_error);
+
+                       if (ReturnType.Kind != MemberKind.Void)
+                               ec.EmitInt (0);
+                       ec.Emit (OpCodes.Ret);
                }
 
-               internal void EmitMoveNext (EmitContext ec, Block original_block)
+               void EmitMoveNext (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       move_next_ok = ig.DefineLabel ();
-                       move_next_error = ig.DefineLabel ();
+                       move_next_ok = ec.DefineLabel ();
+                       move_next_error = ec.DefineLabel ();
 
                        if (resume_points == null) {
-                               EmitMoveNext_NoResumePoints (ec, original_block);
+                               EmitMoveNext_NoResumePoints (ec, block);
                                return;
                        }
 
-                       current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
-                       ig.Emit (OpCodes.Ldarg_0);
-                       ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
-                       ig.Emit (OpCodes.Stloc, current_pc);
+                       current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
+                       ec.Emit (OpCodes.Stloc, current_pc);
 
                        // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt ((int) IteratorStorey.State.After);
+                       ec.Emit (OpCodes.Stfld, storey.PC.Spec);
 
-                       Label [] labels = new Label [1 + resume_points.Count];
-                       labels [0] = ig.DefineLabel ();
+                       Label[] labels = new Label[1 + resume_points.Count];
+                       labels[0] = ec.DefineLabel ();
 
                        bool need_skip_finally = false;
                        for (int i = 0; i < resume_points.Count; ++i) {
-                               ResumableStatement s = (ResumableStatement) resume_points [i];
+                               ResumableStatement s = resume_points[i];
                                need_skip_finally |= s is ExceptionStatement;
-                               labels [i+1] = s.PrepareForEmit (ec);
+                               labels[i + 1] = s.PrepareForEmit (ec);
                        }
 
                        if (need_skip_finally) {
-                               skip_finally = ec.GetTemporaryLocal (TypeManager.bool_type);
-                               ig.Emit (OpCodes.Ldc_I4_0);
-                               ig.Emit (OpCodes.Stloc, skip_finally);
+                               skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
+                               ec.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Stloc, skip_finally);
                        }
 
-                       SymbolWriter.StartIteratorDispatcher (ec.ig);
-                       ig.Emit (OpCodes.Ldloc, current_pc);
-                       ig.Emit (OpCodes.Switch, labels);
+                       SymbolWriter.StartIteratorDispatcher (ec);
+                       ec.Emit (OpCodes.Ldloc, current_pc);
+                       ec.Emit (OpCodes.Switch, labels);
 
-                       ig.Emit (OpCodes.Br, move_next_error);
-                       SymbolWriter.EndIteratorDispatcher (ec.ig);
+                       ec.Emit (OpCodes.Br, move_next_error);
+                       SymbolWriter.EndIteratorDispatcher (ec);
 
-                       ig.MarkLabel (labels [0]);
+                       ec.MarkLabel (labels[0]);
 
-                       SymbolWriter.StartIteratorBody (ec.ig);
-                       original_block.Emit (ec);
-                       SymbolWriter.EndIteratorBody (ec.ig);
+                       SymbolWriter.StartIteratorBody (ec);
+                       block.Emit (ec);
+                       SymbolWriter.EndIteratorBody (ec);
+
+                       SymbolWriter.StartIteratorDispatcher (ec);
+
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt ((int) IteratorStorey.State.After);
+                       ec.Emit (OpCodes.Stfld, storey.PC.Spec);
 
-                       SymbolWriter.StartIteratorDispatcher (ec.ig);
+                       ec.MarkLabel (move_next_error);
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
+                       if (ReturnType.Kind != MemberKind.Void)
+                               ec.EmitInt (0);
+                       ec.Emit (OpCodes.Ret);
 
-                       ig.MarkLabel (move_next_error);
-                       ig.Emit (OpCodes.Ldc_I4_0);
-                       ig.Emit (OpCodes.Ret);
+                       ec.MarkLabel (move_next_ok);
 
-                       ig.MarkLabel (move_next_ok);
-                       ig.Emit (OpCodes.Ldc_I4_1);
-                       ig.Emit (OpCodes.Ret);
+                       if (ReturnType.Kind != MemberKind.Void)
+                               ec.EmitInt (1);
+                       ec.Emit (OpCodes.Ret);
 
-                       SymbolWriter.EndIteratorDispatcher (ec.ig);
+                       SymbolWriter.EndIteratorDispatcher (ec);
                }
 
-               public void EmitDispose (EmitContext ec)
+               //
+               // Called back from YieldStatement
+               //
+               public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
                {
-                       ILGenerator ig = ec.ig;
-
-                       Label end = ig.DefineLabel ();
+                       //
+                       // Guard against being disposed meantime
+                       //
+                       Label disposed = ec.DefineLabel ();
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.Emit (OpCodes.Ldfld, storey.DisposingField.Spec);
+                       ec.Emit (OpCodes.Brtrue_S, disposed);
 
-                       Label [] labels = null;
-                       int n_resume_points = resume_points == null ? 0 : resume_points.Count;
-                       for (int i = 0; i < n_resume_points; ++i) {
-                               ResumableStatement s = (ResumableStatement) resume_points [i];
-                               Label ret = s.PrepareForDispose (ec, end);
-                               if (ret.Equals (end) && labels == null)
-                                       continue;
-                               if (labels == null) {
-                                       labels = new Label [resume_points.Count + 1];
-                                       for (int j = 0; j <= i; ++j)
-                                               labels [j] = end;
-                               }
-                               labels [i+1] = ret;
-                       }
+                       //
+                       // store resume program-counter
+                       //
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt (resume_pc);
+                       ec.Emit (OpCodes.Stfld, storey.PC.Spec);
+                       ec.MarkLabel (disposed);
 
-                       if (labels != null) {
-                               current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
-                               ig.Emit (OpCodes.Ldarg_0);
-                               ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
-                               ig.Emit (OpCodes.Stloc, current_pc);
+                       // mark finally blocks as disabled
+                       if (unwind_protect && skip_finally != null) {
+                               ec.EmitInt (1);
+                               ec.Emit (OpCodes.Stloc, skip_finally);
                        }
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
-
-                       if (labels != null) {
-                               //SymbolWriter.StartIteratorDispatcher (ec.ig);
-                               ig.Emit (OpCodes.Ldloc, current_pc);
-                               ig.Emit (OpCodes.Switch, labels);
-                               //SymbolWriter.EndIteratorDispatcher (ec.ig);
-
-                               foreach (ResumableStatement s in resume_points)
-                                       s.EmitForDispose (ec, this, end, true);
-                       }
+                       // Return ok
+                       ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
 
-                       ig.MarkLabel (end);
+                       ec.MarkLabel (resume_point);
                }
+       }
 
+       //
+       // Iterators are implemented as hidden anonymous block
+       //
+       public class Iterator : StateMachineInitializer
+       {
+               public readonly IMethodData OriginalMethod;
+               public readonly bool IsEnumerable;
+               public readonly TypeSpec OriginalIteratorType;
 
-               ArrayList resume_points;
-               public int AddResumePoint (ResumableStatement stmt)
+               public Iterator (ParametersBlock block, IMethodData method, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
+                       : base (block, host, host.Compiler.BuiltinTypes.Bool)
                {
-                       if (resume_points == null)
-                               resume_points = new ArrayList ();
-                       resume_points.Add (stmt);
-                       return resume_points.Count;
+                       this.OriginalMethod = method;
+                       this.OriginalIteratorType = iterator_type;
+                       this.IsEnumerable = is_enumerable;
+                       this.type = method.ReturnType;
                }
 
-               //
-               // Called back from Yield
-               //
-               public void MarkYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
-               {
-                       ILGenerator ig = ec.ig;
-
-                       // Store the new current
-                       ig.Emit (OpCodes.Ldarg_0);
-                       expr.Emit (ec);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.CurrentField.FieldBuilder);
-
-                       // store resume program-counter
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, resume_pc);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
+               public LocalBuilder SkipFinally {
+                       get { return skip_finally; }
+               }
 
-                       // mark finally blocks as disabled
-                       if (unwind_protect && skip_finally != null) {
-                               ig.Emit (OpCodes.Ldc_I4_1);
-                               ig.Emit (OpCodes.Stloc, skip_finally);
-                       }
+               public LocalBuilder CurrentPC {
+                   get { return current_pc; }
+               }
 
-                       // Return ok
-                       ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
+               public Block Container {
+                       get { return OriginalMethod.Block; }
+               }
 
-                       ig.MarkLabel (resume_point);
+               public GenericMethod GenericMethod {
+                       get { return OriginalMethod.GenericMethod; }
                }
 
                public override string ContainerType {
@@ -805,25 +877,9 @@ namespace Mono.CSharp {
                        get { return true; }
                }
 
-               public override AnonymousMethodStorey Storey {
-                       get { return IteratorHost; }
-               }
-
-               //
-               // Our constructor
-               //
-               private Iterator (IMethodData method, TypeContainer host, Type iterator_type, bool is_enumerable)
-                       : base (
-                               new ToplevelBlock (method.Block, ParametersCompiled.EmptyReadOnlyParameters, method.Block.StartLocation),
-                               TypeManager.bool_type,
-                               method.Location)
+               public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
                {
-                       this.OriginalMethod = method;
-                       this.OriginalIteratorType = iterator_type;
-                       this.IsEnumerable = is_enumerable;
-                       this.Host = host;
-
-                       IteratorHost = Block.ChangeToIterator (this, method.Block);
+                       ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
                }
 
                public override string GetSignatureForError ()
@@ -831,64 +887,55 @@ namespace Mono.CSharp {
                        return OriginalMethod.GetSignatureForError ();
                }
 
-               public override Expression DoResolve (EmitContext ec)
-               {
-                       method = new AnonymousMethodMethod (Storey,
-                               this, Storey, null, TypeManager.system_boolean_expr,
-                               Modifiers.PUBLIC, OriginalMethod.GetSignatureForError (),
-                               new MemberName ("MoveNext", Location),
-                               ParametersCompiled.EmptyReadOnlyParameters);
-
-                       if (!Compatible (ec))
-                               return null;
-
-                       IteratorHost.DefineIteratorMembers ();
-
-                       eclass = ExprClass.Value;
-                       type = ec.ReturnType;
-                       return this;
-               }
-
                public override void Emit (EmitContext ec)
                {
                        //
                        // Load Iterator storey instance
                        //
-                       method.Storey.Instance.Emit (ec);
+                       storey.Instance.Emit (ec);
 
                        //
                        // Initialize iterator PC when it's unitialized
                        //
                        if (IsEnumerable) {
-                               ILGenerator ig = ec.ig;
-                               ig.Emit (OpCodes.Dup);
-                               IntConstant.EmitInt (ig, (int)State.Uninitialized);
-
-                               FieldInfo field = IteratorHost.PC.FieldBuilder;
-#if GMCS_SOURCE
-                               if (Storey.MemberName.IsGeneric)
-                                       field = TypeBuilder.GetField (Storey.Instance.Type, field);
-#endif
-                               ig.Emit (OpCodes.Stfld, field);
+                               ec.Emit (OpCodes.Dup);
+                               ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
+
+                               var field = storey.PC.Spec;
+                               if (storey.MemberName.IsGeneric) {
+                                       field = MemberCache.GetMember (Storey.Instance.Type, field);
+                               }
+
+                               ec.Emit (OpCodes.Stfld, field);
                        }
                }
 
-               public override Expression CreateExpressionTree (EmitContext ec)
+               public override void EmitStatement (EmitContext ec)
                {
-                       throw new NotSupportedException ("ET");
+                       throw new NotImplementedException ();
                }
 
-               public static void CreateIterator (IMethodData method, TypeContainer parent, int modifiers)
+               public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
+               {
+                       // Store the new value into current
+                       var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
+                       fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
+                       fe.EmitAssign (ec, expr, false, false);
+
+                       base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
+               }
+
+               public static void CreateIterator (IMethodData method, TypeContainer parent, Modifiers modifiers)
                {
                        bool is_enumerable;
-                       Type iterator_type;
+                       TypeSpec iterator_type;
 
-                       Type ret = method.ReturnType;
+                       TypeSpec ret = method.ReturnType;
                        if (ret == null)
                                return;
 
-                       if (!CheckType (ret, out iterator_type, out is_enumerable)) {
-                               Report.Error (1624, method.Location,
+                       if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
+                               parent.Compiler.Report.Error (1624, method.Location,
                                              "The body of `{0}' cannot be an iterator block " +
                                              "because `{1}' is not an iterator interface type",
                                              method.GetSignatureForError (),
@@ -901,66 +948,63 @@ namespace Mono.CSharp {
                                Parameter p = parameters [i];
                                Parameter.Modifier mod = p.ModFlags;
                                if ((mod & Parameter.Modifier.ISBYREF) != 0) {
-                                       Report.Error (1623, p.Location,
+                                       parent.Compiler.Report.Error (1623, p.Location,
                                                "Iterators cannot have ref or out parameters");
                                        return;
                                }
 
                                if (p is ArglistParameter) {
-                                       Report.Error (1636, method.Location,
+                                       parent.Compiler.Report.Error (1636, method.Location,
                                                "__arglist is not allowed in parameter list of iterators");
                                        return;
                                }
 
                                if (parameters.Types [i].IsPointer) {
-                                       Report.Error (1637, p.Location,
-                                                         "Iterators cannot have unsafe parameters or " +
-                                                         "yield types");
+                                       parent.Compiler.Report.Error (1637, p.Location,
+                                               "Iterators cannot have unsafe parameters or yield types");
                                        return;
                                }
                        }
 
                        if ((modifiers & Modifiers.UNSAFE) != 0) {
-                               Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
-                               return;
+                               parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
                        }
 
-                       Iterator iter = new Iterator (method, parent, iterator_type, is_enumerable);
-                       iter.Storey.DefineType ();
+                       method.Block.WrapIntoIterator (method, parent, iterator_type, is_enumerable);
                }
 
-               static bool CheckType (Type ret, out Type original_iterator_type, out bool is_enumerable)
+               static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
                {
                        original_iterator_type = null;
                        is_enumerable = false;
 
-                       if (ret == TypeManager.ienumerable_type) {
-                               original_iterator_type = TypeManager.object_type;
+                       if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
+                               original_iterator_type = parent.Compiler.BuiltinTypes.Object;
                                is_enumerable = true;
                                return true;
                        }
-                       if (ret == TypeManager.ienumerator_type) {
-                               original_iterator_type = TypeManager.object_type;
+                       if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
+                               original_iterator_type = parent.Compiler.BuiltinTypes.Object;
                                is_enumerable = false;
                                return true;
                        }
 
-                       if (!TypeManager.IsGenericType (ret))
+                       InflatedTypeSpec inflated = ret as InflatedTypeSpec;
+                       if (inflated == null)
                                return false;
 
-                       Type[] args = TypeManager.GetTypeArguments (ret);
-                       if (args.Length != 1)
-                               return false;
+                       var member_definition = inflated.MemberDefinition;
+                       PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
 
-                       Type gt = TypeManager.DropGenericTypeArguments (ret);
-                       if (gt == TypeManager.generic_ienumerable_type) {
-                               original_iterator_type = TypeManager.TypeToCoreType (args [0]);
+                       if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
+                               original_iterator_type = inflated.TypeArguments[0];
                                is_enumerable = true;
                                return true;
                        }
-                       
-                       if (gt == TypeManager.generic_ienumerator_type) {
-                               original_iterator_type = TypeManager.TypeToCoreType (args [0]);
+
+                       ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
+                       if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
+                               original_iterator_type = inflated.TypeArguments[0];
                                is_enumerable = false;
                                return true;
                        }