Exemple #1
0
 private static bool Object_getClass(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     // this is the null-check idiom that javac uses (both in its own source and in the code it generates)
     if (code[opcodeIndex + 1].NormalizedOpCode == NormalizedByteCode.__pop)
     {
         ilgen.Emit(OpCodes.Dup);
         ilgen.EmitNullCheck();
         return(true);
     }
     // this optimizes obj1.getClass() ==/!= obj2.getClass()
     else if (opcodeIndex + 3 < code.Length &&
              (flags[opcodeIndex + 1] & InstructionFlags.BranchTarget) == 0 &&
              (flags[opcodeIndex + 2] & InstructionFlags.BranchTarget) == 0 &&
              (flags[opcodeIndex + 3] & InstructionFlags.BranchTarget) == 0 &&
              code[opcodeIndex + 1].NormalizedOpCode == NormalizedByteCode.__aload &&
              code[opcodeIndex + 2].NormalizedOpCode == NormalizedByteCode.__invokevirtual &&
              (code[opcodeIndex + 3].NormalizedOpCode == NormalizedByteCode.__if_acmpeq || code[opcodeIndex + 3].NormalizedOpCode == NormalizedByteCode.__if_acmpne) &&
              (IsSafeForGetClassOptimization(ma.GetStackTypeWrapper(opcodeIndex, 0)) || IsSafeForGetClassOptimization(ma.GetStackTypeWrapper(opcodeIndex + 2, 0))))
     {
         ClassFile.ConstantPoolItemMI cpi = classFile.GetMethodref(code[opcodeIndex + 2].Arg1);
         if (cpi.Class == "java.lang.Object" && cpi.Name == "getClass" && cpi.Signature == "()Ljava.lang.Class;")
         {
             // we can't patch the current opcode, so we have to emit the first call to GetTypeHandle here
             ilgen.Emit(OpCodes.Callvirt, Compiler.getTypeMethod);
             code[opcodeIndex + 2].PatchOpCode(NormalizedByteCode.__intrinsic_gettype);
             return(true);
         }
     }
     return(false);
 }
