2006-06-19 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / gmcs / generic.cs
index 0fc30edb60caf3fa1fc55aa95f9b25aa3587f075..5938b7078bfb9740af018f58828947efbaabf358 100644 (file)
@@ -165,12 +165,13 @@ namespace Mono.CSharp {
                Type[] iface_constraint_types;
                Type effective_base_type;
                bool resolved;
+               bool resolved_types;
 
                /// <summary>
                ///   Resolve the constraints - but only resolve things into Expression's, not
                ///   into actual types.
                /// </summary>
-               public bool Resolve (EmitContext ec)
+               public bool Resolve (IResolveContext ec)
                {
                        if (resolved)
                                return true;
@@ -216,13 +217,13 @@ namespace Mono.CSharp {
                                }
 
                                int errors = Report.Errors;
-                               FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
+                               FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
 
                                if (fn == null) {
                                        if (errors != Report.Errors)
                                                return false;
 
-                                       Report.Error (246, loc, "Cannot find type '{0}'", obj);
+                                       Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
                                        return false;
                                }
 
@@ -234,9 +235,9 @@ namespace Mono.CSharp {
 
                                        expr = cexpr;
                                } else
-                                       expr = fn.ResolveAsTypeTerminal (ec);
+                                       expr = fn.ResolveAsTypeTerminal (ec, false);
 
-                               if (expr == null)
+                               if ((expr == null) || (expr.Type == null))
                                        return false;
 
                                TypeParameterExpr texpr = expr as TypeParameterExpr;
@@ -261,6 +262,71 @@ namespace Mono.CSharp {
                                num_constraints++;
                        }
 
+                       ArrayList list = new ArrayList ();
+                       foreach (TypeExpr iface_constraint in iface_constraints) {
+                               foreach (Type type in list) {
+                                       if (!type.Equals (iface_constraint.Type))
+                                               continue;
+
+                                       Report.Error (405, loc,
+                                                     "Duplicate constraint `{0}' for type " +
+                                                     "parameter `{1}'.", iface_constraint.GetSignatureForError (),
+                                                     name);
+                                       return false;
+                               }
+
+                               list.Add (iface_constraint.Type);
+                       }
+
+                       foreach (TypeParameterExpr expr in type_param_constraints) {
+                               foreach (Type type in list) {
+                                       if (!type.Equals (expr.Type))
+                                               continue;
+
+                                       Report.Error (405, loc,
+                                                     "Duplicate constraint `{0}' for type " +
+                                                     "parameter `{1}'.", expr.GetSignatureForError (), name);
+                                       return false;
+                               }
+
+                               list.Add (expr.Type);
+                       }
+
+                       iface_constraint_types = new Type [list.Count];
+                       list.CopyTo (iface_constraint_types, 0);
+
+                       if (class_constraint != null) {
+                               class_constraint_type = class_constraint.Type;
+                               if (class_constraint_type == null)
+                                       return false;
+
+                               if (class_constraint_type.IsSealed) {
+                                       Report.Error (701, loc,
+                                                     "`{0}' is not a valid bound.  Bounds " +
+                                                     "must be interfaces or non sealed " +
+                                                     "classes", TypeManager.CSharpName (class_constraint_type));
+                                       return false;
+                               }
+
+                               if ((class_constraint_type == TypeManager.array_type) ||
+                                   (class_constraint_type == TypeManager.delegate_type) ||
+                                   (class_constraint_type == TypeManager.enum_type) ||
+                                   (class_constraint_type == TypeManager.value_type) ||
+                                   (class_constraint_type == TypeManager.object_type)) {
+                                       Report.Error (702, loc,
+                                                     "Bound cannot be special class `{0}'",
+                                                     TypeManager.CSharpName (class_constraint_type));
+                                       return false;
+                               }
+                       }
+
+                       if (class_constraint_type != null)
+                               effective_base_type = class_constraint_type;
+                       else if (HasValueTypeConstraint)
+                               effective_base_type = TypeManager.value_type;
+                       else
+                               effective_base_type = TypeManager.object_type;
+
                        resolved = true;
                        return true;
                }
@@ -302,11 +368,13 @@ namespace Mono.CSharp {
                /// <summary>
                ///   Resolve the constraints into actual types.
                /// </summary>
-               public bool ResolveTypes (EmitContext ec)
+               public bool ResolveTypes (IResolveContext ec)
                {
-                       if (effective_base_type != null)
+                       if (resolved_types)
                                return true;
 
+                       resolved_types = true;
+
                        foreach (object obj in constraints) {
                                ConstructedType cexpr = obj as ConstructedType;
                                if (cexpr == null)
@@ -322,95 +390,20 @@ namespace Mono.CSharp {
                                        return false;
                        }
 
-                       ArrayList list = new ArrayList ();
-
-                       foreach (TypeExpr iface_constraint in iface_constraints) {
-                               foreach (Type type in list) {
-                                       if (!type.Equals (iface_constraint.Type))
-                                               continue;
-
-                                       Report.Error (405, loc,
-                                                     "Duplicate constraint `{0}' for type " +
-                                                     "parameter `{1}'.", iface_constraint.Type,
-                                                     name);
-                                       return false;
-                               }
-
-                               TypeExpr te = iface_constraint.ResolveAsTypeTerminal (ec);
-                               if (te == null)
-                                       return false;
-
-                               list.Add (te.Type);
-                       }
-
-                       foreach (TypeParameterExpr expr in type_param_constraints) {
-                               foreach (Type type in list) {
-                                       if (!type.Equals (expr.Type))
-                                               continue;
-
-                                       Report.Error (405, loc,
-                                                     "Duplicate constraint `{0}' for type " +
-                                                     "parameter `{1}'.", expr.Type, name);
+                       for (int i = 0; i < iface_constraints.Count; ++i) {
+                               TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
+                               iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
+                               if (iface_constraint == null)
                                        return false;
-                               }
-
-                               list.Add (expr.Type);
-                       }
-
-                       ArrayList new_list = new ArrayList ();
-                       foreach (Type iface in list) {
-                               if (new_list.Contains (iface))
-                                       continue;
-
-                               new_list.Add (iface);
-
-                               Type [] implementing = TypeManager.GetInterfaces (iface);
-                       
-                               foreach (Type imp in implementing) {
-                                       if (!new_list.Contains (imp))
-                                               new_list.Add (imp);
-                               }
+                               iface_constraints [i] = iface_constraint;
                        }
 
-                       iface_constraint_types = new Type [new_list.Count];
-                       new_list.CopyTo (iface_constraint_types, 0);
-
                        if (class_constraint != null) {
-                               TypeExpr te = class_constraint.ResolveAsTypeTerminal (ec);
-                               if (te == null)
+                               class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
+                               if (class_constraint == null)
                                        return false;
-
-                               class_constraint_type = te.Type;
-                               if (class_constraint_type == null)
-                                       return false;
-
-                               if (class_constraint_type.IsSealed) {
-                                       Report.Error (701, loc,
-                                                     "`{0}' is not a valid bound.  Bounds " +
-                                                     "must be interfaces or non sealed " +
-                                                     "classes", class_constraint_type);
-                                       return false;
-                               }
-
-                               if ((class_constraint_type == TypeManager.array_type) ||
-                                   (class_constraint_type == TypeManager.delegate_type) ||
-                                   (class_constraint_type == TypeManager.enum_type) ||
-                                   (class_constraint_type == TypeManager.value_type) ||
-                                   (class_constraint_type == TypeManager.object_type)) {
-                                       Report.Error (702, loc,
-                                                     "Bound cannot be special class `{0}'",
-                                                     class_constraint_type);
-                                       return false;
-                               }
                        }
 
-                       if (class_constraint_type != null)
-                               effective_base_type = class_constraint_type;
-                       else if (HasValueTypeConstraint)
-                               effective_base_type = TypeManager.value_type;
-                       else
-                               effective_base_type = TypeManager.object_type;
-
                        return true;
                }
 
@@ -423,17 +416,17 @@ namespace Mono.CSharp {
                ///      where T : class
                ///      where U : T, struct
                /// </summary>
-               public bool CheckDependencies (EmitContext ec)
+               public bool CheckDependencies ()
                {
                        foreach (TypeParameterExpr expr in type_param_constraints) {
-                               if (!CheckDependencies (expr.TypeParameter, ec))
+                               if (!CheckDependencies (expr.TypeParameter))
                                        return false;
                        }
 
                        return true;
                }
 
-               bool CheckDependencies (TypeParameter tparam, EmitContext ec)
+               bool CheckDependencies (TypeParameter tparam)
                {
                        Constraints constraints = tparam.Constraints;
                        if (constraints == null)
@@ -442,7 +435,7 @@ namespace Mono.CSharp {
                        if (HasValueTypeConstraint && constraints.HasClassConstraint) {
                                Report.Error (455, loc, "Type parameter `{0}' inherits " +
                                              "conflicting constraints `{1}' and `{2}'",
-                                             name, constraints.ClassConstraint,
+                                             name, TypeManager.CSharpName (constraints.ClassConstraint),
                                              "System.ValueType");
                                return false;
                        }
@@ -453,12 +446,12 @@ namespace Mono.CSharp {
                                Type t2 = constraints.ClassConstraint;
                                TypeExpr e2 = constraints.class_constraint;
 
-                               if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
-                                   !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
+                               if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
+                                   !Convert.ImplicitReferenceConversionExists (e2, t1)) {
                                        Report.Error (455, loc,
                                                      "Type parameter `{0}' inherits " +
                                                      "conflicting constraints `{1}' and `{2}'",
-                                                     name, t1, t2);
+                                                     name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
                                        return false;
                                }
                        }
@@ -467,25 +460,13 @@ namespace Mono.CSharp {
                                return true;
 
                        foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
-                               if (!CheckDependencies (expr.TypeParameter, ec))
+                               if (!CheckDependencies (expr.TypeParameter))
                                        return false;
                        }
 
                        return true;
                }
 
-               /// <summary>
-               ///   Set the attributes on the GenericTypeParameterBuilder.
-               /// </summary>
-               /// <remarks>
-               ///   This is not done in Resolve() since Resolve() may be called before
-               ///   the GenericTypeParameterBuilder is created (partial generic classes).
-               /// </remarks>
-               public void Define (GenericTypeParameterBuilder type)
-               {
-                       type.SetGenericParameterAttributes (attrs);
-               }
-
                public override GenericParameterAttributes Attributes {
                        get { return attrs; }
                }
@@ -530,7 +511,7 @@ namespace Mono.CSharp {
                ///   method.  To do that, we're called on each of the implementing method's
                ///   type parameters.
                /// </summary>
-               public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
+               public bool CheckInterfaceMethod (GenericConstraints gc)
                {
                        if (gc.Attributes != attrs)
                                return false;
@@ -576,9 +557,9 @@ namespace Mono.CSharp {
                Location loc;
                GenericTypeParameterBuilder type;
 
-               public TypeParameter (TypeContainer parent, DeclSpace decl, string name,
-                                     Constraints constraints, Location loc)
-                       : base (parent, new MemberName (name, loc), null)
+               public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
+                                     Constraints constraints, Attributes attrs, Location loc)
+                       : base (parent, new MemberName (name, loc), attrs)
                {
                        this.name = name;
                        this.decl = decl;
@@ -619,6 +600,11 @@ namespace Mono.CSharp {
                        }
                }
 
+               // FIXME: This should be removed once we fix the handling of RootContext.Tree.Types
+               public override DeclSpace DeclContainer {
+                       get { return DeclSpace; }
+               }
+
                /// <summary>
                ///   This is the first method which is called during the resolving
                ///   process; we're called immediately after creating the type parameters
@@ -653,7 +639,7 @@ namespace Mono.CSharp {
                public bool Resolve (DeclSpace ds)
                {
                        if (constraints != null) {
-                               if (!constraints.Resolve (ds.EmitContext)) {
+                               if (!constraints.Resolve (ds)) {
                                        constraints = null;
                                        return false;
                                }
@@ -664,23 +650,6 @@ namespace Mono.CSharp {
 
                /// <summary>
                ///   This is the third method which is called during the resolving
-               ///   process.  We're called immediately after calling Resolve() on
-               ///   all of the current class'es type parameters.
-               ///
-               ///   All we do is setting the attributes on the GenericTypeParameterBuilder.
-               /// </summary>
-               /// <remarks>
-               ///   This is not done in Resolve() since Resolve() may be called before
-               ///   Define() for partial generic classes.
-               /// </remarks>
-               public void DefineConstraints ()
-               {
-                       if (constraints != null)
-                               constraints.Define (type);
-               }
-
-               /// <summary>
-               ///   This is the forth method which is called during the resolving
                ///   process.  We're called immediately after calling DefineConstraints()
                ///   on all of the current class'es type parameters.
                ///
@@ -689,7 +658,7 @@ namespace Mono.CSharp {
                ///   Note that we may have circular dependencies on type parameters - this
                ///   is why Resolve() and ResolveType() are separate.
                /// </summary>
-               public bool ResolveType (EmitContext ec)
+               public bool ResolveType (IResolveContext ec)
                {
                        if (constraints != null) {
                                if (!constraints.ResolveTypes (ec)) {
@@ -702,11 +671,11 @@ namespace Mono.CSharp {
                }
 
                /// <summary>
-               ///   This is the fith and last method which is called during the resolving
+               ///   This is the fourth and last method which is called during the resolving
                ///   process.  We're called after everything is fully resolved and actually
                ///   register the constraints with SRE and the TypeManager.
                /// </summary>
-               public bool DefineType (EmitContext ec)
+               public bool DefineType (IResolveContext ec)
                {
                        return DefineType (ec, null, null, false);
                }
@@ -719,7 +688,7 @@ namespace Mono.CSharp {
                ///   The `builder', `implementing' and `is_override' arguments are only
                ///   applicable to method type parameters.
                /// </summary>
-               public bool DefineType (EmitContext ec, MethodBuilder builder,
+               public bool DefineType (IResolveContext ec, MethodBuilder builder,
                                        MethodInfo implementing, bool is_override)
                {
                        if (!ResolveType (ec))
@@ -735,14 +704,11 @@ namespace Mono.CSharp {
                                        return false;
                                }
 
-                               MethodBase mb = implementing;
-                               if (mb.Mono_IsInflatedMethod)
-                                       mb = mb.GetGenericMethodDefinition ();
+                               MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
 
                                int pos = type.GenericParameterPosition;
-                               ParameterData pd = TypeManager.GetParameterData (mb);
-                               GenericConstraints temp_gc = pd.GenericConstraints (pos);
                                Type mparam = mb.GetGenericArguments () [pos];
+                               GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
 
                                if (temp_gc != null)
                                        gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
@@ -753,7 +719,7 @@ namespace Mono.CSharp {
                                if (constraints != null) {
                                        if (temp_gc == null)
                                                ok = false;
-                                       else if (!constraints.CheckInterfaceMethod (ec, gc))
+                                       else if (!constraints.CheckInterfaceMethod (gc))
                                                ok = false;
                                } else {
                                        if (!is_override && (temp_gc != null))
@@ -767,10 +733,10 @@ namespace Mono.CSharp {
                                                425, loc, "The constraints for type " +
                                                "parameter `{0}' of method `{1}' must match " +
                                                "the constraints for type parameter `{2}' " +
-                                               "of interface method `{3}'.  Consider using " +
+                                               "of interface method `{3}'. Consider using " +
                                                "an explicit interface implementation instead",
                                                Name, TypeManager.CSharpSignature (builder),
-                                               mparam, TypeManager.CSharpSignature (mb));
+                                               TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
                                        return false;
                                }
                        } else if (DeclSpace is Iterator) {
@@ -792,6 +758,7 @@ namespace Mono.CSharp {
                                type.SetBaseTypeConstraint (gc.ClassConstraint);
 
                        type.SetInterfaceConstraints (gc.InterfaceConstraints);
+                       type.SetGenericParameterAttributes (gc.Attributes);
                        TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
 
                        return true;
@@ -806,10 +773,10 @@ namespace Mono.CSharp {
                ///      where T : class
                ///      where U : T, struct
                /// </summary>
-               public bool CheckDependencies (EmitContext ec)
+               public bool CheckDependencies ()
                {
                        if (constraints != null)
-                               return constraints.CheckDependencies (ec);
+                               return constraints.CheckDependencies ();
 
                        return true;
                }
@@ -822,15 +789,12 @@ namespace Mono.CSharp {
                ///   check that they're the same.
                ///   con
                /// </summary>
-               public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
+               public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
                {
                        if (type == null)
                                throw new InvalidOperationException ();
 
-                       if (constraints == null) {
-                               new_constraints = constraints;
-                               return true;
-                       } else if (new_constraints == null)
+                       if (new_constraints == null)
                                return true;
 
                        if (!new_constraints.Resolve (ec))
@@ -838,7 +802,17 @@ namespace Mono.CSharp {
                        if (!new_constraints.ResolveTypes (ec))
                                return false;
 
-                       return constraints.CheckInterfaceMethod (ec, new_constraints);
+                       if (constraints != null) 
+                               return constraints.CheckInterfaceMethod (new_constraints);
+
+                       constraints = new_constraints;
+                       return true;
+               }
+
+               public void EmitAttributes ()
+               {
+                       if (OptAttributes != null)
+                               OptAttributes.Emit ();
                }
 
                public override string DocCommentHeader {
@@ -859,17 +833,19 @@ namespace Mono.CSharp {
 
                public override void ApplyAttributeBuilder (Attribute a,
                                                            CustomAttributeBuilder cb)
-               { }
+               {
+                       type.SetCustomAttribute (cb);
+               }
 
                public override AttributeTargets AttributeTargets {
                        get {
-                               return (AttributeTargets) 0;
+                               return (AttributeTargets) AttributeTargets.GenericParameter;
                        }
                }
 
                public override string[] ValidAttributeTargets {
                        get {
-                               return new string [0];
+                               return new string [] { "type parameter" };
                        }
                }
 
@@ -906,8 +882,6 @@ namespace Mono.CSharp {
 
                        ArrayList members = new ArrayList ();
 
-                       GenericConstraints gc = (GenericConstraints) constraints;
-
                        if (gc.HasClassConstraint) {
                                MemberList list = TypeManager.FindMembers (
                                        gc.ClassConstraint, mt, bf, filter, criteria);
@@ -915,7 +889,8 @@ namespace Mono.CSharp {
                                members.AddRange (list);
                        }
 
-                       foreach (Type t in gc.InterfaceConstraints) {
+                       Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
+                       foreach (Type t in ifaces) {
                                MemberList list = TypeManager.FindMembers (
                                        t, mt, bf, filter, criteria);
 
@@ -941,6 +916,27 @@ namespace Mono.CSharp {
                        return "TypeParameter[" + name + "]";
                }
 
+               public static string GetSignatureForError (TypeParameter[] tp)
+               {
+                       if (tp == null || tp.Length == 0)
+                               return "";
+
+                       StringBuilder sb = new StringBuilder ("<");
+                       for (int i = 0; i < tp.Length; ++i) {
+                               if (i > 0)
+                                       sb.Append (",");
+                               sb.Append (tp[i].GetSignatureForError ());
+                       }
+                       sb.Append ('>');
+                       return sb.ToString ();
+               }
+
+               public void InflateConstraints (Type declaring)
+               {
+                       if (constraints != null)
+                               gc = new InflatedConstraints (constraints, declaring);
+               }
+
                protected class InflatedConstraints : GenericConstraints
                {
                        GenericConstraints gc;
@@ -993,9 +989,15 @@ namespace Mono.CSharp {
                                        return null;
                                if (t.IsGenericParameter)
                                        return dargs [t.GenericParameterPosition];
-                               if (t.IsGenericInstance) {
+                               if (t.IsGenericType) {
+                                       Type[] args = t.GetGenericArguments ();
+                                       Type[] inflated = new Type [args.Length];
+
+                                       for (int i = 0; i < args.Length; i++)
+                                               inflated [i] = inflate (args [i]);
+
                                        t = t.GetGenericTypeDefinition ();
-                                       t = t.MakeGenericType (dargs);
+                                       t = t.MakeGenericType (inflated);
                                }
 
                                return t;
@@ -1053,7 +1055,7 @@ namespace Mono.CSharp {
                        this.loc = loc;
                }
 
-               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
                {
                        type = type_parameter.Type;
 
@@ -1121,13 +1123,18 @@ namespace Mono.CSharp {
                ///   parser creates a `MemberName' with `TypeArguments' for both cases and
                ///   in case of a generic type definition, we call GetDeclarations().
                /// </summary>
-               public string[] GetDeclarations ()
+               public TypeParameterName[] GetDeclarations ()
                {
-                       string[] ret = new string [args.Count];
+                       TypeParameterName[] ret = new TypeParameterName [args.Count];
                        for (int i = 0; i < args.Count; i++) {
+                               TypeParameterName name = args [i] as TypeParameterName;
+                               if (name != null) {
+                                       ret [i] = name;
+                                       continue;
+                               }
                                SimpleName sn = args [i] as SimpleName;
                                if (sn != null) {
-                                       ret [i] = sn.Name;
+                                       ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
                                        continue;
                                }
 
@@ -1189,7 +1196,7 @@ namespace Mono.CSharp {
                /// <summary>
                ///   Resolve the type arguments.
                /// </summary>
-               public bool Resolve (EmitContext ec)
+               public bool Resolve (IResolveContext ec)
                {
                        int count = args.Count;
                        bool ok = true;
@@ -1197,7 +1204,7 @@ namespace Mono.CSharp {
                        atypes = new Type [count];
 
                        for (int i = 0; i < count; i++){
-                               TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
+                               TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
                                if (te == null) {
                                        ok = false;
                                        continue;
@@ -1209,6 +1216,10 @@ namespace Mono.CSharp {
                                        Report.Error (306, Location, "The type `{0}' may not be used " +
                                                      "as a type argument.", TypeManager.CSharpName (te.Type));
                                        return false;
+                               } else if (te.Type == TypeManager.void_type) {
+                                       Report.Error (1547, Location,
+                                                     "Keyword `void' cannot be used in this context");
+                                       return false;
                                }
 
                                atypes [i] = te.Type;
@@ -1217,6 +1228,23 @@ namespace Mono.CSharp {
                }
        }
 
+       public class TypeParameterName : SimpleName
+       {
+               Attributes attributes;
+
+               public TypeParameterName (string name, Attributes attrs, Location loc)
+                       : base (name, loc)
+               {
+                       attributes = attrs;
+               }
+
+               public Attributes OptAttributes {
+                       get {
+                               return attributes;
+                       }
+               }
+       }
+
        /// <summary>
        ///   An instantiation of a generic type.
        /// </summary>  
@@ -1289,49 +1317,177 @@ namespace Mono.CSharp {
                        get { return args; }
                }
 
-               protected string DeclarationName {
-                       get {
-                               StringBuilder sb = new StringBuilder ();
-                               sb.Append (gt.FullName);
-                               sb.Append ("<");
-                               for (int i = 0; i < gen_params.Length; i++) {
-                                       if (i > 0)
-                                               sb.Append (",");
-                                       sb.Append (gen_params [i]);
-                               }
-                               sb.Append (">");
-                               return sb.ToString ();
+               public override string GetSignatureForError ()
+               {
+                       return TypeManager.CSharpName (gt);
+               }
+
+               protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
+               {
+                       if (!ResolveConstructedType (ec))
+                               return null;
+
+                       return this;
+               }
+
+               /// <summary>
+               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
+               ///   after fully resolving the constructed type.
+               /// </summary>
+               public bool CheckConstraints (IResolveContext ec)
+               {
+                       return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
+               }
+
+               /// <summary>
+               ///   Resolve the constructed type, but don't check the constraints.
+               /// </summary>
+               public bool ResolveConstructedType (IResolveContext ec)
+               {
+                       if (type != null)
+                               return true;
+                       // If we already know the fully resolved generic type.
+                       if (gt != null)
+                               return DoResolveType (ec);
+
+                       int num_args;
+                       Type t = name.Type;
+
+                       if (t == null) {
+                               Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
+                               return false;
                        }
+
+                       num_args = TypeManager.GetNumberOfTypeArguments (t);
+                       if (num_args == 0) {
+                               Report.Error (308, loc,
+                                             "The non-generic type `{0}' cannot " +
+                                             "be used with type arguments.",
+                                             TypeManager.CSharpName (t));
+                               return false;
+                       }
+
+                       gt = t.GetGenericTypeDefinition ();
+                       return DoResolveType (ec);
                }
 
-               protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
-                                               Type ctype)
+               bool DoResolveType (IResolveContext ec)
                {
-                       if (TypeManager.HasGenericArguments (ctype)) {
-                               Type[] types = TypeManager.GetTypeArguments (ctype);
+                       //
+                       // Resolve the arguments.
+                       //
+                       if (args.Resolve (ec) == false)
+                               return false;
 
-                               TypeArguments new_args = new TypeArguments (loc);
+                       gen_params = gt.GetGenericArguments ();
+                       atypes = args.Arguments;
 
-                               for (int i = 0; i < types.Length; i++) {
-                                       Type t = types [i];
+                       if (atypes.Length != gen_params.Length) {
+                               Report.Error (305, loc,
+                                             "Using the generic type `{0}' " +
+                                             "requires {1} type arguments",
+                                             TypeManager.CSharpName (gt),
+                                             gen_params.Length.ToString ());
+                               return false;
+                       }
 
-                                       if (t.IsGenericParameter) {
-                                               int pos = t.GenericParameterPosition;
-                                               t = args.Arguments [pos];
-                                       }
-                                       new_args.Add (new TypeExpression (t, loc));
-                               }
+                       //
+                       // Now bind the parameters.
+                       //
+                       type = gt.MakeGenericType (atypes);
+                       return true;
+               }
 
-                               TypeExpr ct = new ConstructedType (ctype, new_args, loc);
-                               if (ct.ResolveAsTypeStep (ec) == null)
+               public Expression GetSimpleName (EmitContext ec)
+               {
+                       return this;
+               }
+
+               public override bool CheckAccessLevel (DeclSpace ds)
+               {
+                       return ds.CheckAccessLevel (gt);
+               }
+
+               public override bool AsAccessible (DeclSpace ds, int flags)
+               {
+                       return ds.AsAccessible (gt, flags);
+               }
+
+               public override bool IsClass {
+                       get { return gt.IsClass; }
+               }
+
+               public override bool IsValueType {
+                       get { return gt.IsValueType; }
+               }
+
+               public override bool IsInterface {
+                       get { return gt.IsInterface; }
+               }
+
+               public override bool IsSealed {
+                       get { return gt.IsSealed; }
+               }
+
+               public override bool Equals (object obj)
+               {
+                       ConstructedType cobj = obj as ConstructedType;
+                       if (cobj == null)
+                               return false;
+
+                       if ((type == null) || (cobj.type == null))
+                               return false;
+
+                       return type == cobj.type;
+               }
+
+               public override int GetHashCode ()
+               {
+                       return base.GetHashCode ();
+               }
+
+               public override string Name {
+                       get {
+                               return full_name;
+                       }
+               }
+
+
+               public override string FullName {
+                       get {
+                               return full_name;
+                       }
+               }
+       }
+
+       public abstract class ConstraintChecker
+       {
+               protected readonly Type[] gen_params;
+               protected readonly Type[] atypes;
+               protected readonly Location loc;
+
+               protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
+               {
+                       this.gen_params = gen_params;
+                       this.atypes = atypes;
+                       this.loc = loc;
+               }
+
+               /// <summary>
+               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
+               ///   after fully resolving the constructed type.
+               /// </summary>
+               public bool CheckConstraints (IResolveContext ec)
+               {
+                       for (int i = 0; i < gen_params.Length; i++) {
+                               if (!CheckConstraints (ec, i))
                                        return false;
-                               ctype = ct.Type;
                        }
 
-                       return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
+                       return true;
                }
 
-               protected bool CheckConstraints (EmitContext ec, int index)
+               protected bool CheckConstraints (IResolveContext ec, int index)
                {
                        Type atype = atypes [index];
                        Type ptype = gen_params [index];
@@ -1349,14 +1505,20 @@ namespace Mono.CSharp {
                        if (atype.IsGenericParameter) {
                                GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
                                if (agc != null) {
+                                       if (agc is Constraints)
+                                               ((Constraints) agc).Resolve (ec);
                                        is_class = agc.HasReferenceTypeConstraint;
                                        is_struct = agc.HasValueTypeConstraint;
                                } else {
                                        is_class = is_struct = false;
                                }
                        } else {
-                               is_class = atype.IsClass;
-                               is_struct = atype.IsValueType;
+#if MS_COMPATIBLE
+                               is_class = false;
+                               if (!atype.IsGenericType)
+#endif
+                               is_class = atype.IsClass || atype.IsInterface;
+                               is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
                        }
 
                        //
@@ -1367,14 +1529,18 @@ namespace Mono.CSharp {
                                              "a reference type in order to use it " +
                                              "as type parameter `{1}' in the " +
                                              "generic type or method `{2}'.",
-                                             atype, ptype, DeclarationName);
+                                             TypeManager.CSharpName (atype),
+                                             TypeManager.CSharpName (ptype),
+                                             GetSignatureForError ());
                                return false;
                        } else if (gc.HasValueTypeConstraint && !is_struct) {
-                               Report.Error (453, loc, "The type `{0}' must be " +
-                                             "a value type in order to use it " +
+                               Report.Error (453, loc, "The type `{0}' must be " +
+                                             "non-nullable value type in order to use it " +
                                              "as type parameter `{1}' in the " +
                                              "generic type or method `{2}'.",
-                                             atype, ptype, DeclarationName);
+                                             TypeManager.CSharpName (atype),
+                                             TypeManager.CSharpName (ptype),
+                                             GetSignatureForError ());
                                return false;
                        }
 
@@ -1382,33 +1548,17 @@ namespace Mono.CSharp {
                        // The class constraint comes next.
                        //
                        if (gc.HasClassConstraint) {
-                               if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
-                                       Report.Error (309, loc, "The type `{0}' must be " +
-                                                     "convertible to `{1}' in order to " +
-                                                     "use it as parameter `{2}' in the " +
-                                                     "generic type or method `{3}'",
-                                                     atype, gc.ClassConstraint, ptype, DeclarationName);
+                               if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
                                        return false;
-                               }
                        }
 
                        //
                        // Now, check the interface constraints.
                        //
-                       foreach (Type it in gc.InterfaceConstraints) {
-                               Type itype;
-                               if (it.IsGenericParameter)
-                                       itype = atypes [it.GenericParameterPosition];
-                               else
-                                       itype = it;
-
-                               if (!CheckConstraint (ec, ptype, aexpr, itype)) {
-                                       Report.Error (309, loc, "The type `{0}' must be " +
-                                                     "convertible to `{1}' in order to " +
-                                                     "use it as parameter `{2}' in the " +
-                                                     "generic type or method `{3}'",
-                                                     atype, itype, ptype, DeclarationName);
-                                       return false;
+                       if (gc.InterfaceConstraints != null) {
+                               foreach (Type it in gc.InterfaceConstraints) {
+                                       if (!CheckConstraint (ec, ptype, aexpr, it))
+                                               return false;
                                }
                        }
 
@@ -1422,193 +1572,177 @@ namespace Mono.CSharp {
                        if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
                                return true;
 
-                       if (HasDefaultConstructor (ec, atype))
+                       if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
                                return true;
 
+                       Report_SymbolRelatedToPreviousError ();
+                       Report.SymbolRelatedToPreviousError (atype);
                        Report.Error (310, loc, "The type `{0}' must have a public " +
                                      "parameterless constructor in order to use it " +
                                      "as parameter `{1}' in the generic type or " +
-                                     "method `{2}'", atype, ptype, DeclarationName);
+                                     "method `{2}'",
+                                     TypeManager.CSharpName (atype),
+                                     TypeManager.CSharpName (ptype),
+                                     GetSignatureForError ());
                        return false;
                }
 
-               bool HasDefaultConstructor (EmitContext ec, Type atype)
+               protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
+                                               Type ctype)
                {
-                       if (atype is TypeBuilder) {
-                               if (atype.IsAbstract)
-                                       return false;
-
-                               TypeContainer tc = TypeManager.LookupTypeContainer (atype);
-                               foreach (Constructor c in tc.InstanceConstructors) {
-                                       if ((c.ModFlags & Modifiers.PUBLIC) == 0)
-                                               continue;
-                                       if ((c.Parameters.FixedParameters != null) &&
-                                           (c.Parameters.FixedParameters.Length != 0))
-                                               continue;
-                                       if (c.Parameters.HasArglist ||
-                                           (c.Parameters.ArrayParameter != null))
-                                               continue;
+                       if (TypeManager.HasGenericArguments (ctype)) {
+                               Type[] types = TypeManager.GetTypeArguments (ctype);
 
-                                       return true;
-                               }
-                       }
+                               TypeArguments new_args = new TypeArguments (loc);
 
-                       MethodGroupExpr mg = Expression.MemberLookup (
-                               ec, atype, ".ctor", MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance |
-                               BindingFlags.DeclaredOnly, loc)
-                               as MethodGroupExpr;
+                               for (int i = 0; i < types.Length; i++) {
+                                       Type t = types [i];
 
-                       if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
-                               foreach (MethodBase mb in mg.Methods) {
-                                       ParameterData pd = TypeManager.GetParameterData (mb);
-                                       if (pd.Count == 0)
-                                               return true;
+                                       if (t.IsGenericParameter) {
+                                               int pos = t.GenericParameterPosition;
+                                               t = atypes [pos];
+                                       }
+                                       new_args.Add (new TypeExpression (t, loc));
                                }
-                       }
-
-                       return false;
-               }
 
-               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
-               {
-                       if (!ResolveConstructedType (ec))
-                               return null;
-
-                       return this;
-               }
-
-               /// <summary>
-               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
-               ///   after fully resolving the constructed type.
-               /// </summary>
-               public bool CheckConstraints (EmitContext ec)
-               {
-                       for (int i = 0; i < gen_params.Length; i++) {
-                               if (!CheckConstraints (ec, i))
+                               TypeExpr ct = new ConstructedType (ctype, new_args, loc);
+                               if (ct.ResolveAsTypeStep (ec, false) == null)
                                        return false;
+                               ctype = ct.Type;
+                       } else if (ctype.IsGenericParameter) {
+                               int pos = ctype.GenericParameterPosition;
+                               ctype = atypes [pos];
                        }
 
-                       return true;
-               }
-
-               /// <summary>
-               ///   Resolve the constructed type, but don't check the constraints.
-               /// </summary>
-               public bool ResolveConstructedType (EmitContext ec)
-               {
-                       if (type != null)
+                       if (Convert.ImplicitStandardConversionExists (expr, ctype))
                                return true;
-                       // If we already know the fully resolved generic type.
-                       if (gt != null)
-                               return DoResolveType (ec);
 
-                       int num_args;
-                       Type t = name.Type;
+                       Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
+                       return false;
+               }
 
-                       if (t == null) {
-                               Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
+               bool HasDefaultConstructor (Type containerType, Type atype)
+               {
+                       if (atype.IsAbstract)
                                return false;
-                       }
 
-                       num_args = TypeManager.GetNumberOfTypeArguments (t);
-                       if (num_args == 0) {
-                               Report.Error (308, loc,
-                                             "The non-generic type `{0}' cannot " +
-                                             "be used with type arguments.",
-                                             TypeManager.CSharpName (t));
-                               return false;
-                       }
+               again:
+                       atype = TypeManager.DropGenericTypeArguments (atype);
+                       if (atype is TypeBuilder) {
+                               TypeContainer tc = TypeManager.LookupTypeContainer (atype);
+                               if (tc.InstanceConstructors == null) {
+                                       atype = atype.BaseType;
+                                       goto again;
+                               }
+
+                               foreach (Constructor c in tc.InstanceConstructors) {
+                                       if ((c.ModFlags & Modifiers.PUBLIC) == 0)
+                                               continue;
+                                       if ((c.Parameters.FixedParameters != null) &&
+                                           (c.Parameters.FixedParameters.Length != 0))
+                                               continue;
+                                       if (c.Parameters.HasArglist || c.Parameters.HasParams)
+                                               continue;
 
-                       gt = t.GetGenericTypeDefinition ();
-                       return DoResolveType (ec);
-               }
+                                       return true;
+                               }
+                       }
 
-               bool DoResolveType (EmitContext ec)
-               {
-                       //
-                       // Resolve the arguments.
-                       //
-                       if (args.Resolve (ec) == false)
-                               return false;
+                       TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
+                       if (tparam != null)
+                               return tparam.HasConstructorConstraint;
 
-                       gen_params = gt.GetGenericArguments ();
-                       atypes = args.Arguments;
+                       MemberList list = TypeManager.FindMembers (
+                               atype, MemberTypes.Constructor,
+                               BindingFlags.Public | BindingFlags.Instance |
+                               BindingFlags.DeclaredOnly, null, null);
 
-                       if (atypes.Length != gen_params.Length) {
-                               Report.Error (305, loc,
-                                             "Using the generic type `{0}' " +
-                                             "requires {1} type arguments",
-                                             TypeManager.GetFullName (gt),
-                                             gen_params.Length);
+                       if (atype.IsAbstract || (list == null))
                                return false;
+
+                       foreach (MethodBase mb in list) {
+                               ParameterData pd = TypeManager.GetParameterData (mb);
+                               if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
+                                       return true;
                        }
 
-                       //
-                       // Now bind the parameters.
-                       //
-                       type = gt.MakeGenericType (atypes);
-                       return true;
+                       return false;
                }
 
-               public Expression GetSimpleName (EmitContext ec)
-               {
-                       return this;
-               }
+               protected abstract string GetSignatureForError ();
+               protected abstract void Report_SymbolRelatedToPreviousError ();
 
-               public override bool CheckAccessLevel (DeclSpace ds)
+               void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
                {
-                       return ds.CheckAccessLevel (gt);
+                       Report_SymbolRelatedToPreviousError ();
+                       Report.SymbolRelatedToPreviousError (atype);
+                       Report.Error (309, loc, 
+                                     "The type `{0}' must be convertible to `{1}' in order to " +
+                                     "use it as parameter `{2}' in the generic type or method `{3}'",
+                                     TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
+                                     TypeManager.CSharpName (ptype), GetSignatureForError ());
                }
 
-               public override bool AsAccessible (DeclSpace ds, int flags)
+               public static bool CheckConstraints (EmitContext ec, MethodBase definition,
+                                                    MethodBase instantiated, Location loc)
                {
-                       return ds.AsAccessible (gt, flags);
-               }
-
-               public override bool IsClass {
-                       get { return gt.IsClass; }
-               }
+                       MethodConstraintChecker checker = new MethodConstraintChecker (
+                               definition, definition.GetGenericArguments (),
+                               instantiated.GetGenericArguments (), loc);
 
-               public override bool IsValueType {
-                       get { return gt.IsValueType; }
+                       return checker.CheckConstraints (ec);
                }
 
-               public override bool IsInterface {
-                       get { return gt.IsInterface; }
-               }
+               public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
+                                                    Type[] atypes, Location loc)
+               {
+                       TypeConstraintChecker checker = new TypeConstraintChecker (
+                               gt, gen_params, atypes, loc);
 
-               public override bool IsSealed {
-                       get { return gt.IsSealed; }
+                       return checker.CheckConstraints (ec);
                }
 
-               public override bool Equals (object obj)
+               protected class MethodConstraintChecker : ConstraintChecker
                {
-                       ConstructedType cobj = obj as ConstructedType;
-                       if (cobj == null)
-                               return false;
+                       MethodBase definition;
 
-                       if ((type == null) || (cobj.type == null))
-                               return false;
+                       public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
+                                                       Type[] atypes, Location loc)
+                               : base (gen_params, atypes, loc)
+                       {
+                               this.definition = definition;
+                       }
 
-                       return type == cobj.type;
+                       protected override string GetSignatureForError ()
+                       {
+                               return TypeManager.CSharpSignature (definition);
+                       }
+
+                       protected override void Report_SymbolRelatedToPreviousError ()
+                       {
+                               Report.SymbolRelatedToPreviousError (definition);
+                       }
                }
 
-               public override int GetHashCode ()
+               protected class TypeConstraintChecker : ConstraintChecker
                {
-                       return base.GetHashCode ();
-               }
+                       Type gt;
 
-               public override string Name {
-                       get {
-                               return full_name;
+                       public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
+                                                     Location loc)
+                               : base (gen_params, atypes, loc)
+                       {
+                               this.gt = gt;
                        }
-               }
 
+                       protected override string GetSignatureForError ()
+                       {
+                               return TypeManager.CSharpName (gt);
+                       }
 
-               public override string FullName {
-                       get {
-                               return full_name;
+                       protected override void Report_SymbolRelatedToPreviousError ()
+                       {
+                               Report.SymbolRelatedToPreviousError (gt);
                        }
                }
        }
@@ -1618,9 +1752,16 @@ namespace Mono.CSharp {
        /// </summary>
        public class GenericMethod : DeclSpace
        {
-               public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name)
+               Expression return_type;
+               Parameters parameters;
+
+               public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
+                                     Expression return_type, Parameters parameters)
                        : base (ns, parent, name, null)
-               { }
+               {
+                       this.return_type = return_type;
+                       this.parameters = parameters;
+               }
 
                public override TypeBuilder DefineType ()
                {
@@ -1629,8 +1770,6 @@ namespace Mono.CSharp {
 
                public override bool Define ()
                {
-                       ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
-
                        for (int i = 0; i < TypeParameters.Length; i++)
                                if (!TypeParameters [i].Resolve (this))
                                        return false;
@@ -1645,8 +1784,11 @@ namespace Mono.CSharp {
                public bool Define (MethodBuilder mb)
                {
                        GenericTypeParameterBuilder[] gen_params;
-                       string[] names = MemberName.TypeArguments.GetDeclarations ();
-                       gen_params = mb.DefineGenericParameters (names);
+                       TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
+                       string[] snames = new string [names.Length];
+                       for (int i = 0; i < names.Length; i++)
+                               snames [i] = names [i].Name;
+                       gen_params = mb.DefineGenericParameters (snames);
                        for (int i = 0; i < TypeParameters.Length; i++)
                                TypeParameters [i].Define (gen_params [i]);
 
@@ -1654,7 +1796,7 @@ namespace Mono.CSharp {
                                return false;
 
                        for (int i = 0; i < TypeParameters.Length; i++) {
-                               if (!TypeParameters [i].ResolveType (ec))
+                               if (!TypeParameters [i].ResolveType (this))
                                        return false;
                        }
 
@@ -1672,10 +1814,27 @@ namespace Mono.CSharp {
                                            ec, mb, implementing, is_override))
                                        return false;
 
-                       return true;
+                       bool ok = true;
+                       foreach (Parameter p in parameters.FixedParameters){
+                               if (!p.Resolve (ec))
+                                       ok = false;
+                       }
+                       if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
+                               ok = false;
+
+                       return ok;
+               }
+
+               public void EmitAttributes ()
+               {
+                       for (int i = 0; i < TypeParameters.Length; i++)
+                               TypeParameters [i].EmitAttributes ();
+
+                       if (OptAttributes != null)
+                               OptAttributes.Emit ();
                }
 
-               public override bool DefineMembers (TypeContainer parent)
+               public override bool DefineMembers ()
                {
                        return true;
                }
@@ -1694,7 +1853,7 @@ namespace Mono.CSharp {
 
                public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
                {
-                       // FIXME
+                       base.ApplyAttributeBuilder (a, cb);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -1720,7 +1879,7 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
+                       TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
                        if (texpr == null)
                                return null;
 
@@ -1733,7 +1892,7 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
-                               LocalTemporary temp_storage = new LocalTemporary (ec, type);
+                               LocalTemporary temp_storage = new LocalTemporary (type);
 
                                temp_storage.AddressOf (ec, AddressOp.LoadStore);
                                ec.ig.Emit (OpCodes.Initobj, type);
@@ -1767,13 +1926,13 @@ namespace Mono.CSharp {
                        get { return underlying.ToString () + "?"; }
                }
 
-               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
                {
                        TypeArguments args = new TypeArguments (loc);
                        args.Add (underlying);
 
                        ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
-                       return ctype.ResolveAsTypeTerminal (ec);
+                       return ctype.ResolveAsTypeTerminal (ec, false);
                }
        }
 
@@ -1782,7 +1941,6 @@ namespace Mono.CSharp {
                //
                // A list of core types that the compiler requires or uses
                //
-               static public Type new_constraint_attr_type;
                static public Type activator_type;
                static public Type generic_ienumerator_type;
                static public Type generic_ienumerable_type;
@@ -1811,8 +1969,6 @@ namespace Mono.CSharp {
                static void InitGenericCoreTypes ()
                {
                        activator_type = CoreLookupType ("System", "Activator");
-                       new_constraint_attr_type = CoreLookupType (
-                               "System.Runtime.CompilerServices", "NewConstraintAttribute");
 
                        generic_ienumerator_type = CoreLookupType (
                                "System.Collections.Generic", "IEnumerator", 1);
@@ -1843,9 +1999,7 @@ namespace Mono.CSharp {
 
                public static TypeContainer LookupGenericTypeContainer (Type t)
                {
-                       while (t.IsGenericInstance)
-                               t = t.GetGenericTypeDefinition ();
-
+                       t = DropGenericTypeArguments (t);
                        return LookupTypeContainer (t);
                }
 
@@ -1863,14 +2017,7 @@ namespace Mono.CSharp {
                        if (tparam != null)
                                return tparam.GenericConstraints;
 
-                       return new ReflectionConstraints (t);
-               }
-
-               public static bool IsGeneric (Type t)
-               {
-                       DeclSpace ds = (DeclSpace) builder_to_declspace [t];
-
-                       return ds.IsGeneric;
+                       return ReflectionConstraints.GetConstraints (t);
                }
 
                public static bool HasGenericArguments (Type t)
@@ -1909,13 +2056,66 @@ namespace Mono.CSharp {
                                return t.GetGenericArguments ();
                }
 
+               public static Type DropGenericTypeArguments (Type t)
+               {
+                       if (!t.IsGenericType)
+                               return t;
+                       // Micro-optimization: a generic typebuilder is always a generic type definition
+                       if (t is TypeBuilder)
+                               return t;
+                       return t.GetGenericTypeDefinition ();
+               }
+
+               public static MethodBase DropGenericMethodArguments (MethodBase m)
+               {
+                       if (m.IsGenericMethodDefinition)
+                               return m;
+                       if (m.IsGenericMethod)
+                               return ((MethodInfo) m).GetGenericMethodDefinition ();
+                       if (!m.DeclaringType.IsGenericType)
+                               return m;
+
+                       Type t = m.DeclaringType.GetGenericTypeDefinition ();
+                       BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
+                               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
+
+                       if (m is ConstructorInfo) {
+                               foreach (ConstructorInfo c in t.GetConstructors (bf))
+                                       if (c.MetadataToken == m.MetadataToken)
+                                               return c;
+                       } else {
+                               foreach (MethodBase mb in t.GetMethods (bf))
+                                       if (mb.MetadataToken == m.MetadataToken)
+                                               return mb;
+                       }
+
+                       return m;
+               }
+
+               public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
+               {
+                       if (fi.DeclaringType.IsGenericTypeDefinition ||
+                           !fi.DeclaringType.IsGenericType)
+                               return fi;
+
+                       Type t = fi.DeclaringType.GetGenericTypeDefinition ();
+                       BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
+                               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
+
+                       foreach (FieldInfo f in t.GetFields (bf))
+                               if (f.MetadataToken == fi.MetadataToken)
+                                       return f;
+
+                       return fi;
+               }
+
                //
                // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
                // For instance "string[]" -> "IEnumerable<string>".
                //
                public static bool IsIEnumerable (Type array, Type enumerator)
                {
-                       if (!array.IsArray || !enumerator.IsGenericInstance)
+                       if (!array.IsArray || !enumerator.IsGenericType)
                                return false;
 
                        if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
@@ -1930,43 +2130,6 @@ namespace Mono.CSharp {
                        if (a.Equals (b))
                                return true;
 
-                       if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
-                               //
-                               // `a' is a generic type definition's TypeBuilder and `b' is a
-                               // generic instance of the same type.
-                               //
-                               // Example:
-                               //
-                               // class Stack<T>
-                               // {
-                               //     void Test (Stack<T> stack) { }
-                               // }
-                               //
-                               // The first argument of `Test' will be the generic instance
-                               // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
-                               //
-                               //
-                               // We hit this via Closure.Filter() for gen-82.cs.
-                               //
-                               if (a != b.GetGenericTypeDefinition ())
-                                       return false;
-
-                               Type[] aparams = a.GetGenericArguments ();
-                               Type[] bparams = b.GetGenericArguments ();
-
-                               if (aparams.Length != bparams.Length)
-                                       return false;
-
-                               for (int i = 0; i < aparams.Length; i++)
-                                       if (!IsEqual (aparams [i], bparams [i]))
-                                               return false;
-
-                               return true;
-                       }
-
-                       if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
-                               return IsEqual (b, a);
-
                        if (a.IsGenericParameter && b.IsGenericParameter) {
                                if (a.DeclaringMethod != b.DeclaringMethod &&
                                    (a.DeclaringMethod == null || b.DeclaringMethod == null))
@@ -1980,7 +2143,10 @@ namespace Mono.CSharp {
                                return IsEqual (a.GetElementType (), b.GetElementType ());
                        }
 
-                       if (a.IsGenericInstance && b.IsGenericInstance) {
+                       if (a.IsByRef && b.IsByRef)
+                               return IsEqual (a.GetElementType (), b.GetElementType ());
+
+                       if (a.IsGenericType && b.IsGenericType) {
                                if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
                                        return false;
 
@@ -1998,6 +2164,24 @@ namespace Mono.CSharp {
                                return true;
                        }
 
+                       //
+                       // This is to build with the broken circular dependencies between
+                       // System and System.Configuration in the 2.x profile where we
+                       // end up with a situation where:
+                       //
+                       // System on the second build is referencing the System.Configuration
+                       // that has references to the first System build.
+                       //
+                       // Point in case: NameValueCollection built on the first pass, vs
+                       // NameValueCollection build on the second one.  The problem is that
+                       // we need to override some methods sometimes, or we need to 
+                       //
+                       if (RootContext.BrokenCircularDeps){
+                               if (a.Name == b.Name && a.Namespace == b.Namespace){
+                                       Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
+                                       return true;
+                               }
+                       }
                        return false;
                }
 
@@ -2026,7 +2210,7 @@ namespace Mono.CSharp {
                                //    class X<T,U> : I<T>, I<U>
                                //    class X<T> : I<T>, I<float>
                                // 
-                               if (b.IsGenericParameter || !b.IsGenericInstance) {
+                               if (b.IsGenericParameter || !b.IsGenericType) {
                                        int pos = a.GenericParameterPosition;
                                        Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
                                        if (args [pos] == null) {
@@ -2071,7 +2255,7 @@ namespace Mono.CSharp {
                        // become equal).
                        //
 
-                       if (a.IsGenericInstance || b.IsGenericInstance)
+                       if (a.IsGenericType || b.IsGenericType)
                                return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
 
                        //
@@ -2103,7 +2287,7 @@ namespace Mono.CSharp {
                                                                   Type[] class_infered,
                                                                   Type[] method_infered)
                {
-                       if (!a.IsGenericInstance || !b.IsGenericInstance)
+                       if (!a.IsGenericType || !b.IsGenericType)
                                return false;
                        if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
                                return false;
@@ -2136,21 +2320,19 @@ namespace Mono.CSharp {
                        int tcount = GetNumberOfTypeArguments (type);
                        int pcount = GetNumberOfTypeArguments (parent);
 
-                       if (type.IsGenericInstance)
-                               type = type.GetGenericTypeDefinition ();
-                       if (parent.IsGenericInstance)
-                               parent = parent.GetGenericTypeDefinition ();
-
                        if (tcount != pcount)
                                return false;
 
+                       type = DropGenericTypeArguments (type);
+                       parent = DropGenericTypeArguments (parent);
+
                        return type.Equals (parent);
                }
 
                /// <summary>
                ///   Whether `mb' is a generic method definition.
                /// </summary>
-               public static bool IsGenericMethod (MethodBase mb)
+               public static bool IsGenericMethodDefinition (MethodBase mb)
                {
                        if (mb.DeclaringType is TypeBuilder) {
                                IMethodData method = (IMethodData) builder_to_method [mb];
@@ -2163,23 +2345,35 @@ namespace Mono.CSharp {
                        return mb.IsGenericMethodDefinition;
                }
 
+               /// <summary>
+               ///   Whether `mb' is a generic method definition.
+               /// </summary>
+               public static bool IsGenericMethod (MethodBase mb)
+               {
+                       if (mb.DeclaringType is TypeBuilder) {
+                               IMethodData method = (IMethodData) builder_to_method [mb];
+                               if (method == null)
+                                       return false;
+
+                               return method.GenericMethod != null;
+                       }
+
+                       return mb.IsGenericMethod;
+               }
+
                //
                // Type inference.
                //
 
                static bool InferType (Type pt, Type at, Type[] infered)
                {
-                       if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
+                       if (pt.IsGenericParameter) {
+                               if (pt.DeclaringMethod == null)
+                                       return pt == at;
+
                                int pos = pt.GenericParameterPosition;
 
                                if (infered [pos] == null) {
-                                       Type check = at;
-                                       while (check.IsArray)
-                                               check = check.GetElementType ();
-
-                                       if (pt == check)
-                                               return false;
-
                                        infered [pos] = at;
                                        return true;
                                }
@@ -2198,11 +2392,19 @@ namespace Mono.CSharp {
                        }
 
                        if (at.IsArray) {
-                               if (!pt.IsArray ||
-                                   (at.GetArrayRank () != pt.GetArrayRank ()))
-                                       return false;
+                               if (pt.IsArray) {
+                                       if (at.GetArrayRank () != pt.GetArrayRank ())
+                                               return false;
 
-                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                                       return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                               }
+
+                               if (!pt.IsGenericType ||
+                                   (pt.GetGenericTypeDefinition () != generic_ienumerable_type))
+                                   return false;
+
+                               Type[] args = GetTypeArguments (pt);
+                               return InferType (args [0], at.GetElementType (), infered);
                        }
 
                        if (pt.IsArray) {
@@ -2216,7 +2418,7 @@ namespace Mono.CSharp {
                        if (pt.IsByRef && at.IsByRef)
                                return InferType (pt.GetElementType (), at.GetElementType (), infered);
                        ArrayList list = new ArrayList ();
-                       if (at.IsGenericInstance)
+                       if (at.IsGenericType)
                                list.Add (at);
                        for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
                                list.Add (bt);
@@ -2226,7 +2428,7 @@ namespace Mono.CSharp {
                        bool found_one = false;
 
                        foreach (Type type in list) {
-                               if (!type.IsGenericInstance)
+                               if (!type.IsGenericType)
                                        continue;
 
                                Type[] infered_types = new Type [infered.Length];
@@ -2374,7 +2576,7 @@ namespace Mono.CSharp {
                ///   when resolving an Invocation or a DelegateInvocation and the user
                ///   did not explicitly specify type arguments.
                /// </summary>
-               public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
+               public static bool InferTypeArguments (ArrayList arguments,
                                                       ref MethodBase method)
                {
                        if (!TypeManager.IsGenericMethod (method))
@@ -2399,8 +2601,10 @@ namespace Mono.CSharp {
                                        break;
                                }
                        }
+
+                       // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
                        if (!is_open)
-                               return true;
+                               return !TypeManager.IsGenericMethodDefinition (method);
 
                        Type[] infered_types = new Type [method_args.Length];
 
@@ -2428,7 +2632,7 @@ namespace Mono.CSharp {
                /// <summary>
                ///   Type inference.
                /// </summary>
-               public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
+               public static bool InferTypeArguments (ParameterData apd,
                                                       ref MethodBase method)
                {
                        if (!TypeManager.IsGenericMethod (method))
@@ -2458,17 +2662,29 @@ namespace Mono.CSharp {
 
                public static bool IsNullableType (Type t)
                {
-                       if (!t.IsGenericInstance)
+                       return generic_nullable_type == DropGenericTypeArguments (t);
+               }
+
+               public static bool IsNullableTypeOf (Type t, Type nullable)
+               {
+                       if (!IsNullableType (t))
+                               return false;
+
+                       return GetTypeArguments (t) [0] == nullable;
+               }
+
+               public static bool IsNullableValueType (Type t)
+               {
+                       if (!IsNullableType (t))
                                return false;
 
-                       Type gt = t.GetGenericTypeDefinition ();
-                       return gt == generic_nullable_type;
+                       return GetTypeArguments (t) [0].IsValueType;
                }
        }
 
        public abstract class Nullable
        {
-               protected sealed class NullableInfo
+               public sealed class NullableInfo
                {
                        public readonly Type Type;
                        public readonly Type UnderlyingType;
@@ -2481,8 +2697,8 @@ namespace Mono.CSharp {
                                Type = type;
                                UnderlyingType = TypeManager.GetTypeArguments (type) [0];
 
-                               PropertyInfo has_value_pi = type.GetProperty ("HasValue");
-                               PropertyInfo value_pi = type.GetProperty ("Value");
+                               PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
+                               PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
 
                                HasValue = has_value_pi.GetGetMethod (false);
                                Value = value_pi.GetGetMethod (false);
@@ -2490,7 +2706,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
+               public class Unwrap : Expression, IMemoryLocation, IAssignMethod
                {
                        Expression expr;
                        NullableInfo info;
@@ -2498,10 +2714,15 @@ namespace Mono.CSharp {
                        LocalTemporary temp;
                        bool has_temp;
 
-                       public Unwrap (Expression expr, Location loc)
+                       protected Unwrap (Expression expr)
                        {
                                this.expr = expr;
-                               this.loc = loc;
+                               this.loc = expr.Location;
+                       }
+
+                       public static Unwrap Create (Expression expr, EmitContext ec)
+                       {
+                               return new Unwrap (expr).Resolve (ec) as Unwrap;
                        }
 
                        public override Expression DoResolve (EmitContext ec)
@@ -2510,8 +2731,7 @@ namespace Mono.CSharp {
                                if (expr == null)
                                        return null;
 
-                               if (!(expr is IMemoryLocation))
-                                       temp = new LocalTemporary (ec, expr.Type);
+                               temp = new LocalTemporary (expr.Type);
 
                                info = new NullableInfo (expr.Type);
                                type = info.UnderlyingType;
@@ -2531,6 +2751,11 @@ namespace Mono.CSharp {
                                ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
                        }
 
+                       public void Store (EmitContext ec)
+                       {
+                               create_temp (ec);
+                       }
+
                        void create_temp (EmitContext ec)
                        {
                                if ((temp != null) && !has_temp) {
@@ -2565,26 +2790,52 @@ namespace Mono.CSharp {
                        public void EmitAssign (EmitContext ec, Expression source,
                                                bool leave_copy, bool prepare_for_load)
                        {
-                               source.Emit (ec);
-                               ec.ig.Emit (OpCodes.Newobj, info.Constructor);
+                               InternalWrap wrap = new InternalWrap (source, info, loc);
+                               ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
+                       }
+
+                       protected class InternalWrap : Expression
+                       {
+                               public Expression expr;
+                               public NullableInfo info;
 
-                               if (leave_copy)
-                                       ec.ig.Emit (OpCodes.Dup);
+                               public InternalWrap (Expression expr, NullableInfo info, Location loc)
+                               {
+                                       this.expr = expr;
+                                       this.info = info;
+                                       this.loc = loc;
+
+                                       type = info.Type;
+                                       eclass = ExprClass.Value;
+                               }
+
+                               public override Expression DoResolve (EmitContext ec)
+                               {
+                                       return this;
+                               }
 
-                               Expression empty = new EmptyExpression (expr.Type);
-                               ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
+                               public override void Emit (EmitContext ec)
+                               {
+                                       expr.Emit (ec);
+                                       ec.ig.Emit (OpCodes.Newobj, info.Constructor);
+                               }
                        }
                }
 
-               protected class Wrap : Expression
+               public class Wrap : Expression
                {
                        Expression expr;
                        NullableInfo info;
 
-                       public Wrap (Expression expr, Location loc)
+                       protected Wrap (Expression expr)
                        {
                                this.expr = expr;
-                               this.loc = loc;
+                               this.loc = expr.Location;
+                       }
+
+                       public static Wrap Create (Expression expr, EmitContext ec)
+                       {
+                               return new Wrap (expr).Resolve (ec) as Wrap;
                        }
 
                        public override Expression DoResolve (EmitContext ec)
@@ -2594,7 +2845,7 @@ namespace Mono.CSharp {
                                        return null;
 
                                TypeExpr target_type = new NullableType (expr.Type, loc);
-                               target_type = target_type.ResolveAsTypeTerminal (ec);
+                               target_type = target_type.ResolveAsTypeTerminal (ec, false);
                                if (target_type == null)
                                        return null;
 
@@ -2611,11 +2862,11 @@ namespace Mono.CSharp {
                        }
                }
 
-               public class NullableLiteral : Expression, IMemoryLocation {
+               public class NullableLiteral : NullLiteral, IMemoryLocation {
                        public NullableLiteral (Type target_type, Location loc)
+                               : base (loc)
                        {
                                this.type = target_type;
-                               this.loc = loc;
 
                                eclass = ExprClass.Value;
                        }
@@ -2627,7 +2878,7 @@ namespace Mono.CSharp {
 
                        public override void Emit (EmitContext ec)
                        {
-                               LocalTemporary value_target = new LocalTemporary (ec, type);
+                               LocalTemporary value_target = new LocalTemporary (type);
 
                                value_target.AddressOf (ec, AddressOp.Store);
                                ec.ig.Emit (OpCodes.Initobj, type);
@@ -2636,7 +2887,7 @@ namespace Mono.CSharp {
 
                        public void AddressOf (EmitContext ec, AddressOp Mode)
                        {
-                               LocalTemporary value_target = new LocalTemporary (ec, type);
+                               LocalTemporary value_target = new LocalTemporary (type);
                                        
                                value_target.AddressOf (ec, AddressOp.Store);
                                ec.ig.Emit (OpCodes.Initobj, type);
@@ -2661,7 +2912,7 @@ namespace Mono.CSharp {
                                if (expr == null)
                                        return null;
 
-                               unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
+                               unwrap = Unwrap.Create (expr, ec);
                                if (unwrap == null)
                                        return null;
 
@@ -2669,7 +2920,7 @@ namespace Mono.CSharp {
                                if (underlying == null)
                                        return null;
 
-                               wrap = new Wrap (underlying, loc).Resolve (ec);
+                               wrap = Wrap.Create (underlying, ec);
                                if (wrap == null)
                                        return null;
 
@@ -2776,7 +3027,8 @@ namespace Mono.CSharp {
                {
                        public readonly Binary.Operator Oper;
 
-                       Expression left, right, underlying, null_value, bool_wrap;
+                       Expression left, right, original_left, original_right;
+                       Expression underlying, null_value, bool_wrap;
                        Unwrap left_unwrap, right_unwrap;
                        bool is_equality, is_comparision, is_boolean;
 
@@ -2784,32 +3036,38 @@ namespace Mono.CSharp {
                                                     Location loc)
                        {
                                this.Oper = op;
-                               this.left = left;
-                               this.right = right;
+                               this.left = original_left = left;
+                               this.right = original_right = right;
                                this.loc = loc;
                        }
 
                        public override Expression DoResolve (EmitContext ec)
                        {
                                if (TypeManager.IsNullableType (left.Type)) {
-                                       left_unwrap = new Unwrap (left, loc);
-                                       left = left_unwrap.Resolve (ec);
+                                       left = left_unwrap = Unwrap.Create (left, ec);
                                        if (left == null)
                                                return null;
                                }
 
                                if (TypeManager.IsNullableType (right.Type)) {
-                                       right_unwrap = new Unwrap (right, loc);
-                                       right = right_unwrap.Resolve (ec);
+                                       right = right_unwrap = Unwrap.Create (right, ec);
                                        if (right == null)
                                                return null;
                                }
 
-                               if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
-                                    (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
+                               if ((Oper == Binary.Operator.LogicalAnd) ||
+                                   (Oper == Binary.Operator.LogicalOr)) {
+                                       Binary.Error_OperatorCannotBeApplied (
+                                               loc, Binary.OperName (Oper),
+                                               original_left.GetSignatureForError (),
+                                               original_right.GetSignatureForError ());
+                                       return null;
+                               }
+
+                               if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
                                    ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
                                        Expression empty = new EmptyExpression (TypeManager.bool_type);
-                                       bool_wrap = new Wrap (empty, loc).Resolve (ec);
+                                       bool_wrap = Wrap.Create (empty, ec);
                                        null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
 
                                        type = bool_wrap.Type;
@@ -2838,7 +3096,7 @@ namespace Mono.CSharp {
                                        if (underlying == null)
                                                return null;
 
-                                       underlying = new Wrap (underlying, loc).Resolve (ec);
+                                       underlying = Wrap.Create (underlying, ec);
                                        if (underlying == null)
                                                return null;
 
@@ -2918,95 +3176,70 @@ namespace Mono.CSharp {
                        {
                                ILGenerator ig = ec.ig;
 
-                               Label left_not_null_label = ig.DefineLabel ();
-                               Label false_label = ig.DefineLabel ();
-                               Label true_label = ig.DefineLabel ();
-                               Label end_label = ig.DefineLabel ();
-
-                               bool false_label_used = false;
-                               bool true_label_used = false;
+                               // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
+                               if (left is NullLiteral) {
+                                       if (right_unwrap == null)
+                                               throw new InternalErrorException ();
+                                       right_unwrap.EmitCheck (ec);
+                                       if (Oper == Binary.Operator.Equality) {
+                                               ig.Emit (OpCodes.Ldc_I4_0);
+                                               ig.Emit (OpCodes.Ceq);
+                                       }
+                                       return;
+                               }
 
-                               if (left_unwrap != null) {
+                               if (right is NullLiteral) {
+                                       if (left_unwrap == null)
+                                               throw new InternalErrorException ();
                                        left_unwrap.EmitCheck (ec);
-                                       if (right is NullLiteral) {
-                                               if (Oper == Binary.Operator.Equality) {
-                                                       true_label_used = true;
-                                                       ig.Emit (OpCodes.Brfalse, true_label);
-                                               } else {
-                                                       false_label_used = true;
-                                                       ig.Emit (OpCodes.Brfalse, false_label);
-                                               }
-                                       } else if (right_unwrap != null) {
-                                               ig.Emit (OpCodes.Dup);
-                                               ig.Emit (OpCodes.Brtrue, left_not_null_label);
-                                               right_unwrap.EmitCheck (ec);
+                                       if (Oper == Binary.Operator.Equality) {
+                                               ig.Emit (OpCodes.Ldc_I4_0);
                                                ig.Emit (OpCodes.Ceq);
-                                               if (Oper == Binary.Operator.Inequality) {
-                                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                                       ig.Emit (OpCodes.Ceq);
-                                               }
-                                               ig.Emit (OpCodes.Br, end_label);
-
-                                               ig.MarkLabel (left_not_null_label);
-                                               ig.Emit (OpCodes.Pop);
-                                       } else {
-                                               if (Oper == Binary.Operator.Equality) {
-                                                       false_label_used = true;
-                                                       ig.Emit (OpCodes.Brfalse, false_label);
-                                               } else {
-                                                       true_label_used = true;
-                                                       ig.Emit (OpCodes.Brfalse, true_label);
-                                               }
                                        }
+                                       return;
                                }
 
-                               if (right_unwrap != null) {
+                               Label both_have_value_label = ig.DefineLabel ();
+                               Label end_label = ig.DefineLabel ();
+
+                               if (left_unwrap != null && right_unwrap != null) {
+                                       Label dissimilar_label = ig.DefineLabel ();
+
+                                       left_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Dup);
                                        right_unwrap.EmitCheck (ec);
-                                       if (left is NullLiteral) {
-                                               if (Oper == Binary.Operator.Equality) {
-                                                       true_label_used = true;
-                                                       ig.Emit (OpCodes.Brfalse, true_label);
-                                               } else {
-                                                       false_label_used = true;
-                                                       ig.Emit (OpCodes.Brfalse, false_label);
-                                               }
-                                       } else {
-                                               if (Oper == Binary.Operator.Equality) {
-                                                       false_label_used = true;
-                                                       ig.Emit (OpCodes.Brfalse, false_label);
-                                               } else {
-                                                       true_label_used = true;
-                                                       ig.Emit (OpCodes.Brfalse, true_label);
-                                               }
-                                       }
-                               }
+                                       ig.Emit (OpCodes.Bne_Un, dissimilar_label);
 
-                               bool left_is_null = left is NullLiteral;
-                               bool right_is_null = right is NullLiteral;
-                               if (left_is_null || right_is_null) {
-                                       if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
-                                           ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
-                                               true_label_used = true;
-                                               ig.Emit (OpCodes.Br, true_label);
-                                       } else {
-                                               false_label_used = true;
-                                               ig.Emit (OpCodes.Br, false_label);
-                                       }
-                               } else {
-                                       underlying.Emit (ec);
+                                       ig.Emit (OpCodes.Brtrue, both_have_value_label);
+
+                                       // both are null
+                                       if (Oper == Binary.Operator.Equality)
+                                               ig.Emit (OpCodes.Ldc_I4_1);
+                                       else
+                                               ig.Emit (OpCodes.Ldc_I4_0);
                                        ig.Emit (OpCodes.Br, end_label);
-                               }
 
-                               ig.MarkLabel (false_label);
-                               if (false_label_used) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       if (true_label_used)
-                                               ig.Emit (OpCodes.Br, end_label);
+                                       ig.MarkLabel (dissimilar_label);
+                                       ig.Emit (OpCodes.Pop);
+                               } else if (left_unwrap != null) {
+                                       left_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brtrue, both_have_value_label);
+                               } else if (right_unwrap != null) {
+                                       right_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brtrue, both_have_value_label);
+                               } else {
+                                       throw new InternalErrorException ("shouldn't get here");
                                }
 
-                               ig.MarkLabel (true_label);
-                               if (true_label_used)
+                               // one is null while the other isn't
+                               if (Oper == Binary.Operator.Equality)
+                                       ig.Emit (OpCodes.Ldc_I4_0);
+                               else
                                        ig.Emit (OpCodes.Ldc_I4_1);
+                               ig.Emit (OpCodes.Br, end_label);
+
+                               ig.MarkLabel (both_have_value_label);
+                               underlying.Emit (ec);
 
                                ig.MarkLabel (end_label);
                        }
@@ -3039,6 +3272,11 @@ namespace Mono.CSharp {
 
                        public override void Emit (EmitContext ec)
                        {
+                               if (left_unwrap != null)
+                                       left_unwrap.Store (ec);
+                               if (right_unwrap != null)
+                                       right_unwrap.Store (ec);
+
                                if (is_boolean) {
                                        EmitBoolean (ec);
                                        return;
@@ -3091,9 +3329,8 @@ namespace Mono.CSharp {
 
                        public override Expression DoResolve (EmitContext ec)
                        {
-                               unwrap = new Unwrap (expr, loc);
-                               expr = unwrap.Resolve (ec);
-                               if (expr == null)
+                               unwrap = Unwrap.Create (expr, ec);
+                               if (unwrap == null)
                                        return null;
 
                                if (unwrap.Type != TypeManager.bool_type)
@@ -3166,7 +3403,7 @@ namespace Mono.CSharp {
                                if (TypeManager.IsNullableType (ltype)) {
                                        NullableInfo info = new NullableInfo (ltype);
 
-                                       unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
+                                       unwrap = Unwrap.Create (left, ec);
                                        if (unwrap == null)
                                                return null;
 
@@ -3253,7 +3490,7 @@ namespace Mono.CSharp {
                                if (expr == null)
                                        return null;
 
-                               unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
+                               unwrap = Unwrap.Create (expr, ec);
                                if (unwrap == null)
                                        return null;