Exemple #2
0
 internal static bool Emit(DynamicTypeWrapper.FinishContext context, TypeWrapper wrapper, CodeEmitter ilgen, ClassFile classFile, int i, ClassFile.Method.Instruction[] code, InstructionFlags[] flags)
 {
     if (i >= 3 &&
         (flags[i - 0] & InstructionFlags.BranchTarget) == 0 &&
         (flags[i - 1] & InstructionFlags.BranchTarget) == 0 &&
         (flags[i - 2] & InstructionFlags.BranchTarget) == 0 &&
         (flags[i - 3] & InstructionFlags.BranchTarget) == 0 &&
         code[i - 1].NormalizedOpCode == NormalizedByteCode.__ldc_nothrow &&
         code[i - 2].NormalizedOpCode == NormalizedByteCode.__ldc &&
         code[i - 3].NormalizedOpCode == NormalizedByteCode.__ldc)
     {
         // we now have a structural match, now we need to make sure that the argument values are what we expect
         TypeWrapper tclass    = classFile.GetConstantPoolClassType(code[i - 3].Arg1);
         TypeWrapper vclass    = classFile.GetConstantPoolClassType(code[i - 2].Arg1);
         string      fieldName = classFile.GetConstantPoolConstantString(code[i - 1].Arg1);
         if (tclass == wrapper && !vclass.IsUnloadable && !vclass.IsPrimitive && !vclass.IsNonPrimitiveValueType)
         {
             FieldWrapper field = wrapper.GetFieldWrapper(fieldName, vclass.SigName);
             if (field != null && !field.IsStatic && field.IsVolatile && field.DeclaringType == wrapper && field.FieldTypeWrapper == vclass)
             {
                 // everything matches up, now call the actual emitter
                 ilgen.Emit(OpCodes.Pop);
                 ilgen.Emit(OpCodes.Pop);
                 ilgen.Emit(OpCodes.Pop);
                 ilgen.Emit(OpCodes.Newobj, context.GetAtomicReferenceFieldUpdater(field));
                 return(true);
             }
         }
     }
     return(false);
 }
        internal static bool Emit(DynamicTypeWrapper.FinishContext context, ClassFile classFile, int constantPoolIndex, ClassFile.ConstantPoolItemInvokeDynamic cpi, CodeEmitter ilgen)
        {
#if !WINRT
            ClassFile.BootstrapMethod bsm = classFile.GetBootstrapMethod(cpi.BootstrapMethod);
            if (!IsLambdaMetafactory(classFile, bsm) && !IsLambdaAltMetafactory(classFile, bsm))
            {
                return(false);
            }
            LambdaMetafactory lmf = context.GetValue <LambdaMetafactory>(constantPoolIndex);
            if (lmf.ctor == null && !lmf.EmitImpl(context, classFile, cpi, bsm, ilgen))
            {
#if STATIC_COMPILER
                if (context.TypeWrapper.GetClassLoader().DisableDynamicBinding)
                {
                    StaticCompiler.IssueMessage(Message.UnableToCreateLambdaFactory);
                }
#endif
                return(false);
            }
            ilgen.Emit(OpCodes.Newobj, lmf.ctor);
            // the CLR verification rules about type merging mean we have to explicitly cast to the interface type here
            ilgen.Emit(OpCodes.Castclass, cpi.GetRetType().TypeAsBaseType);
            return(true);
#else
            throw new NotImplementedException();
#endif
        }
        private static void AddDefaultInterfaceMethods(DynamicTypeWrapper.FinishContext context, MethodWrapper[] methodList, TypeBuilder tb)
        {
            // we use special name to hide these from Java reflection
            const MethodAttributes attr    = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final | MethodAttributes.SpecialName;
            TypeWrapperFactory     factory = context.TypeWrapper.GetClassLoader().GetTypeWrapperFactory();

            foreach (MethodWrapper mw in methodList)
            {
                if (!mw.IsAbstract)
                {
                    MethodBuilder mb = mw.GetDefineMethodHelper().DefineMethod(factory, tb, mw.Name, attr);
                    if (mw.Name != mw.RealName)
                    {
                        tb.DefineMethodOverride(mb, (MethodInfo)mw.GetMethod());
                    }
                    DynamicTypeWrapper.FinishContext.EmitCallDefaultInterfaceMethod(mb, mw);
                }
                else if (IsObjectMethod(mw))
                {
                    MethodBuilder mb = mw.GetDefineMethodHelper().DefineMethod(factory, tb, mw.Name, attr);
                    if (mw.Name != mw.RealName)
                    {
                        tb.DefineMethodOverride(mb, (MethodInfo)mw.GetMethod());
                    }
                    CodeEmitter ilgen = CodeEmitter.Create(mb);
                    for (int i = 0, count = mw.GetParameters().Length; i <= count; i++)
                    {
                        ilgen.EmitLdarg(i);
                    }
                    CoreClasses.java.lang.Object.Wrapper.GetMethodWrapper(mw.Name, mw.Signature, false).EmitCallvirt(ilgen);
                    ilgen.Emit(OpCodes.Ret);
                    ilgen.DoEmit();
                }
            }
        }
Exemple #5
0
        private static bool ThreadLocal_new(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
        {
            // it is only valid to replace a ThreadLocal instantiation by our ThreadStatic based version, if we can prove that the instantiation only happens once
            // (which is the case when we're in <clinit> and there aren't any branches that lead to the current position)
            if (caller.Name != StringConstants.CLINIT)
            {
                return(false);
            }
#if CLASSGC
            if (JVM.classUnloading)
            {
                // RunAndCollect assemblies do not support ThreadStaticAttribute
                return(false);
            }
#endif
            for (int i = 0; i <= opcodeIndex; i++)
            {
                if ((flags[i] & InstructionFlags.BranchTarget) != 0)
                {
                    return(false);
                }
            }
            ilgen.Emit(OpCodes.Newobj, DefineThreadLocalType(context, opcodeIndex, caller));
            return(true);
        }
Exemple #6
0
        private static ConstructorBuilder DefineThreadLocalType(DynamicTypeWrapper.FinishContext context, int opcodeIndex, MethodWrapper caller)
        {
            TypeWrapper  threadLocal = ClassLoaderWrapper.LoadClassCritical("ikvm.internal.IntrinsicThreadLocal");
            TypeBuilder  tb          = caller.DeclaringType.TypeAsBuilder.DefineNestedType("__<tls>_" + opcodeIndex, TypeAttributes.NestedPrivate | TypeAttributes.Sealed, threadLocal.TypeAsBaseType);
            FieldBuilder fb          = tb.DefineField("field", Types.Object, FieldAttributes.Private | FieldAttributes.Static);

            fb.SetCustomAttribute(new CustomAttributeBuilder(JVM.Import(typeof(ThreadStaticAttribute)).GetConstructor(Type.EmptyTypes), new object[0]));
            MethodBuilder mbGet = tb.DefineMethod("get", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final, Types.Object, Type.EmptyTypes);
            ILGenerator   ilgen = mbGet.GetILGenerator();

            ilgen.Emit(OpCodes.Ldsfld, fb);
            ilgen.Emit(OpCodes.Ret);
            MethodBuilder mbSet = tb.DefineMethod("set", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final, null, new Type[] { Types.Object });

            ilgen = mbSet.GetILGenerator();
            ilgen.Emit(OpCodes.Ldarg_1);
            ilgen.Emit(OpCodes.Stsfld, fb);
            ilgen.Emit(OpCodes.Ret);
            ConstructorBuilder cb        = tb.DefineConstructor(MethodAttributes.Assembly, CallingConventions.Standard, Type.EmptyTypes);
            CodeEmitter        ctorilgen = CodeEmitter.Create(cb);

            ctorilgen.Emit(OpCodes.Ldarg_0);
            MethodWrapper basector = threadLocal.GetMethodWrapper("<init>", "()V", false);

            basector.Link();
            basector.EmitCall(ctorilgen);
            ctorilgen.Emit(OpCodes.Ret);
            ctorilgen.DoEmit();
            context.RegisterPostFinishProc(delegate
            {
                threadLocal.Finish();
                tb.CreateType();
            });
            return(cb);
        }
Exemple #7
0
        private static bool System_arraycopy(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
        {
            // if the array arguments on the stack are of a known array type, we can redirect to an optimized version of arraycopy.
            // Note that we also have to handle VMSystem.arraycopy, because on GNU Classpath StringBuffer directly calls
            // this method to avoid prematurely initialising System.
            TypeWrapper dst_type = ma.GetStackTypeWrapper(opcodeIndex, 2);
            TypeWrapper src_type = ma.GetStackTypeWrapper(opcodeIndex, 4);

            if (!dst_type.IsUnloadable && dst_type.IsArray && dst_type == src_type)
            {
                switch (dst_type.Name[1])
                {
                case 'J':
                case 'D':
                    ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.arraycopy_primitive_8);
                    break;

                case 'I':
                case 'F':
                    ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.arraycopy_primitive_4);
                    break;

                case 'S':
                case 'C':
                    ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.arraycopy_primitive_2);
                    break;

                case 'B':
                case 'Z':
                    ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.arraycopy_primitive_1);
                    break;

                default:
                    // TODO once the verifier tracks actual types (i.e. it knows that
                    // a particular reference is the result of a "new" opcode) we can
                    // use the fast version if the exact destination type is known
                    // (in that case the "dst_type == src_type" above should
                    // be changed to "src_type.IsAssignableTo(dst_type)".
                    TypeWrapper elemtw = dst_type.ElementTypeWrapper;
                    // note that IsFinal returns true for array types, so we have to be careful!
                    if (!elemtw.IsArray && elemtw.IsFinal)
                    {
                        ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.arraycopy_fast);
                    }
                    else
                    {
                        ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.arraycopy);
                    }
                    break;
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #8
0
        private static bool Class_getPrimitiveClass(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
        {
            ilgen.LazyEmitPop();
            ilgen.Emit(OpCodes.Ldnull);
            MethodWrapper mw = CoreClasses.java.lang.Class.Wrapper.GetMethodWrapper("<init>", "(Lcli.System.Type;)V", false);

            mw.Link();
            mw.EmitNewobj(ilgen);
            return(true);
        }
Exemple #9
0
 internal EmitIntrinsicContext(MethodWrapper method, DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, CodeInfo ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     this.Method      = method;
     this.Context     = context;
     this.Emitter     = ilgen;
     this.ma          = ma;
     this.OpcodeIndex = opcodeIndex;
     this.Caller      = caller;
     this.ClassFile   = classFile;
     this.Code        = code;
     this.Flags       = flags;
 }
Exemple #10
0
        private static bool Class_desiredAssertionStatus(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
        {
            TypeWrapper classLiteral = ilgen.PeekLazyClassLiteral();

            if (classLiteral != null && classLiteral.GetClassLoader().RemoveAsserts)
            {
                ilgen.LazyEmitPop();
                ilgen.LazyEmitLdc_I4(0);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #11
0
        private static bool String_toCharArray(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
        {
            string str = ilgen.PopLazyLdstr();

            if (str != null)
            {
                // arbitrary length for "big" strings
                if (str.Length > 128)
                {
                    EmitLoadCharArrayLiteral(ilgen, str, caller.DeclaringType);
                    return(true);
                }
                ilgen.Emit(OpCodes.Ldstr, str);
            }
            return(false);
        }
Exemple #12
0
 private static bool ClassLoader_getCallerClassLoader(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     if (caller.HasCallerID)
     {
         int arg = caller.GetParametersForDefineMethod().Length - 1;
         if (!caller.IsStatic)
         {
             arg++;
         }
         ilgen.Emit(OpCodes.Ldarg, (short)arg);
         MethodWrapper mw = [email protected]("getCallerClassLoader", "()Ljava.lang.ClassLoader;", false);
         mw.Link();
         mw.EmitCallvirt(ilgen);
         return(true);
     }
     return(false);
 }
Exemple #13
0
 private static bool CallerID_getCallerID(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     if (caller.HasCallerID)
     {
         int arg = caller.GetParametersForDefineMethod().Length - 1;
         if (!caller.IsStatic)
         {
             arg++;
         }
         ilgen.Emit(OpCodes.Ldarg, (short)arg);
         return(true);
     }
     else
     {
         JVM.CriticalFailure("CallerID.getCallerID() requires a HasCallerID annotation", null);
     }
     return(false);
 }
Exemple #14
0
        private static bool Util_getInstanceTypeFromClass(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
        {
            TypeWrapper tw = ilgen.PeekLazyClassLiteral();

            if (tw != null)
            {
                ilgen.LazyEmitPop();
                if (tw.IsRemapped && tw.IsFinal)
                {
                    ilgen.Emit(OpCodes.Ldtoken, tw.TypeAsTBD);
                }
                else
                {
                    ilgen.Emit(OpCodes.Ldtoken, tw.TypeAsBaseType);
                }
                ilgen.Emit(OpCodes.Call, Compiler.getTypeFromHandleMethod);
                return(true);
            }
            return(false);
        }
Exemple #15
0
    private static void DoEmit(DynamicTypeWrapper.FinishContext context, TypeWrapper wrapper, CodeEmitter ilgen, FieldWrapper field)
    {
        ConstructorBuilder cb;
        bool exists;

        lock (map)
        {
            exists = map.TryGetValue(field, out cb);
        }
        if (!exists)
        {
            // note that we don't need to lock here, because we're running as part of FinishCore, which is already protected by a lock
            TypeWrapper arfuTypeWrapper = ClassLoaderWrapper.LoadClassCritical("ikvm.internal.IntrinsicAtomicReferenceFieldUpdater");
            TypeBuilder tb = wrapper.TypeAsBuilder.DefineNestedType("__<ARFU>_" + field.Name + field.Signature.Replace('.', '/'), TypeAttributes.NestedPrivate | TypeAttributes.Sealed, arfuTypeWrapper.TypeAsBaseType);
            EmitCompareAndSet("compareAndSet", tb, field.GetField());
            EmitGet(tb, field.GetField());
            EmitSet("set", tb, field.GetField());

            cb = tb.DefineConstructor(MethodAttributes.Assembly, CallingConventions.Standard, Type.EmptyTypes);
            lock (map)
            {
                map.Add(field, cb);
            }
            CodeEmitter ctorilgen = CodeEmitter.Create(cb);
            ctorilgen.Emit(OpCodes.Ldarg_0);
            MethodWrapper basector = arfuTypeWrapper.GetMethodWrapper("<init>", "()V", false);
            basector.Link();
            basector.EmitCall(ctorilgen);
            ctorilgen.Emit(OpCodes.Ret);
            ctorilgen.DoEmit();
            context.RegisterPostFinishProc(delegate
            {
                arfuTypeWrapper.Finish();
                tb.CreateType();
            });
        }
        ilgen.Emit(OpCodes.Pop);
        ilgen.Emit(OpCodes.Pop);
        ilgen.Emit(OpCodes.Pop);
        ilgen.Emit(OpCodes.Newobj, cb);
    }
Exemple #16
0
 private static bool Reflection_getCallerClass(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     if (caller.HasCallerID &&
         opcodeIndex > 0 &&
         (flags[opcodeIndex - 1] & InstructionFlags.BranchTarget) == 0 &&
         code[opcodeIndex - 1].NormalizedOpCode == NormalizedByteCode.__iconst &&
         code[opcodeIndex - 1].Arg1 == 2)
     {
         ilgen.LazyEmitPop();
         int arg = caller.GetParametersForDefineMethod().Length - 1;
         if (!caller.IsStatic)
         {
             arg++;
         }
         ilgen.Emit(OpCodes.Ldarg, (short)arg);
         MethodWrapper mw = [email protected]("getCallerClass", "()Ljava.lang.Class;", false);
         mw.Link();
         mw.EmitCallvirt(ilgen);
         return(true);
     }
     return(false);
 }
Exemple #17
0
 internal static bool Emit(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     // note that intrinsics can always refuse to emit code and the code generator will fall back to a normal method call
     return(intrinsics[new IntrinsicKey(method)](context, ilgen, method, ma, opcodeIndex, caller, classFile, code, flags));
 }
Exemple #18
0
 private static bool Float_floatToRawIntBits(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     EmitConversion(ilgen, typeofFloatConverter, "ToInt");
     return(true);
 }
Exemple #19
0
 private static bool Double_longBitsToDouble(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     EmitConversion(ilgen, typeofDoubleConverter, "ToDouble");
     return(true);
 }
Exemple #20
0
 private static bool AtomicReferenceFieldUpdater_newUpdater(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     return(AtomicReferenceFieldUpdaterEmitter.Emit(context, caller.DeclaringType, ilgen, classFile, opcodeIndex, code, flags));
 }
        private bool EmitImpl(DynamicTypeWrapper.FinishContext context, ClassFile classFile, ClassFile.ConstantPoolItemInvokeDynamic cpi, ClassFile.BootstrapMethod bsm, CodeEmitter ilgen)
        {
            if (HasUnloadable(cpi))
            {
                Fail("cpi has unloadable");
                return(false);
            }
            bool serializable = false;

            TypeWrapper[] markers = TypeWrapper.EmptyArray;
            ClassFile.ConstantPoolItemMethodType[] bridges = null;
            if (bsm.ArgumentCount > 3)
            {
                AltFlags flags = (AltFlags)classFile.GetConstantPoolConstantInteger(bsm.GetArgument(3));
                serializable = (flags & AltFlags.Serializable) != 0;
                int argpos = 4;
                if ((flags & AltFlags.Markers) != 0)
                {
                    markers = new TypeWrapper[classFile.GetConstantPoolConstantInteger(bsm.GetArgument(argpos++))];
                    for (int i = 0; i < markers.Length; i++)
                    {
                        if ((markers[i] = classFile.GetConstantPoolClassType(bsm.GetArgument(argpos++))).IsUnloadable)
                        {
                            Fail("unloadable marker");
                            return(false);
                        }
                    }
                }
                if ((flags & AltFlags.Bridges) != 0)
                {
                    bridges = new ClassFile.ConstantPoolItemMethodType[classFile.GetConstantPoolConstantInteger(bsm.GetArgument(argpos++))];
                    for (int i = 0; i < bridges.Length; i++)
                    {
                        bridges[i] = classFile.GetConstantPoolConstantMethodType(bsm.GetArgument(argpos++));
                        if (HasUnloadable(bridges[i]))
                        {
                            Fail("unloadable bridge");
                            return(false);
                        }
                    }
                }
            }
            ClassFile.ConstantPoolItemMethodType   samMethodType          = classFile.GetConstantPoolConstantMethodType(bsm.GetArgument(0));
            ClassFile.ConstantPoolItemMethodHandle implMethod             = classFile.GetConstantPoolConstantMethodHandle(bsm.GetArgument(1));
            ClassFile.ConstantPoolItemMethodType   instantiatedMethodType = classFile.GetConstantPoolConstantMethodType(bsm.GetArgument(2));
            if (HasUnloadable(samMethodType) ||
                HasUnloadable((ClassFile.ConstantPoolItemMI)implMethod.MemberConstantPoolItem) ||
                HasUnloadable(instantiatedMethodType))
            {
                Fail("bsm args has unloadable");
                return(false);
            }
            TypeWrapper interfaceType = cpi.GetRetType();

            MethodWrapper[] methodList;
            if (!CheckSupportedInterfaces(context.TypeWrapper, interfaceType, markers, bridges, out methodList))
            {
                Fail("unsupported interface");
                return(false);
            }
            if (serializable && Array.Exists(methodList, delegate(MethodWrapper mw) { return(mw.Name == "writeReplace" && mw.Signature == "()Ljava.lang.Object;"); }))
            {
                Fail("writeReplace");
                return(false);
            }
            if (!IsSupportedImplMethod(implMethod, context.TypeWrapper, cpi.GetArgTypes(), instantiatedMethodType))
            {
                Fail("implMethod " + implMethod.MemberConstantPoolItem.Class + "::" + implMethod.MemberConstantPoolItem.Name + implMethod.MemberConstantPoolItem.Signature);
                return(false);
            }
            TypeWrapper[] implParameters = GetImplParameters(implMethod);
            CheckConstraints(instantiatedMethodType, samMethodType, cpi.GetArgTypes(), implParameters);
            if (bridges != null)
            {
                foreach (ClassFile.ConstantPoolItemMethodType bridge in bridges)
                {
                    if (bridge.Signature == samMethodType.Signature)
                    {
                        Fail("bridge signature matches sam");
                        return(false);
                    }
                    if (!CheckConstraints(instantiatedMethodType, bridge, cpi.GetArgTypes(), implParameters))
                    {
                        Fail("bridge constraints");
                        return(false);
                    }
                }
            }
            if (instantiatedMethodType.GetRetType() != PrimitiveTypeWrapper.VOID)
            {
                TypeWrapper Rt = instantiatedMethodType.GetRetType();
                TypeWrapper Ra = GetImplReturnType(implMethod);
                if (Ra == PrimitiveTypeWrapper.VOID || !IsAdaptable(Ra, Rt, true))
                {
                    Fail("The return type Rt is void, or the return type Ra is not void and is adaptable to Rt");
                    return(false);
                }
            }
            MethodWrapper        interfaceMethod = null;
            List <MethodWrapper> methods         = new List <MethodWrapper>();

            foreach (MethodWrapper mw in methodList)
            {
                if (mw.Name == cpi.Name && mw.Signature == samMethodType.Signature)
                {
                    interfaceMethod = mw;
                    methods.Add(mw);
                }
                else if (mw.IsAbstract && !IsObjectMethod(mw))
                {
                    methods.Add(mw);
                }
            }
            if (interfaceMethod == null || !interfaceMethod.IsAbstract || IsObjectMethod(interfaceMethod) || !MatchSignatures(interfaceMethod, samMethodType))
            {
                Fail("interfaceMethod");
                return(false);
            }

            TypeBuilder tb = context.DefineAnonymousClass();

            // we're not implementing the interfaces recursively (because we don't care about .NET Compact anymore),
            // but should we decide to do that, we'd need to somehow communicate to AnonymousTypeWrapper what the 'real' interface is
            tb.AddInterfaceImplementation(interfaceType.TypeAsBaseType);
            if (serializable && Array.IndexOf(markers, CoreClasses.java.io.Serializable.Wrapper) == -1)
            {
                tb.AddInterfaceImplementation(CoreClasses.java.io.Serializable.Wrapper.TypeAsBaseType);
            }
            foreach (TypeWrapper marker in markers)
            {
                tb.AddInterfaceImplementation(marker.TypeAsBaseType);
            }
            ctor = CreateConstructorAndDispatch(context, cpi, tb, methods, implParameters, samMethodType, implMethod, instantiatedMethodType, serializable);
            AddDefaultInterfaceMethods(context, methodList, tb);
            return(true);
        }
        private static void EmitDispatch(DynamicTypeWrapper.FinishContext context, TypeWrapper[] args, TypeBuilder tb, MethodWrapper interfaceMethod, TypeWrapper[] implParameters,
                                         ClassFile.ConstantPoolItemMethodHandle implMethod, ClassFile.ConstantPoolItemMethodType instantiatedMethodType, FieldBuilder[] capturedFields)
        {
            MethodBuilder mb = interfaceMethod.GetDefineMethodHelper().DefineMethod(context.TypeWrapper, tb, interfaceMethod.Name, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final);

            if (interfaceMethod.Name != interfaceMethod.RealName)
            {
                tb.DefineMethodOverride(mb, (MethodInfo)interfaceMethod.GetMethod());
            }
            CodeEmitter ilgen = CodeEmitter.Create(mb);

            for (int i = 0; i < capturedFields.Length; i++)
            {
                ilgen.EmitLdarg(0);
                OpCode opc = OpCodes.Ldfld;
                if (i == 0 && args[0].IsGhost)
                {
                    switch (implMethod.Kind)
                    {
                    case ClassFile.RefKind.invokeInterface:
                    case ClassFile.RefKind.invokeVirtual:
                    case ClassFile.RefKind.invokeSpecial:
                        opc = OpCodes.Ldflda;
                        break;
                    }
                }
                ilgen.Emit(opc, capturedFields[i]);
            }
            for (int i = 0, count = interfaceMethod.GetParameters().Length, k = capturedFields.Length; i < count; i++)
            {
                ilgen.EmitLdarg(i + 1);
                TypeWrapper Ui = interfaceMethod.GetParameters()[i];
                TypeWrapper Ti = instantiatedMethodType.GetArgTypes()[i];
                TypeWrapper Aj = implParameters[i + k];
                if (Ui == PrimitiveTypeWrapper.BYTE)
                {
                    ilgen.Emit(OpCodes.Conv_I1);
                }
                if (Ti != Ui)
                {
                    if (Ti.IsGhost)
                    {
                        Ti.EmitConvStackTypeToSignatureType(ilgen, Ui);
                    }
                    else if (Ui.IsGhost)
                    {
                        Ui.EmitConvSignatureTypeToStackType(ilgen);
                    }
                    else
                    {
                        Ti.EmitCheckcast(ilgen);
                    }
                }
                if (Ti != Aj)
                {
                    if (Ti.IsPrimitive && !Aj.IsPrimitive)
                    {
                        Boxer.EmitBox(ilgen, Ti);
                    }
                    else if (!Ti.IsPrimitive && Aj.IsPrimitive)
                    {
                        TypeWrapper primitive = GetPrimitiveFromWrapper(Ti);
                        Boxer.EmitUnbox(ilgen, primitive, false);
                        if (primitive == PrimitiveTypeWrapper.BYTE)
                        {
                            ilgen.Emit(OpCodes.Conv_I1);
                        }
                    }
                    else if (Aj == PrimitiveTypeWrapper.LONG)
                    {
                        ilgen.Emit(OpCodes.Conv_I8);
                    }
                    else if (Aj == PrimitiveTypeWrapper.FLOAT)
                    {
                        ilgen.Emit(OpCodes.Conv_R4);
                    }
                    else if (Aj == PrimitiveTypeWrapper.DOUBLE)
                    {
                        ilgen.Emit(OpCodes.Conv_R8);
                    }
                }
            }
            switch (implMethod.Kind)
            {
            case ClassFile.RefKind.invokeVirtual:
            case ClassFile.RefKind.invokeInterface:
                ((MethodWrapper)implMethod.Member).EmitCallvirt(ilgen);
                break;

            case ClassFile.RefKind.newInvokeSpecial:
                ((MethodWrapper)implMethod.Member).EmitNewobj(ilgen);
                break;

            case ClassFile.RefKind.invokeStatic:
            case ClassFile.RefKind.invokeSpecial:
                ((MethodWrapper)implMethod.Member).EmitCall(ilgen);
                break;

            default:
                throw new InvalidOperationException();
            }
            TypeWrapper Ru = interfaceMethod.ReturnType;
            TypeWrapper Ra = GetImplReturnType(implMethod);
            TypeWrapper Rt = instantiatedMethodType.GetRetType();

            if (Ra == PrimitiveTypeWrapper.BYTE)
            {
                ilgen.Emit(OpCodes.Conv_I1);
            }
            if (Ra != Ru)
            {
                if (Ru == PrimitiveTypeWrapper.VOID)
                {
                    ilgen.Emit(OpCodes.Pop);
                }
                else if (Ra.IsGhost)
                {
                    Ra.EmitConvSignatureTypeToStackType(ilgen);
                }
                else if (Ru.IsGhost)
                {
                    Ru.EmitConvStackTypeToSignatureType(ilgen, Ra);
                }
            }
            if (Ra != Rt)
            {
                if (Rt.IsPrimitive)
                {
                    if (Rt == PrimitiveTypeWrapper.VOID)
                    {
                        // already popped
                    }
                    else if (!Ra.IsPrimitive)
                    {
                        TypeWrapper primitive = GetPrimitiveFromWrapper(Ra);
                        if (primitive != null)
                        {
                            Boxer.EmitUnbox(ilgen, primitive, false);
                        }
                        else
                        {
                            // If Q is not a primitive wrapper, cast Q to the base Wrapper(S); for example Number for numeric types
                            EmitConvertingUnbox(ilgen, Rt);
                        }
                    }
                    else if (Rt == PrimitiveTypeWrapper.LONG)
                    {
                        ilgen.Emit(OpCodes.Conv_I8);
                    }
                    else if (Rt == PrimitiveTypeWrapper.FLOAT)
                    {
                        ilgen.Emit(OpCodes.Conv_R4);
                    }
                    else if (Rt == PrimitiveTypeWrapper.DOUBLE)
                    {
                        ilgen.Emit(OpCodes.Conv_R8);
                    }
                }
                else if (Ra.IsPrimitive)
                {
                    Boxer.EmitBox(ilgen, GetPrimitiveFromWrapper(Rt));
                }
                else
                {
                    Rt.EmitCheckcast(ilgen);
                }
            }
            ilgen.EmitTailCallPrevention();
            ilgen.Emit(OpCodes.Ret);
            ilgen.DoEmit();
        }
        private static MethodBuilder CreateConstructorAndDispatch(DynamicTypeWrapper.FinishContext context, ClassFile.ConstantPoolItemInvokeDynamic cpi, TypeBuilder tb,
                                                                  List <MethodWrapper> methods, TypeWrapper[] implParameters, ClassFile.ConstantPoolItemMethodType samMethodType, ClassFile.ConstantPoolItemMethodHandle implMethod,
                                                                  ClassFile.ConstantPoolItemMethodType instantiatedMethodType, bool serializable)
        {
            TypeWrapper[] args = cpi.GetArgTypes();

            // captured values
            Type[]         capturedTypes  = new Type[args.Length];
            FieldBuilder[] capturedFields = new FieldBuilder[capturedTypes.Length];
            for (int i = 0; i < capturedTypes.Length; i++)
            {
                capturedTypes[i] = args[i].TypeAsSignatureType;
                FieldAttributes attr = FieldAttributes.Private;
                if (i > 0 || !args[0].IsGhost)
                {
                    attr |= FieldAttributes.InitOnly;
                }
                capturedFields[i] = tb.DefineField("arg$" + (i + 1), capturedTypes[i], attr);
            }

            // constructor
            MethodBuilder ctor  = ReflectUtil.DefineConstructor(tb, MethodAttributes.Assembly, capturedTypes);
            CodeEmitter   ilgen = CodeEmitter.Create(ctor);

            ilgen.Emit(OpCodes.Ldarg_0);
            ilgen.Emit(OpCodes.Call, Types.Object.GetConstructor(Type.EmptyTypes));
            for (int i = 0; i < capturedTypes.Length; i++)
            {
                ilgen.EmitLdarg(0);
                ilgen.EmitLdarg(i + 1);
                ilgen.Emit(OpCodes.Stfld, capturedFields[i]);
            }
            ilgen.Emit(OpCodes.Ret);
            ilgen.DoEmit();

            // dispatch methods
            foreach (MethodWrapper mw in methods)
            {
                EmitDispatch(context, args, tb, mw, implParameters, implMethod, instantiatedMethodType, capturedFields);
            }

            // writeReplace method
            if (serializable)
            {
                MethodBuilder writeReplace = tb.DefineMethod("writeReplace", MethodAttributes.Private, Types.Object, Type.EmptyTypes);
                ilgen = CodeEmitter.Create(writeReplace);
                context.TypeWrapper.EmitClassLiteral(ilgen);
                ilgen.Emit(OpCodes.Ldstr, cpi.GetRetType().Name.Replace('.', '/'));
                ilgen.Emit(OpCodes.Ldstr, cpi.Name);
                ilgen.Emit(OpCodes.Ldstr, samMethodType.Signature.Replace('.', '/'));
                ilgen.EmitLdc_I4((int)implMethod.Kind);
                ilgen.Emit(OpCodes.Ldstr, implMethod.Class.Replace('.', '/'));
                ilgen.Emit(OpCodes.Ldstr, implMethod.Name);
                ilgen.Emit(OpCodes.Ldstr, implMethod.Signature.Replace('.', '/'));
                ilgen.Emit(OpCodes.Ldstr, instantiatedMethodType.Signature.Replace('.', '/'));
                ilgen.EmitLdc_I4(capturedFields.Length);
                ilgen.Emit(OpCodes.Newarr, Types.Object);
                for (int i = 0; i < capturedFields.Length; i++)
                {
                    ilgen.Emit(OpCodes.Dup);
                    ilgen.EmitLdc_I4(i);
                    ilgen.EmitLdarg(0);
                    ilgen.Emit(OpCodes.Ldfld, capturedFields[i]);
                    if (args[i].IsPrimitive)
                    {
                        Boxer.EmitBox(ilgen, args[i]);
                    }
                    else if (args[i].IsGhost)
                    {
                        args[i].EmitConvSignatureTypeToStackType(ilgen);
                    }
                    ilgen.Emit(OpCodes.Stelem, Types.Object);
                }
                MethodWrapper ctorSerializedLambda = ClassLoaderWrapper.LoadClassCritical("java.lang.invoke.SerializedLambda").GetMethodWrapper(StringConstants.INIT,
                                                                                                                                                "(Ljava.lang.Class;Ljava.lang.String;Ljava.lang.String;Ljava.lang.String;ILjava.lang.String;Ljava.lang.String;Ljava.lang.String;Ljava.lang.String;[Ljava.lang.Object;)V", false);
                ctorSerializedLambda.Link();
                ctorSerializedLambda.EmitNewobj(ilgen);
                ilgen.Emit(OpCodes.Ret);
                ilgen.DoEmit();

                if (!context.TypeWrapper.GetClassLoader().NoAutomagicSerialization)
                {
                    // add .NET serialization interop support
                    Serialization.MarkSerializable(tb);
                    Serialization.AddGetObjectData(tb);
                }
            }

            return(ctor);
        }