001    /*
002     * Copyright 2010-2016 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.kotlin.codegen;
018    
019    import com.intellij.psi.tree.IElementType;
020    import kotlin.Unit;
021    import kotlin.collections.ArraysKt;
022    import kotlin.collections.CollectionsKt;
023    import kotlin.jvm.functions.Function1;
024    import org.jetbrains.annotations.Contract;
025    import org.jetbrains.annotations.NotNull;
026    import org.jetbrains.annotations.Nullable;
027    import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
028    import org.jetbrains.kotlin.builtins.PrimitiveType;
029    import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods;
030    import org.jetbrains.kotlin.codegen.intrinsics.JavaClassProperty;
031    import org.jetbrains.kotlin.codegen.state.GenerationState;
032    import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
033    import org.jetbrains.kotlin.descriptors.*;
034    import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor;
035    import org.jetbrains.kotlin.load.java.JvmAbi;
036    import org.jetbrains.kotlin.psi.KtExpression;
037    import org.jetbrains.kotlin.psi.ValueArgument;
038    import org.jetbrains.kotlin.resolve.BindingContext;
039    import org.jetbrains.kotlin.resolve.DescriptorUtils;
040    import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor;
041    import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument;
042    import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
043    import org.jetbrains.kotlin.resolve.calls.model.ResolvedValueArgument;
044    import org.jetbrains.kotlin.resolve.constants.ConstantValue;
045    import org.jetbrains.kotlin.resolve.jvm.AsmTypes;
046    import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterKind;
047    import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature;
048    import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
049    import org.jetbrains.kotlin.types.KotlinType;
050    import org.jetbrains.org.objectweb.asm.Label;
051    import org.jetbrains.org.objectweb.asm.Type;
052    import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
053    
054    import java.util.List;
055    
056    import static org.jetbrains.kotlin.codegen.AsmUtil.*;
057    import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
058    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
059    
060    public abstract class StackValue {
061    
062        private static final String NULLABLE_BYTE_TYPE_NAME = "java/lang/Byte";
063        private static final String NULLABLE_SHORT_TYPE_NAME = "java/lang/Short";
064        private static final String NULLABLE_LONG_TYPE_NAME = "java/lang/Long";
065    
066        public static final StackValue.Local LOCAL_0 = local(0, OBJECT_TYPE);
067        private static final StackValue UNIT = operation(UNIT_TYPE, new Function1<InstructionAdapter, Unit>() {
068            @Override
069            public Unit invoke(InstructionAdapter v) {
070                v.visitFieldInsn(GETSTATIC, UNIT_TYPE.getInternalName(), JvmAbi.INSTANCE_FIELD, UNIT_TYPE.getDescriptor());
071                return null;
072            }
073        });
074    
075        @NotNull
076        public final Type type;
077        private final boolean canHaveSideEffects;
078    
079        protected StackValue(@NotNull Type type) {
080            this(type, true);
081        }
082    
083        protected StackValue(@NotNull Type type, boolean canHaveSideEffects) {
084            this.type = type;
085            this.canHaveSideEffects = canHaveSideEffects;
086        }
087    
088        /**
089         * This method is called to put the value on the top of the JVM stack if <code>depth</code> other values have been put on the
090         * JVM stack after this value was generated.
091         *
092         * @param type  the type as which the value should be put
093         * @param v     the visitor used to genClassOrObject the instructions
094         * @param depth the number of new values put onto the stack
095         */
096        public void moveToTopOfStack(@NotNull Type type, @NotNull InstructionAdapter v, int depth) {
097            put(type, v);
098        }
099    
100        public void put(@NotNull Type type, @NotNull InstructionAdapter v) {
101            put(type, v, false);
102        }
103    
104        public void put(@NotNull Type type, @NotNull InstructionAdapter v, boolean skipReceiver) {
105            if (!skipReceiver) {
106                putReceiver(v, true);
107            }
108            putSelector(type, v);
109        }
110    
111        public abstract void putSelector(@NotNull Type type, @NotNull InstructionAdapter v);
112    
113        public boolean isNonStaticAccess(boolean isRead) {
114            return false;
115        }
116    
117    
118        public void putReceiver(@NotNull InstructionAdapter v, boolean isRead) {
119            //by default there is no receiver
120            //if you have it inherit StackValueWithSimpleReceiver
121        }
122    
123        public void dup(@NotNull InstructionAdapter v, boolean withReceiver) {
124            if (!Type.VOID_TYPE.equals(type)) {
125                AsmUtil.dup(v, type);
126            }
127        }
128    
129        public void store(@NotNull StackValue value, @NotNull InstructionAdapter v) {
130            store(value, v, false);
131        }
132    
133        public boolean canHaveSideEffects() {
134            return canHaveSideEffects;
135        }
136    
137        public void store(@NotNull StackValue value, @NotNull InstructionAdapter v, boolean skipReceiver) {
138            if (!skipReceiver) {
139                putReceiver(v, false);
140            }
141            value.put(value.type, v);
142            storeSelector(value.type, v);
143        }
144    
145        protected void storeSelector(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
146            throw new UnsupportedOperationException("Cannot store to value " + this);
147        }
148    
149        @NotNull
150        public static Local local(int index, @NotNull Type type) {
151            return new Local(index, type);
152        }
153    
154        @NotNull
155        public static Delegate delegate(
156                @NotNull Type type,
157                @NotNull StackValue delegateValue,
158                @NotNull StackValue metadataValue,
159                @NotNull VariableDescriptorWithAccessors variableDescriptor,
160                @NotNull ExpressionCodegen codegen
161        ) {
162            return new Delegate(type, delegateValue, metadataValue, variableDescriptor, codegen);
163        }
164    
165        @NotNull
166        public static StackValue shared(int index, @NotNull Type type) {
167            return new Shared(index, type);
168        }
169    
170        @NotNull
171        public static StackValue onStack(@NotNull Type type) {
172            return type == Type.VOID_TYPE ? none() : new OnStack(type);
173        }
174    
175        @NotNull
176        public static StackValue constant(@Nullable Object value, @NotNull Type type) {
177            if (type == Type.BOOLEAN_TYPE) {
178                assert value instanceof Boolean : "Value for boolean constant should have boolean type: " + value;
179                return BranchedValue.Companion.booleanConstant((Boolean) value);
180            }
181            else {
182                return new Constant(value, type);
183            }
184        }
185    
186        @NotNull
187        public static StackValue cmp(@NotNull IElementType opToken, @NotNull Type type, StackValue left, StackValue right) {
188            return BranchedValue.Companion.cmp(opToken, type, left, right);
189        }
190    
191        @NotNull
192        public static StackValue not(@NotNull StackValue stackValue) {
193            return BranchedValue.Companion.createInvertValue(stackValue);
194        }
195    
196        public static StackValue or(@NotNull StackValue left, @NotNull StackValue right) {
197            return new Or(left, right);
198        }
199    
200        public static StackValue and(@NotNull StackValue left, @NotNull StackValue right) {
201            return new And(left, right);
202        }
203    
204        public static StackValue compareIntWithZero(@NotNull StackValue argument, int operation) {
205            return new BranchedValue(argument, null, Type.INT_TYPE, operation);
206        }
207    
208        public static StackValue compareWithNull(@NotNull StackValue argument, int operation) {
209            return new BranchedValue(argument, null, AsmTypes.OBJECT_TYPE, operation);
210        }
211    
212        @NotNull
213        public static StackValue arrayElement(@NotNull Type type, StackValue array, StackValue index) {
214            return new ArrayElement(type, array, index);
215        }
216    
217        @NotNull
218        public static StackValue collectionElement(
219                CollectionElementReceiver collectionElementReceiver,
220                Type type,
221                ResolvedCall<FunctionDescriptor> getter,
222                ResolvedCall<FunctionDescriptor> setter,
223                ExpressionCodegen codegen
224        ) {
225            return new CollectionElement(collectionElementReceiver, type, getter, setter, codegen);
226        }
227    
228        @NotNull
229        public static Field field(@NotNull Type type, @NotNull Type owner, @NotNull String name, boolean isStatic, @NotNull StackValue receiver) {
230            return field(type, owner, name, isStatic, receiver, null);
231        }
232    
233        @NotNull
234        public static Field field(
235                @NotNull Type type,
236                @NotNull Type owner,
237                @NotNull String name,
238                boolean isStatic,
239                @NotNull StackValue receiver,
240                @Nullable DeclarationDescriptor descriptor
241        ) {
242            return new Field(type, owner, name, isStatic, receiver, descriptor);
243        }
244    
245        @NotNull
246        public static Field field(@NotNull StackValue.Field field, @NotNull StackValue newReceiver) {
247            return field(field.type, field.owner, field.name, field.isStaticPut, newReceiver, field.descriptor);
248        }
249    
250        @NotNull
251        public static Field field(@NotNull FieldInfo info, @NotNull StackValue receiver) {
252            return field(info.getFieldType(), Type.getObjectType(info.getOwnerInternalName()), info.getFieldName(), info.isStatic(), receiver);
253        }
254    
255        @NotNull
256        public static StackValue changeReceiverForFieldAndSharedVar(@NotNull StackValueWithSimpleReceiver stackValue, @Nullable StackValue newReceiver) {
257            //TODO static check
258            if (newReceiver == null || stackValue.isStaticPut) return stackValue;
259            return stackValue.changeReceiver(newReceiver);
260        }
261    
262        @NotNull
263        public static Property property(
264                @NotNull PropertyDescriptor descriptor,
265                @Nullable Type backingFieldOwner,
266                @NotNull Type type,
267                boolean isStaticBackingField,
268                @Nullable String fieldName,
269                @Nullable CallableMethod getter,
270                @Nullable CallableMethod setter,
271                @NotNull StackValue receiver,
272                @NotNull ExpressionCodegen codegen,
273                @Nullable ResolvedCall resolvedCall
274        ) {
275            return new Property(descriptor, backingFieldOwner, getter, setter, isStaticBackingField, fieldName, type, receiver, codegen, resolvedCall);
276        }
277    
278        @NotNull
279        public static StackValue expression(Type type, KtExpression expression, ExpressionCodegen generator) {
280            return new Expression(type, expression, generator);
281        }
282    
283        private static void box(Type type, Type toType, InstructionAdapter v) {
284            if (type == Type.BYTE_TYPE || toType.getInternalName().equals(NULLABLE_BYTE_TYPE_NAME) && type == Type.INT_TYPE) {
285                v.cast(type, Type.BYTE_TYPE);
286                v.invokestatic(NULLABLE_BYTE_TYPE_NAME, "valueOf", "(B)L" + NULLABLE_BYTE_TYPE_NAME + ";", false);
287            }
288            else if (type == Type.SHORT_TYPE || toType.getInternalName().equals(NULLABLE_SHORT_TYPE_NAME) && type == Type.INT_TYPE) {
289                v.cast(type, Type.SHORT_TYPE);
290                v.invokestatic(NULLABLE_SHORT_TYPE_NAME, "valueOf", "(S)L" + NULLABLE_SHORT_TYPE_NAME + ";", false);
291            }
292            else if (type == Type.LONG_TYPE || toType.getInternalName().equals(NULLABLE_LONG_TYPE_NAME) && type == Type.INT_TYPE) {
293                v.cast(type, Type.LONG_TYPE);
294                v.invokestatic(NULLABLE_LONG_TYPE_NAME, "valueOf", "(J)L" + NULLABLE_LONG_TYPE_NAME + ";", false);
295            }
296            else if (type == Type.INT_TYPE) {
297                v.invokestatic("java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);
298            }
299            else if (type == Type.BOOLEAN_TYPE) {
300                v.invokestatic("java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
301            }
302            else if (type == Type.CHAR_TYPE) {
303                v.invokestatic("java/lang/Character", "valueOf", "(C)Ljava/lang/Character;", false);
304            }
305            else if (type == Type.FLOAT_TYPE) {
306                v.invokestatic("java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false);
307            }
308            else if (type == Type.DOUBLE_TYPE) {
309                v.invokestatic("java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false);
310            }
311        }
312    
313        private static void unbox(Type type, InstructionAdapter v) {
314            if (type == Type.INT_TYPE) {
315                v.invokevirtual("java/lang/Number", "intValue", "()I", false);
316            }
317            else if (type == Type.BOOLEAN_TYPE) {
318                v.invokevirtual("java/lang/Boolean", "booleanValue", "()Z", false);
319            }
320            else if (type == Type.CHAR_TYPE) {
321                v.invokevirtual("java/lang/Character", "charValue", "()C", false);
322            }
323            else if (type == Type.SHORT_TYPE) {
324                v.invokevirtual("java/lang/Number", "shortValue", "()S", false);
325            }
326            else if (type == Type.LONG_TYPE) {
327                v.invokevirtual("java/lang/Number", "longValue", "()J", false);
328            }
329            else if (type == Type.BYTE_TYPE) {
330                v.invokevirtual("java/lang/Number", "byteValue", "()B", false);
331            }
332            else if (type == Type.FLOAT_TYPE) {
333                v.invokevirtual("java/lang/Number", "floatValue", "()F", false);
334            }
335            else if (type == Type.DOUBLE_TYPE) {
336                v.invokevirtual("java/lang/Number", "doubleValue", "()D", false);
337            }
338        }
339    
340        protected void coerceTo(@NotNull Type toType, @NotNull InstructionAdapter v) {
341            coerce(this.type, toType, v);
342        }
343    
344        protected void coerceFrom(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
345            coerce(topOfStackType, this.type, v);
346        }
347    
348        public static void coerce(@NotNull Type fromType, @NotNull Type toType, @NotNull InstructionAdapter v) {
349            if (toType.equals(fromType)) return;
350    
351            if (toType.getSort() == Type.VOID) {
352                pop(v, fromType);
353            }
354            else if (fromType.getSort() == Type.VOID) {
355                if (toType.equals(UNIT_TYPE) || toType.equals(OBJECT_TYPE)) {
356                    putUnitInstance(v);
357                }
358                else if (toType.getSort() == Type.OBJECT || toType.getSort() == Type.ARRAY) {
359                    v.aconst(null);
360                }
361                else {
362                    pushDefaultPrimitiveValueOnStack(toType, v);
363                }
364            }
365            else if (toType.equals(UNIT_TYPE)) {
366                if (fromType.equals(getType(Object.class))) {
367                    v.checkcast(UNIT_TYPE);
368                }
369                else if (!fromType.equals(getType(Void.class))) {
370                    pop(v, fromType);
371                    putUnitInstance(v);
372                }
373            }
374            else if (toType.getSort() == Type.ARRAY) {
375                if (fromType.getSort() == Type.ARRAY &&
376                    fromType.getElementType().equals(AsmTypes.JAVA_CLASS_TYPE) && toType.equals(K_CLASS_ARRAY_TYPE)) {
377                    wrapJavaClassesIntoKClasses(v);
378                }
379                else {
380                    v.checkcast(toType);
381                }
382            }
383            else if (toType.getSort() == Type.OBJECT) {
384                if (fromType.getSort() == Type.OBJECT || fromType.getSort() == Type.ARRAY) {
385                    if (!toType.equals(OBJECT_TYPE)) {
386                        if (fromType.equals(AsmTypes.JAVA_CLASS_TYPE) && toType.equals(AsmTypes.K_CLASS_TYPE)) {
387                            wrapJavaClassIntoKClass(v);
388                        }
389                        else {
390                            v.checkcast(toType);
391                        }
392                    }
393                }
394                else {
395                    box(fromType, toType, v);
396                }
397            }
398            else if (fromType.getSort() == Type.OBJECT) {
399                Type unboxedType = unboxPrimitiveTypeOrNull(fromType);
400                if (unboxedType != null) {
401                    unbox(unboxedType, v);
402                    coerce(unboxedType, toType, v);
403                }
404                else {
405                    Type numberType = getType(Number.class);
406                    if (toType.getSort() == Type.BOOLEAN || (toType.getSort() == Type.CHAR && !numberType.equals(fromType))) {
407                        coerce(fromType, boxType(toType), v);
408                    }
409                    else {
410                        coerce(fromType, numberType, v);
411                    }
412                    unbox(toType, v);
413                }
414            }
415            else {
416                v.cast(fromType, toType);
417            }
418        }
419    
420        public static void putUnitInstance(@NotNull InstructionAdapter v) {
421            unit().put(UNIT_TYPE, v);
422        }
423    
424        public static StackValue unit() {
425            return UNIT;
426        }
427    
428        public static StackValue none() {
429            return None.INSTANCE;
430        }
431    
432        public static Field receiverWithRefWrapper(
433                @NotNull Type localType,
434                @NotNull Type classType,
435                @NotNull String fieldName,
436                @NotNull StackValue receiver,
437                @Nullable DeclarationDescriptor descriptor
438        ) {
439            return field(sharedTypeForType(localType), classType, fieldName, false, receiver, descriptor);
440        }
441    
442        public static FieldForSharedVar fieldForSharedVar(
443                @NotNull Type localType,
444                @NotNull Type classType,
445                @NotNull String fieldName,
446                @NotNull Field refWrapper
447        ) {
448            return new FieldForSharedVar(localType, classType, fieldName, refWrapper);
449        }
450    
451        @NotNull
452        public static FieldForSharedVar fieldForSharedVar(@NotNull FieldForSharedVar field, @NotNull StackValue newReceiver) {
453            Field oldReceiver = (Field) field.receiver;
454            Field newSharedVarReceiver = field(oldReceiver, newReceiver);
455            return new FieldForSharedVar(field.type, field.owner, field.name, newSharedVarReceiver);
456        }
457    
458        public static StackValue coercion(@NotNull StackValue value, @NotNull Type castType) {
459            if (value.type.equals(castType)) {
460                return value;
461            }
462            return new CoercionValue(value, castType);
463        }
464    
465        @NotNull
466        public static StackValue thisOrOuter(
467                @NotNull ExpressionCodegen codegen,
468                @NotNull ClassDescriptor descriptor,
469                boolean isSuper,
470                boolean castReceiver
471        ) {
472            // Coerce 'this' for the case when it is smart cast.
473            // Do not coerce for other cases due to the 'protected' access issues (JVMS 7, 4.9.2 Structural Constraints).
474            boolean coerceType = descriptor.getKind() == ClassKind.INTERFACE || (castReceiver && !isSuper);
475            return new ThisOuter(codegen, descriptor, isSuper, coerceType);
476        }
477    
478        public static StackValue postIncrement(int index, int increment) {
479            return new PostIncrement(index, increment);
480        }
481    
482        public static StackValue preIncrementForLocalVar(int index, int increment) {
483            return new PreIncrementForLocalVar(index, increment);
484        }
485    
486        public static StackValue preIncrement(
487                @NotNull Type type,
488                @NotNull StackValue stackValue,
489                int delta,
490                ResolvedCall resolvedCall,
491                @NotNull ExpressionCodegen codegen
492        ) {
493            if (stackValue instanceof StackValue.Local && Type.INT_TYPE == stackValue.type) {
494                return preIncrementForLocalVar(((StackValue.Local) stackValue).index, delta);
495            }
496            return new PrefixIncrement(type, stackValue, resolvedCall, codegen);
497        }
498    
499        public static StackValue receiver(
500                ResolvedCall<?> resolvedCall,
501                StackValue receiver,
502                ExpressionCodegen codegen,
503                @Nullable Callable callableMethod
504        ) {
505            ReceiverValue callDispatchReceiver = resolvedCall.getDispatchReceiver();
506            CallableDescriptor descriptor = resolvedCall.getResultingDescriptor();
507            if (descriptor instanceof SyntheticFieldDescriptor) {
508                callDispatchReceiver = ((SyntheticFieldDescriptor) descriptor).getDispatchReceiverForBackend();
509            }
510    
511            ReceiverValue callExtensionReceiver = resolvedCall.getExtensionReceiver();
512            if (callDispatchReceiver != null || callExtensionReceiver != null
513                || isLocalFunCall(callableMethod) || isCallToMemberObjectImportedByName(resolvedCall)) {
514                ReceiverParameterDescriptor dispatchReceiverParameter = descriptor.getDispatchReceiverParameter();
515                ReceiverParameterDescriptor extensionReceiverParameter = descriptor.getExtensionReceiverParameter();
516    
517                if (descriptor instanceof SyntheticFieldDescriptor) {
518                    dispatchReceiverParameter = ((SyntheticFieldDescriptor) descriptor).getDispatchReceiverParameterForBackend();
519                }
520    
521                boolean hasExtensionReceiver = callExtensionReceiver != null;
522                StackValue dispatchReceiver = platformStaticCallIfPresent(
523                        genReceiver(hasExtensionReceiver ? none() : receiver, codegen, resolvedCall, callableMethod, callDispatchReceiver, false),
524                        descriptor
525                );
526                StackValue extensionReceiver = genReceiver(receiver, codegen, resolvedCall, callableMethod, callExtensionReceiver, true);
527                Type type = CallReceiver.calcType(resolvedCall, dispatchReceiverParameter, extensionReceiverParameter, codegen.typeMapper, callableMethod, codegen.getState());
528                assert type != null : "Could not map receiver type for " + resolvedCall;
529                return new CallReceiver(dispatchReceiver, extensionReceiver, type);
530            }
531            return receiver;
532        }
533    
534        private static StackValue genReceiver(
535                @NotNull StackValue receiver,
536                @NotNull ExpressionCodegen codegen,
537                @NotNull ResolvedCall resolvedCall,
538                @Nullable Callable callableMethod,
539                @Nullable ReceiverValue receiverValue,
540                boolean isExtension
541        ) {
542            if (receiver == none()) {
543                if (receiverValue != null) {
544                    return codegen.generateReceiverValue(receiverValue, false);
545                }
546                else if (isLocalFunCall(callableMethod) && !isExtension) {
547                    StackValue value = codegen.findLocalOrCapturedValue(resolvedCall.getResultingDescriptor().getOriginal());
548                    assert value != null : "Local fun should be found in locals or in captured params: " + resolvedCall;
549                    return value;
550                }
551                else if (isCallToMemberObjectImportedByName(resolvedCall)) {
552                    return singleton(((ImportedFromObjectCallableDescriptor) resolvedCall.getResultingDescriptor()).getContainingObject(), codegen.typeMapper);
553                }
554            }
555            else if (receiverValue != null) {
556                return receiver;
557            }
558            return none();
559        }
560    
561        private static boolean isCallToMemberObjectImportedByName(@NotNull ResolvedCall resolvedCall) {
562            return resolvedCall.getResultingDescriptor() instanceof ImportedFromObjectCallableDescriptor;
563        }
564    
565        private static StackValue platformStaticCallIfPresent(@NotNull StackValue resultReceiver, @NotNull CallableDescriptor descriptor) {
566            if (CodegenUtilKt.isJvmStaticInObjectOrClass(descriptor)) {
567                if (resultReceiver.canHaveSideEffects()) {
568                    return coercion(resultReceiver, Type.VOID_TYPE);
569                }
570                else {
571                    return none();
572                }
573            }
574            return resultReceiver;
575        }
576    
577        @Contract("null -> false")
578        private static boolean isLocalFunCall(@Nullable Callable callableMethod) {
579            return callableMethod != null && callableMethod.getGenerateCalleeType() != null;
580        }
581    
582        public static StackValue receiverWithoutReceiverArgument(StackValue receiverWithParameter) {
583            if (receiverWithParameter instanceof CallReceiver) {
584                CallReceiver callReceiver = (CallReceiver) receiverWithParameter;
585                return new CallReceiver(callReceiver.dispatchReceiver, none(), callReceiver.type);
586            }
587            return receiverWithParameter;
588        }
589    
590        @NotNull
591        public static Field enumEntry(@NotNull ClassDescriptor descriptor, @NotNull KotlinTypeMapper typeMapper) {
592            DeclarationDescriptor enumClass = descriptor.getContainingDeclaration();
593            assert DescriptorUtils.isEnumClass(enumClass) : "Enum entry should be declared in enum class: " + descriptor;
594            Type type = typeMapper.mapType((ClassDescriptor) enumClass);
595            return field(type, type, descriptor.getName().asString(), true, none(), descriptor);
596        }
597    
598        @NotNull
599        public static Field singleton(@NotNull ClassDescriptor classDescriptor, @NotNull KotlinTypeMapper typeMapper) {
600            return field(FieldInfo.createForSingleton(classDescriptor, typeMapper), none());
601        }
602    
603        public static Field singletonViaInstance(ClassDescriptor classDescriptor, KotlinTypeMapper typeMapper) {
604            return field(FieldInfo.createSingletonViaInstance(classDescriptor, typeMapper), none());
605        }
606    
607        public static StackValue operation(Type type, Function1<InstructionAdapter, Unit> lambda) {
608            return new OperationStackValue(type, lambda);
609        }
610    
611        public static StackValue functionCall(Type type, Function1<InstructionAdapter, Unit> lambda) {
612            return new FunctionCallStackValue(type, lambda);
613        }
614    
615        public static boolean couldSkipReceiverOnStaticCall(StackValue value) {
616            return value instanceof Local || value instanceof Constant;
617        }
618    
619        private static class None extends StackValue {
620            public static final None INSTANCE = new None();
621    
622            private None() {
623                super(Type.VOID_TYPE, false);
624            }
625    
626            @Override
627            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
628                coerceTo(type, v);
629            }
630        }
631    
632        public static class Local extends StackValue {
633            public final int index;
634    
635            private Local(int index, Type type) {
636                super(type, false);
637                this.index = index;
638    
639                if (index < 0) {
640                    throw new IllegalStateException("local variable index must be non-negative");
641                }
642            }
643    
644            @Override
645            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
646                v.load(index, this.type);
647                coerceTo(type, v);
648                // TODO unbox
649            }
650    
651            @Override
652            public void storeSelector(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
653                coerceFrom(topOfStackType, v);
654                v.store(index, this.type);
655            }
656        }
657    
658        public static class Delegate extends StackValue {
659            @NotNull
660            private final StackValue delegateValue;
661            @NotNull
662            private final StackValue metadataValue;
663            @NotNull
664            private final VariableDescriptorWithAccessors variableDescriptor;
665            @NotNull
666            private final ExpressionCodegen codegen;
667    
668            private Delegate(
669                    @NotNull Type type,
670                    @NotNull StackValue delegateValue,
671                    @NotNull StackValue metadataValue,
672                    @NotNull VariableDescriptorWithAccessors variableDescriptor,
673                    @NotNull ExpressionCodegen codegen
674            ) {
675                super(type);
676                this.delegateValue = delegateValue;
677                this.metadataValue = metadataValue;
678                this.variableDescriptor = variableDescriptor;
679                this.codegen = codegen;
680            }
681    
682    
683            private ResolvedCall<FunctionDescriptor> getResolvedCall(boolean isGetter) {
684                BindingContext bindingContext = codegen.getState().getBindingContext();
685                VariableAccessorDescriptor accessor = isGetter ? variableDescriptor.getGetter(): variableDescriptor.getSetter();
686                assert accessor != null : "Accessor descriptor for delegated local property should be present " + variableDescriptor;
687                ResolvedCall<FunctionDescriptor> resolvedCall = bindingContext.get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor);
688                assert resolvedCall != null : "Resolve call should be recorded for delegate call " + variableDescriptor;
689                return resolvedCall;
690            }
691    
692            @Override
693            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
694                ResolvedCall<FunctionDescriptor> resolvedCall = getResolvedCall(true);
695                List<? extends ValueArgument> arguments = resolvedCall.getCall().getValueArguments();
696                assert arguments.size() == 2 : "Resolved call for 'getValue' should have 2 arguments, but was " +
697                                               arguments.size() + ": " + resolvedCall;
698    
699                codegen.tempVariables.put(arguments.get(0).asElement(), StackValue.constant(null, OBJECT_TYPE));
700                codegen.tempVariables.put(arguments.get(1).asElement(), metadataValue);
701                StackValue lastValue = codegen.invokeFunction(resolvedCall, delegateValue);
702                lastValue.put(type, v);
703    
704                codegen.tempVariables.remove(arguments.get(0).asElement());
705                codegen.tempVariables.remove(arguments.get(1).asElement());
706            }
707    
708            @Override
709            public void store(@NotNull StackValue rightSide, @NotNull InstructionAdapter v, boolean skipReceiver) {
710                ResolvedCall<FunctionDescriptor> resolvedCall = getResolvedCall(false);
711                List<? extends ValueArgument> arguments = resolvedCall.getCall().getValueArguments();
712                assert arguments.size() == 3 : "Resolved call for 'setValue' should have 3 arguments, but was " +
713                                               arguments.size() + ": " + resolvedCall;
714    
715                codegen.tempVariables.put(arguments.get(0).asElement(), StackValue.constant(null, OBJECT_TYPE));
716                codegen.tempVariables.put(arguments.get(1).asElement(), metadataValue);
717                codegen.tempVariables.put(arguments.get(2).asElement(), rightSide);
718                StackValue lastValue = codegen.invokeFunction(resolvedCall, delegateValue);
719                lastValue.put(Type.VOID_TYPE, v);
720    
721                codegen.tempVariables.remove(arguments.get(0).asElement());
722                codegen.tempVariables.remove(arguments.get(1).asElement());
723                codegen.tempVariables.remove(arguments.get(2).asElement());
724            }
725        }
726    
727        public static class OnStack extends StackValue {
728            public OnStack(Type type) {
729                super(type);
730            }
731    
732            @Override
733            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
734                coerceTo(type, v);
735            }
736    
737            @Override
738            public void moveToTopOfStack(@NotNull Type type, @NotNull InstructionAdapter v, int depth) {
739                if (depth == 0) {
740                    put(type, v);
741                }
742                else if (depth == 1) {
743                    int size = this.type.getSize();
744                    if (size == 1) {
745                        v.swap();
746                    }
747                    else if (size == 2) {
748                        v.dupX2();
749                        v.pop();
750                    }
751                    else {
752                        throw new UnsupportedOperationException("don't know how to move type " + type + " to top of stack");
753                    }
754    
755                    coerceTo(type, v);
756                }
757                else if (depth == 2) {
758                    int size = this.type.getSize();
759                    if (size == 1) {
760                        v.dup2X1();
761                        v.pop2();
762                    }
763                    else if (size == 2) {
764                        v.dup2X2();
765                        v.pop2();
766                    }
767                    else {
768                        throw new UnsupportedOperationException("don't know how to move type " + type + " to top of stack");
769                    }
770    
771                    coerceTo(type, v);
772                }
773                else {
774                    throw new UnsupportedOperationException("unsupported move-to-top depth " + depth);
775                }
776            }
777        }
778    
779        private static class Constant extends StackValue {
780            @Nullable
781            private final Object value;
782    
783            public Constant(@Nullable Object value, Type type) {
784                super(type, false);
785                assert !Type.BOOLEAN_TYPE.equals(type) : "Boolean constants should be created via 'StackValue.constant'";
786                this.value = value;
787            }
788    
789            @Override
790            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
791                if (value instanceof Integer || value instanceof Byte || value instanceof Short) {
792                    v.iconst(((Number) value).intValue());
793                }
794                else if (value instanceof Character) {
795                    v.iconst(((Character) value).charValue());
796                }
797                else if (value instanceof Long) {
798                    v.lconst((Long) value);
799                }
800                else if (value instanceof Float) {
801                    v.fconst((Float) value);
802                }
803                else if (value instanceof Double) {
804                    v.dconst((Double) value);
805                }
806                else {
807                    v.aconst(value);
808                }
809    
810                if (value != null || AsmUtil.isPrimitive(type)) {
811                    coerceTo(type, v);
812                }
813            }
814        }
815    
816        private static class ArrayElement extends StackValueWithSimpleReceiver {
817            private final Type type;
818    
819            public ArrayElement(Type type, StackValue array, StackValue index) {
820                super(type, false, false, new Receiver(Type.LONG_TYPE, array, index), true);
821                this.type = type;
822            }
823    
824            @Override
825            public void storeSelector(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
826                coerceFrom(topOfStackType, v);
827                v.astore(this.type);
828            }
829    
830            @Override
831            public int receiverSize() {
832                return 2;
833            }
834    
835            @Override
836            public void putSelector(
837                    @NotNull Type type, @NotNull InstructionAdapter v
838            ) {
839                v.aload(this.type);    // assumes array and index are on the stack
840                coerceTo(type, v);
841            }
842        }
843    
844        public static class CollectionElementReceiver extends StackValue {
845            private final Callable callable;
846            private final boolean isGetter;
847            private final ExpressionCodegen codegen;
848            private final List<ResolvedValueArgument> valueArguments;
849            private final FrameMap frame;
850            private final StackValue receiver;
851            private final ResolvedCall<FunctionDescriptor> resolvedGetCall;
852            private final ResolvedCall<FunctionDescriptor> resolvedSetCall;
853            private DefaultCallArgs defaultArgs;
854            private CallGenerator callGenerator;
855            boolean isComplexOperationWithDup;
856    
857            public CollectionElementReceiver(
858                    @NotNull Callable callable,
859                    @NotNull StackValue receiver,
860                    ResolvedCall<FunctionDescriptor> resolvedGetCall,
861                    ResolvedCall<FunctionDescriptor> resolvedSetCall,
862                    boolean isGetter,
863                    @NotNull ExpressionCodegen codegen,
864                    List<ResolvedValueArgument> valueArguments
865            ) {
866                super(OBJECT_TYPE);
867                this.callable = callable;
868    
869                this.isGetter = isGetter;
870                this.receiver = receiver;
871                this.resolvedGetCall = resolvedGetCall;
872                this.resolvedSetCall = resolvedSetCall;
873                this.valueArguments = valueArguments;
874                this.codegen = codegen;
875                this.frame = codegen.myFrameMap;
876            }
877    
878            @Override
879            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
880                ResolvedCall<?> call = isGetter ? resolvedGetCall : resolvedSetCall;
881                StackValue newReceiver = StackValue.receiver(call, receiver, codegen, callable);
882                ArgumentGenerator generator = createArgumentGenerator();
883                newReceiver.put(newReceiver.type, v);
884                callGenerator.processAndPutHiddenParameters(false);
885    
886                defaultArgs = generator.generate(valueArguments, valueArguments);
887            }
888    
889            private ArgumentGenerator createArgumentGenerator() {
890                assert callGenerator == null :
891                        "'putSelector' and 'createArgumentGenerator' methods should be called once for CollectionElementReceiver: " + callable;
892                ResolvedCall<FunctionDescriptor> resolvedCall = isGetter ? resolvedGetCall : resolvedSetCall;
893                assert resolvedCall != null : "Resolved call should be non-null: " + callable;
894                callGenerator =
895                        !isComplexOperationWithDup ? codegen.getOrCreateCallGenerator(resolvedCall) : codegen.defaultCallGenerator;
896                return new CallBasedArgumentGenerator(
897                        codegen,
898                        callGenerator,
899                        resolvedCall.getResultingDescriptor().getValueParameters(), callable.getValueParameterTypes()
900                );
901            }
902    
903            @Override
904            public void dup(@NotNull InstructionAdapter v, boolean withReceiver) {
905                dupReceiver(v);
906            }
907    
908            public void dupReceiver(@NotNull InstructionAdapter v) {
909                if (CollectionElement.isStandardStack(codegen.typeMapper, resolvedGetCall, 1) &&
910                    CollectionElement.isStandardStack(codegen.typeMapper, resolvedSetCall, 2)) {
911                    v.dup2();   // collection and index
912                    return;
913                }
914    
915                FrameMap.Mark mark = frame.mark();
916    
917                // indexes
918                List<ValueParameterDescriptor> valueParameters = resolvedGetCall.getResultingDescriptor().getValueParameters();
919                int firstParamIndex = -1;
920                for (int i = valueParameters.size() - 1; i >= 0; --i) {
921                    Type type = codegen.typeMapper.mapType(valueParameters.get(i).getType());
922                    firstParamIndex = frame.enterTemp(type);
923                    v.store(firstParamIndex, type);
924                }
925    
926                ReceiverValue receiverParameter = resolvedGetCall.getExtensionReceiver();
927                int receiverIndex = -1;
928                if (receiverParameter != null) {
929                    Type type = codegen.typeMapper.mapType(receiverParameter.getType());
930                    receiverIndex = frame.enterTemp(type);
931                    v.store(receiverIndex, type);
932                }
933    
934                ReceiverValue dispatchReceiver = resolvedGetCall.getDispatchReceiver();
935                int thisIndex = -1;
936                if (dispatchReceiver != null) {
937                    thisIndex = frame.enterTemp(OBJECT_TYPE);
938                    v.store(thisIndex, OBJECT_TYPE);
939                }
940    
941                // for setter
942    
943                int realReceiverIndex;
944                Type realReceiverType;
945                if (receiverIndex != -1) {
946                    realReceiverType = codegen.typeMapper.mapType(receiverParameter.getType());
947                    realReceiverIndex = receiverIndex;
948                }
949                else if (thisIndex != -1) {
950                    realReceiverType = OBJECT_TYPE;
951                    realReceiverIndex = thisIndex;
952                }
953                else {
954                    throw new UnsupportedOperationException();
955                }
956    
957                if (resolvedSetCall.getDispatchReceiver() != null) {
958                    if (resolvedSetCall.getExtensionReceiver() != null) {
959                        codegen.generateReceiverValue(resolvedSetCall.getDispatchReceiver(), false).put(OBJECT_TYPE, v);
960                    }
961                    v.load(realReceiverIndex, realReceiverType);
962                }
963                else {
964                    if (resolvedSetCall.getExtensionReceiver() != null) {
965                        v.load(realReceiverIndex, realReceiverType);
966                    }
967                    else {
968                        throw new UnsupportedOperationException();
969                    }
970                }
971    
972                int index = firstParamIndex;
973                for (ValueParameterDescriptor valueParameter : valueParameters) {
974                    Type type = codegen.typeMapper.mapType(valueParameter.getType());
975                    v.load(index, type);
976                    index -= type.getSize();
977                }
978    
979                // restoring original
980                if (thisIndex != -1) {
981                    v.load(thisIndex, OBJECT_TYPE);
982                }
983    
984                if (receiverIndex != -1) {
985                    v.load(receiverIndex, realReceiverType);
986                }
987    
988                index = firstParamIndex;
989                for (ValueParameterDescriptor valueParameter : valueParameters) {
990                    Type type = codegen.typeMapper.mapType(valueParameter.getType());
991                    v.load(index, type);
992                    index -= type.getSize();
993                }
994    
995                mark.dropTo();
996            }
997        }
998    
999        public static class CollectionElement extends StackValueWithSimpleReceiver {
1000            private final Callable getter;
1001            private final Callable setter;
1002            private final ExpressionCodegen codegen;
1003            private final ResolvedCall<FunctionDescriptor> resolvedGetCall;
1004            private final ResolvedCall<FunctionDescriptor> resolvedSetCall;
1005    
1006            public CollectionElement(
1007                    @NotNull CollectionElementReceiver collectionElementReceiver,
1008                    @NotNull Type type,
1009                    @Nullable ResolvedCall<FunctionDescriptor> resolvedGetCall,
1010                    @Nullable ResolvedCall<FunctionDescriptor> resolvedSetCall,
1011                    @NotNull ExpressionCodegen codegen
1012            ) {
1013                super(type, false, false, collectionElementReceiver, true);
1014                this.resolvedGetCall = resolvedGetCall;
1015                this.resolvedSetCall = resolvedSetCall;
1016                this.setter = resolvedSetCall == null ? null :
1017                              codegen.resolveToCallable(codegen.accessibleFunctionDescriptor(resolvedSetCall), false, resolvedSetCall);
1018                this.getter = resolvedGetCall == null ? null :
1019                              codegen.resolveToCallable(codegen.accessibleFunctionDescriptor(resolvedGetCall), false, resolvedGetCall);
1020                this.codegen = codegen;
1021            }
1022    
1023            @Override
1024            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1025                if (getter == null) {
1026                    throw new UnsupportedOperationException("no getter specified");
1027                }
1028                CallGenerator callGenerator = getCallGenerator();
1029                callGenerator.genCall(getter, resolvedGetCall, genDefaultMaskIfPresent(callGenerator), codegen);
1030                coerceTo(type, v);
1031            }
1032    
1033            private boolean genDefaultMaskIfPresent(CallGenerator callGenerator) {
1034                DefaultCallArgs defaultArgs = ((CollectionElementReceiver) receiver).defaultArgs;
1035                return defaultArgs.generateOnStackIfNeeded(callGenerator, true);
1036            }
1037    
1038            private CallGenerator getCallGenerator() {
1039                CallGenerator generator = ((CollectionElementReceiver) receiver).callGenerator;
1040                assert generator != null :
1041                        "CollectionElementReceiver should be putted on stack before CollectionElement:" +
1042                        " getCall = " + resolvedGetCall + ",  setCall = " + resolvedSetCall;
1043                return generator;
1044            }
1045    
1046            @Override
1047            public int receiverSize() {
1048                if (isStandardStack(codegen.typeMapper, resolvedGetCall, 1) && isStandardStack(codegen.typeMapper, resolvedSetCall, 2)) {
1049                    return 2;
1050                }
1051                else {
1052                    return -1;
1053                }
1054            }
1055    
1056            public static boolean isStandardStack(@NotNull KotlinTypeMapper typeMapper, @Nullable ResolvedCall<?> call, int valueParamsSize) {
1057                if (call == null) {
1058                    return true;
1059                }
1060    
1061                List<ValueParameterDescriptor> valueParameters = call.getResultingDescriptor().getValueParameters();
1062                if (valueParameters.size() != valueParamsSize) {
1063                    return false;
1064                }
1065    
1066                for (ValueParameterDescriptor valueParameter : valueParameters) {
1067                    if (typeMapper.mapType(valueParameter.getType()).getSize() != 1) {
1068                        return false;
1069                    }
1070                }
1071    
1072                if (call.getDispatchReceiver() != null) {
1073                    if (call.getExtensionReceiver() != null) {
1074                        return false;
1075                    }
1076                }
1077                else {
1078                    //noinspection ConstantConditions
1079                    if (typeMapper.mapType(call.getResultingDescriptor().getExtensionReceiverParameter().getType()).getSize() != 1) {
1080                        return false;
1081                    }
1082                }
1083    
1084                return true;
1085            }
1086    
1087            @Override
1088            public void storeSelector(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
1089                if (setter == null) {
1090                    throw new UnsupportedOperationException("no setter specified");
1091                }
1092    
1093                Type lastParameterType = ArraysKt.last(setter.getParameterTypes());
1094                coerce(topOfStackType, lastParameterType, v);
1095    
1096                getCallGenerator().afterParameterPut(lastParameterType, StackValue.onStack(lastParameterType),
1097                                                     CollectionsKt.getLastIndex(setter.getValueParameterTypes()));
1098    
1099                //Convention setter couldn't have default parameters, just getter can have it at last positions
1100                //We should remove default parameters of getter from stack*/
1101                //Note that it works only for non-inline case
1102                CollectionElementReceiver collectionElementReceiver = (CollectionElementReceiver) receiver;
1103                if (collectionElementReceiver.isGetter) {
1104                    List<ResolvedValueArgument> arguments = collectionElementReceiver.valueArguments;
1105                    List<Type> types = getter.getValueParameterTypes();
1106                    for (int i = arguments.size() - 1; i >= 0; i--) {
1107                        ResolvedValueArgument argument = arguments.get(i);
1108                        if (argument instanceof DefaultValueArgument) {
1109                            Type defaultType = types.get(i);
1110                            AsmUtil.swap(v, lastParameterType, defaultType);
1111                            AsmUtil.pop(v, defaultType);
1112                        }
1113                    }
1114                }
1115    
1116                getCallGenerator().genCall(setter, resolvedSetCall, false, codegen);
1117                Type returnType = setter.getReturnType();
1118                if (returnType != Type.VOID_TYPE) {
1119                    pop(v, returnType);
1120                }
1121            }
1122        }
1123    
1124    
1125        public static class Field extends StackValueWithSimpleReceiver {
1126            public final Type owner;
1127            public final String name;
1128            public final DeclarationDescriptor descriptor;
1129    
1130            public Field(
1131                    @NotNull Type type,
1132                    @NotNull Type owner,
1133                    @NotNull String name,
1134                    boolean isStatic,
1135                    @NotNull StackValue receiver,
1136                    @Nullable DeclarationDescriptor descriptor
1137            ) {
1138                super(type, isStatic, isStatic, receiver, receiver.canHaveSideEffects());
1139                this.owner = owner;
1140                this.name = name;
1141                this.descriptor = descriptor;
1142            }
1143    
1144            @Override
1145            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1146                v.visitFieldInsn(isStaticPut ? GETSTATIC : GETFIELD, owner.getInternalName(), name, this.type.getDescriptor());
1147                coerceTo(type, v);
1148            }
1149    
1150            @Override
1151            public void storeSelector(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
1152                coerceFrom(topOfStackType, v);
1153                v.visitFieldInsn(isStaticStore ? PUTSTATIC : PUTFIELD, owner.getInternalName(), name, this.type.getDescriptor());
1154            }
1155    
1156            @Override
1157            protected StackValueWithSimpleReceiver changeReceiver(@NotNull StackValue newReceiver) {
1158                return field(this, newReceiver);
1159            }
1160        }
1161    
1162        public static class Property extends StackValueWithSimpleReceiver {
1163            private final CallableMethod getter;
1164            private final CallableMethod setter;
1165            private final Type backingFieldOwner;
1166    
1167            private final PropertyDescriptor descriptor;
1168    
1169            private final String fieldName;
1170            @NotNull private final ExpressionCodegen codegen;
1171            @Nullable private final ResolvedCall resolvedCall;
1172    
1173            public Property(
1174                    @NotNull PropertyDescriptor descriptor, @Nullable Type backingFieldOwner,
1175                    @Nullable CallableMethod getter, @Nullable CallableMethod setter, boolean isStaticBackingField,
1176                    @Nullable String fieldName, @NotNull Type type,
1177                    @NotNull StackValue receiver,
1178                    @NotNull ExpressionCodegen codegen,
1179                    @Nullable ResolvedCall resolvedCall
1180            ) {
1181                super(type, isStatic(isStaticBackingField, getter), isStatic(isStaticBackingField, setter), receiver, true);
1182                this.backingFieldOwner = backingFieldOwner;
1183                this.getter = getter;
1184                this.setter = setter;
1185                this.descriptor = descriptor;
1186                this.fieldName = fieldName;
1187                this.codegen = codegen;
1188                this.resolvedCall = resolvedCall;
1189            }
1190    
1191            @Override
1192            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1193                if (getter == null) {
1194                    assert fieldName != null : "Property should have either a getter or a field name: " + descriptor;
1195                    assert backingFieldOwner != null : "Property should have either a getter or a backingFieldOwner: " + descriptor;
1196                    if (inlineConstantIfNeeded(type, v)) return;
1197    
1198                    v.visitFieldInsn(isStaticPut ? GETSTATIC : GETFIELD,
1199                                     backingFieldOwner.getInternalName(), fieldName, this.type.getDescriptor());
1200                    genNotNullAssertionForLateInitIfNeeded(v);
1201                    coerceTo(type, v);
1202                }
1203                else {
1204                    PropertyGetterDescriptor getterDescriptor = descriptor.getGetter();
1205                    assert getterDescriptor != null : "Getter descriptor should be not null for " + descriptor;
1206                    if (resolvedCall != null && getterDescriptor.isInline()) {
1207                        CallGenerator callGenerator = codegen.getOrCreateCallGenerator(resolvedCall, getterDescriptor);
1208                        callGenerator.processAndPutHiddenParameters(false);
1209                        callGenerator.genCall(getter, resolvedCall, false, codegen);
1210                    }
1211                    else {
1212                        getter.genInvokeInstruction(v);
1213                    }
1214                    coerce(getter.getReturnType(), type, v);
1215    
1216                    KotlinType returnType = descriptor.getReturnType();
1217                    if (returnType != null && KotlinBuiltIns.isNothing(returnType)) {
1218                        v.aconst(null);
1219                        v.athrow();
1220                    }
1221                }
1222            }
1223    
1224            private boolean inlineConstantIfNeeded(@NotNull Type type, @NotNull InstructionAdapter v) {
1225                if (JvmCodegenUtil.isInlinedJavaConstProperty(descriptor)) {
1226                    return inlineConstant(type, v);
1227                }
1228    
1229                if (descriptor.isConst() && codegen.getState().getShouldInlineConstVals()) {
1230                    return inlineConstant(type, v);
1231                }
1232    
1233                return false;
1234            }
1235    
1236            private boolean inlineConstant(@NotNull Type type, @NotNull InstructionAdapter v) {
1237                assert AsmUtil.isPrimitive(this.type) || AsmTypes.JAVA_STRING_TYPE.equals(this.type) :
1238                        "Const property should have primitive or string type: " + descriptor;
1239                assert isStaticPut : "Const property should be static" + descriptor;
1240    
1241                ConstantValue<?> constantValue = descriptor.getCompileTimeInitializer();
1242                if (constantValue == null) return false;
1243    
1244                Object value = constantValue.getValue();
1245                if (this.type == Type.FLOAT_TYPE && value instanceof Double) {
1246                    value = ((Double) value).floatValue();
1247                }
1248    
1249                StackValue.constant(value, this.type).putSelector(type, v);
1250    
1251                return true;
1252            }
1253    
1254            private void genNotNullAssertionForLateInitIfNeeded(@NotNull InstructionAdapter v) {
1255                if (!descriptor.isLateInit()) return;
1256    
1257                v.dup();
1258                Label ok = new Label();
1259                v.ifnonnull(ok);
1260                v.visitLdcInsn(descriptor.getName().asString());
1261                v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "throwUninitializedPropertyAccessException", "(Ljava/lang/String;)V", false);
1262                v.mark(ok);
1263            }
1264    
1265            @Override
1266            public void store(@NotNull StackValue rightSide, @NotNull InstructionAdapter v, boolean skipReceiver) {
1267                PropertySetterDescriptor setterDescriptor = descriptor.getSetter();
1268                if (resolvedCall != null && setterDescriptor != null && setterDescriptor.isInline()) {
1269                    assert setter != null : "Setter should be not null for " + descriptor;
1270                    CallGenerator callGenerator = codegen.getOrCreateCallGenerator(resolvedCall, setterDescriptor);
1271                    if (!skipReceiver) {
1272                        putReceiver(v, false);
1273                    }
1274                    callGenerator.processAndPutHiddenParameters(true);
1275                    callGenerator.putValueIfNeeded(rightSide.type, rightSide);
1276                    callGenerator.putHiddenParamsIntoLocals();
1277                    callGenerator.genCall(setter, resolvedCall, false, codegen);
1278                }
1279                else {
1280                    super.store(rightSide, v, skipReceiver);
1281                }
1282            }
1283    
1284            @Override
1285            public void storeSelector(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
1286                if (setter == null) {
1287                    coerceFrom(topOfStackType, v);
1288                    assert fieldName != null : "Property should have either a setter or a field name: " + descriptor;
1289                    assert backingFieldOwner != null : "Property should have either a setter or a backingFieldOwner: " + descriptor;
1290                    v.visitFieldInsn(isStaticStore ? PUTSTATIC : PUTFIELD, backingFieldOwner.getInternalName(), fieldName, this.type.getDescriptor());
1291                }
1292                else {
1293                    coerce(topOfStackType, ArraysKt.last(setter.getParameterTypes()), v);
1294                    setter.genInvokeInstruction(v);
1295    
1296                    Type returnType = setter.getReturnType();
1297                    if (returnType != Type.VOID_TYPE) {
1298                        pop(v, returnType);
1299                    }
1300                }
1301            }
1302    
1303            private static boolean isStatic(boolean isStaticBackingField, @Nullable CallableMethod callable) {
1304                if (isStaticBackingField && callable == null) {
1305                    return true;
1306                }
1307    
1308                if (callable != null && callable.isStaticCall()) {
1309                    List<JvmMethodParameterSignature> parameters = callable.getValueParameters();
1310                    for (JvmMethodParameterSignature parameter : parameters) {
1311                        JvmMethodParameterKind kind = parameter.getKind();
1312                        if (kind == JvmMethodParameterKind.VALUE) {
1313                            break;
1314                        }
1315                        if (kind == JvmMethodParameterKind.RECEIVER || kind == JvmMethodParameterKind.THIS) {
1316                            return false;
1317                        }
1318                    }
1319                    return true;
1320                }
1321    
1322                return false;
1323            }
1324        }
1325    
1326        private static class Expression extends StackValue {
1327            private final KtExpression expression;
1328            private final ExpressionCodegen generator;
1329    
1330            public Expression(Type type, KtExpression expression, ExpressionCodegen generator) {
1331                super(type);
1332                this.expression = expression;
1333                this.generator = generator;
1334            }
1335    
1336            @Override
1337            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1338                generator.gen(expression, type);
1339            }
1340        }
1341    
1342        public static class Shared extends StackValueWithSimpleReceiver {
1343            private final int index;
1344    
1345            public Shared(int index, Type type) {
1346                super(type, false, false, local(index, OBJECT_TYPE), false);
1347                this.index = index;
1348            }
1349    
1350            public int getIndex() {
1351                return index;
1352            }
1353    
1354            @Override
1355            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1356                Type refType = refType(this.type);
1357                Type sharedType = sharedTypeForType(this.type);
1358                v.visitFieldInsn(GETFIELD, sharedType.getInternalName(), "element", refType.getDescriptor());
1359                coerceFrom(refType, v);
1360                coerceTo(type, v);
1361            }
1362    
1363            @Override
1364            public void storeSelector(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
1365                coerceFrom(topOfStackType, v);
1366                Type refType = refType(this.type);
1367                Type sharedType = sharedTypeForType(this.type);
1368                v.visitFieldInsn(PUTFIELD, sharedType.getInternalName(), "element", refType.getDescriptor());
1369            }
1370        }
1371    
1372        @NotNull
1373        public static Type sharedTypeForType(@NotNull Type type) {
1374            switch (type.getSort()) {
1375                case Type.OBJECT:
1376                case Type.ARRAY:
1377                    return OBJECT_REF_TYPE;
1378                default:
1379                    PrimitiveType primitiveType = AsmUtil.asmPrimitiveTypeToLangPrimitiveType(type);
1380                    if (primitiveType == null) throw new UnsupportedOperationException();
1381    
1382                    String typeName = primitiveType.getTypeName().getIdentifier();
1383                    return Type.getObjectType(REF_TYPE_PREFIX + typeName + "Ref");
1384            }
1385        }
1386    
1387        public static Type refType(Type type) {
1388            if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
1389                return OBJECT_TYPE;
1390            }
1391    
1392            return type;
1393        }
1394    
1395        public static class FieldForSharedVar extends StackValueWithSimpleReceiver {
1396            final Type owner;
1397            final String name;
1398    
1399            public FieldForSharedVar(Type type, Type owner, String name, StackValue.Field receiver) {
1400                super(type, false, false, receiver, receiver.canHaveSideEffects());
1401                this.owner = owner;
1402                this.name = name;
1403            }
1404    
1405            @Override
1406            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1407                Type sharedType = sharedTypeForType(this.type);
1408                Type refType = refType(this.type);
1409                v.visitFieldInsn(GETFIELD, sharedType.getInternalName(), "element", refType.getDescriptor());
1410                coerceFrom(refType, v);
1411                coerceTo(type, v);
1412            }
1413    
1414            @Override
1415            public void storeSelector(@NotNull Type topOfStackType, @NotNull InstructionAdapter v) {
1416                coerceFrom(topOfStackType, v);
1417                v.visitFieldInsn(PUTFIELD, sharedTypeForType(type).getInternalName(), "element", refType(type).getDescriptor());
1418            }
1419    
1420            @Override
1421            protected StackValueWithSimpleReceiver changeReceiver(@NotNull StackValue newReceiver) {
1422                return fieldForSharedVar(this, newReceiver);
1423            }
1424        }
1425    
1426        private static class ThisOuter extends StackValue {
1427            private final ExpressionCodegen codegen;
1428            private final ClassDescriptor descriptor;
1429            private final boolean isSuper;
1430            private final boolean coerceType;
1431    
1432            public ThisOuter(ExpressionCodegen codegen, ClassDescriptor descriptor, boolean isSuper, boolean coerceType) {
1433                super(OBJECT_TYPE, false);
1434                this.codegen = codegen;
1435                this.descriptor = descriptor;
1436                this.isSuper = isSuper;
1437                this.coerceType = coerceType;
1438            }
1439    
1440            @Override
1441            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1442                StackValue stackValue = codegen.generateThisOrOuter(descriptor, isSuper);
1443                stackValue.put(coerceType ? type : stackValue.type, v);
1444            }
1445        }
1446    
1447        private static class PostIncrement extends StackValue {
1448            private final int index;
1449            private final int increment;
1450    
1451            public PostIncrement(int index, int increment) {
1452                super(Type.INT_TYPE);
1453                this.index = index;
1454                this.increment = increment;
1455            }
1456    
1457            @Override
1458            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1459                if (!type.equals(Type.VOID_TYPE)) {
1460                    v.load(index, Type.INT_TYPE);
1461                    coerceTo(type, v);
1462                }
1463                v.iinc(index, increment);
1464            }
1465        }
1466    
1467        private static class PreIncrementForLocalVar extends StackValue {
1468            private final int index;
1469            private final int increment;
1470    
1471            public PreIncrementForLocalVar(int index, int increment) {
1472                super(Type.INT_TYPE);
1473                this.index = index;
1474                this.increment = increment;
1475            }
1476    
1477            @Override
1478            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1479                v.iinc(index, increment);
1480                if (!type.equals(Type.VOID_TYPE)) {
1481                    v.load(index, Type.INT_TYPE);
1482                    coerceTo(type, v);
1483                }
1484            }
1485        }
1486    
1487        private static class PrefixIncrement extends StackValue {
1488            private final ResolvedCall resolvedCall;
1489            private final ExpressionCodegen codegen;
1490            private StackValue value;
1491    
1492            public PrefixIncrement(
1493                    @NotNull Type type,
1494                    @NotNull StackValue value,
1495                    ResolvedCall resolvedCall,
1496                    @NotNull ExpressionCodegen codegen
1497            ) {
1498                super(type);
1499                this.value = value;
1500                this.resolvedCall = resolvedCall;
1501                this.codegen = codegen;
1502            }
1503    
1504            @Override
1505            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1506                value = StackValue.complexReceiver(value, true, false, true);
1507                value.put(this.type, v);
1508    
1509                value.store(codegen.invokeFunction(resolvedCall, StackValue.onStack(this.type)), v, true);
1510    
1511                value.put(this.type, v, true);
1512                coerceTo(type, v);
1513            }
1514        }
1515    
1516        public static class CallReceiver extends StackValue {
1517            private final StackValue dispatchReceiver;
1518            private final StackValue extensionReceiver;
1519    
1520            public CallReceiver(
1521                    @NotNull StackValue dispatchReceiver,
1522                    @NotNull StackValue extensionReceiver,
1523                    @NotNull Type type
1524            ) {
1525                super(type, dispatchReceiver.canHaveSideEffects() || extensionReceiver.canHaveSideEffects());
1526                this.dispatchReceiver = dispatchReceiver;
1527                this.extensionReceiver = extensionReceiver;
1528            }
1529    
1530            @Nullable
1531            public static Type calcType(
1532                    @NotNull ResolvedCall<?> resolvedCall,
1533                    @Nullable ReceiverParameterDescriptor dispatchReceiver,
1534                    @Nullable ReceiverParameterDescriptor extensionReceiver,
1535                    @NotNull KotlinTypeMapper typeMapper,
1536                    @Nullable Callable callableMethod,
1537                    @NotNull GenerationState state
1538            ) {
1539                if (extensionReceiver != null) {
1540                    CallableDescriptor descriptor = resolvedCall.getCandidateDescriptor();
1541    
1542                    if (descriptor instanceof PropertyDescriptor &&
1543                        // hackaround: boxing changes behaviour of T.javaClass intrinsic
1544                        state.getIntrinsics().getIntrinsic((PropertyDescriptor) descriptor) != JavaClassProperty.INSTANCE
1545                    ) {
1546                        ReceiverParameterDescriptor receiverCandidate = descriptor.getExtensionReceiverParameter();
1547                        assert receiverCandidate != null;
1548                        return typeMapper.mapType(receiverCandidate.getType());
1549                    }
1550    
1551                    return callableMethod != null ? callableMethod.getExtensionReceiverType() : typeMapper.mapType(extensionReceiver.getType());
1552                }
1553                else if (dispatchReceiver != null) {
1554                    CallableDescriptor descriptor = resolvedCall.getResultingDescriptor();
1555    
1556                    if (CodegenUtilKt.isJvmStaticInObjectOrClass(descriptor)) {
1557                        return Type.VOID_TYPE;
1558                    }
1559    
1560                    if (callableMethod != null) {
1561                        return callableMethod.getDispatchReceiverType();
1562                    }
1563    
1564                    // Extract the receiver from the resolved call, workarounding the fact that ResolvedCall#dispatchReceiver doesn't have
1565                    // all the needed information, for example there's no way to find out whether or not a smart cast was applied to the receiver.
1566                    DeclarationDescriptor container = descriptor.getContainingDeclaration();
1567                    if (container instanceof ClassDescriptor) {
1568                        return typeMapper.mapClass((ClassDescriptor) container);
1569                    }
1570    
1571                    return typeMapper.mapType(dispatchReceiver);
1572                }
1573                else if (isLocalFunCall(callableMethod)) {
1574                    return callableMethod.getGenerateCalleeType();
1575                }
1576    
1577                return Type.VOID_TYPE;
1578            }
1579    
1580            @Override
1581            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1582                StackValue currentExtensionReceiver = extensionReceiver;
1583                boolean hasExtensionReceiver = extensionReceiver != none();
1584                if (extensionReceiver instanceof StackValue.SafeCall) {
1585                    currentExtensionReceiver.put(currentExtensionReceiver.type, v);
1586                    currentExtensionReceiver = StackValue.onStack(currentExtensionReceiver.type);
1587                }
1588    
1589                dispatchReceiver.put(hasExtensionReceiver ? dispatchReceiver.type : type, v);
1590    
1591                currentExtensionReceiver
1592                        .moveToTopOfStack(hasExtensionReceiver ? type : currentExtensionReceiver.type, v, dispatchReceiver.type.getSize());
1593            }
1594    
1595            @Override
1596            public void dup(@NotNull InstructionAdapter v, boolean withReceiver) {
1597                AsmUtil.dup(v, extensionReceiver.type, dispatchReceiver.type);
1598            }
1599    
1600            @NotNull
1601            public StackValue getDispatchReceiver() {
1602                return dispatchReceiver;
1603            }
1604    
1605            @NotNull
1606            public StackValue getExtensionReceiver() {
1607                return extensionReceiver;
1608            }
1609        }
1610    
1611        public abstract static class StackValueWithSimpleReceiver extends StackValue {
1612    
1613            public final boolean isStaticPut;
1614    
1615            public final boolean isStaticStore;
1616            @NotNull
1617            public final StackValue receiver;
1618    
1619            public StackValueWithSimpleReceiver(
1620                    @NotNull Type type,
1621                    boolean isStaticPut,
1622                    boolean isStaticStore,
1623                    @NotNull StackValue receiver,
1624                    boolean canHaveSideEffects
1625            ) {
1626                super(type, canHaveSideEffects);
1627                this.receiver = receiver;
1628                this.isStaticPut = isStaticPut;
1629                this.isStaticStore = isStaticStore;
1630            }
1631    
1632            @Override
1633            public void putReceiver(@NotNull InstructionAdapter v, boolean isRead) {
1634                boolean hasReceiver = isNonStaticAccess(isRead);
1635                if (hasReceiver || receiver.canHaveSideEffects()) {
1636                    receiver.put(hasReceiver ? receiver.type : Type.VOID_TYPE, v);
1637                }
1638            }
1639    
1640            @Override
1641            public boolean isNonStaticAccess(boolean isRead) {
1642                return isRead ? !isStaticPut : !isStaticStore;
1643            }
1644    
1645            public int receiverSize() {
1646                return receiver.type.getSize();
1647            }
1648    
1649            @Override
1650            public void dup(@NotNull InstructionAdapter v, boolean withWriteReceiver) {
1651                if (!withWriteReceiver) {
1652                    super.dup(v, false);
1653                }
1654                else {
1655                    int receiverSize = isNonStaticAccess(false) ? receiverSize() : 0;
1656                    switch (receiverSize) {
1657                        case 0:
1658                            AsmUtil.dup(v, type);
1659                            break;
1660    
1661                        case 1:
1662                            if (type.getSize() == 2) {
1663                                v.dup2X1();
1664                            }
1665                            else {
1666                                v.dupX1();
1667                            }
1668                            break;
1669    
1670                        case 2:
1671                            if (type.getSize() == 2) {
1672                                v.dup2X2();
1673                            }
1674                            else {
1675                                v.dupX2();
1676                            }
1677                            break;
1678    
1679                        case -1:
1680                            throw new UnsupportedOperationException();
1681                    }
1682                }
1683            }
1684    
1685            @Override
1686            public void store(
1687                    @NotNull StackValue rightSide, @NotNull InstructionAdapter v, boolean skipReceiver
1688            ) {
1689                if (!skipReceiver) {
1690                    putReceiver(v, false);
1691                }
1692                rightSide.put(rightSide.type, v);
1693                storeSelector(rightSide.type, v);
1694            }
1695    
1696            protected StackValueWithSimpleReceiver changeReceiver(@NotNull StackValue newReceiver) {
1697                return this;
1698            }
1699        }
1700    
1701        private static class ComplexReceiver extends StackValue {
1702    
1703            private final StackValueWithSimpleReceiver originalValueWithReceiver;
1704            private final boolean[] isReadOperations;
1705    
1706            public ComplexReceiver(StackValueWithSimpleReceiver value, boolean[] isReadOperations) {
1707                super(value.type, value.receiver.canHaveSideEffects());
1708                this.originalValueWithReceiver = value;
1709                this.isReadOperations = isReadOperations;
1710                if (value instanceof CollectionElement) {
1711                    if (value.receiver instanceof CollectionElementReceiver) {
1712                        ((CollectionElementReceiver) value.receiver).isComplexOperationWithDup = true;
1713                    }
1714                }
1715            }
1716    
1717            @Override
1718            public void putSelector(
1719                    @NotNull Type type, @NotNull InstructionAdapter v
1720            ) {
1721                boolean wasPut = false;
1722                StackValue receiver = originalValueWithReceiver.receiver;
1723                for (boolean operation : isReadOperations) {
1724                    if (originalValueWithReceiver.isNonStaticAccess(operation)) {
1725                        if (!wasPut) {
1726                            receiver.put(receiver.type, v);
1727                            wasPut = true;
1728                        }
1729                        else {
1730                            receiver.dup(v, false);
1731                        }
1732                    }
1733                }
1734    
1735                if (!wasPut && receiver.canHaveSideEffects()) {
1736                    receiver.put(Type.VOID_TYPE, v);
1737                }
1738            }
1739        }
1740    
1741        public static class Receiver extends StackValue {
1742    
1743            private final StackValue[] instructions;
1744    
1745            protected Receiver(@NotNull Type type, StackValue... receiverInstructions) {
1746                super(type);
1747                instructions = receiverInstructions;
1748            }
1749    
1750            @Override
1751            public void putSelector(
1752                    @NotNull Type type, @NotNull InstructionAdapter v
1753            ) {
1754                for (StackValue instruction : instructions) {
1755                    instruction.put(instruction.type, v);
1756                }
1757            }
1758        }
1759    
1760        public static class DelegatedForComplexReceiver extends StackValueWithSimpleReceiver {
1761    
1762            public final StackValueWithSimpleReceiver originalValue;
1763    
1764            public DelegatedForComplexReceiver(
1765                    @NotNull Type type,
1766                    @NotNull StackValueWithSimpleReceiver originalValue,
1767                    @NotNull ComplexReceiver receiver
1768            ) {
1769                super(type, bothReceiverStatic(originalValue), bothReceiverStatic(originalValue), receiver, originalValue.canHaveSideEffects());
1770                this.originalValue = originalValue;
1771            }
1772    
1773            private static boolean bothReceiverStatic(StackValueWithSimpleReceiver originalValue) {
1774                return !(originalValue.isNonStaticAccess(true) || originalValue.isNonStaticAccess(false));
1775            }
1776    
1777            @Override
1778            public void putSelector(
1779                    @NotNull Type type, @NotNull InstructionAdapter v
1780            ) {
1781                originalValue.putSelector(type, v);
1782            }
1783    
1784            @Override
1785            public void store(@NotNull StackValue rightSide, @NotNull InstructionAdapter v, boolean skipReceiver) {
1786                if (!skipReceiver) {
1787                    putReceiver(v, false);
1788                }
1789                originalValue.store(rightSide, v, true);
1790            }
1791    
1792            @Override
1793            public void storeSelector(
1794                    @NotNull Type topOfStackType, @NotNull InstructionAdapter v
1795            ) {
1796                originalValue.storeSelector(topOfStackType, v);
1797            }
1798    
1799            @Override
1800            public void dup(@NotNull InstructionAdapter v, boolean withWriteReceiver) {
1801                originalValue.dup(v, withWriteReceiver);
1802            }
1803        }
1804    
1805        public static StackValue complexWriteReadReceiver(StackValue stackValue) {
1806            return complexReceiver(stackValue, false, true);
1807        }
1808    
1809        private static StackValue complexReceiver(StackValue stackValue, boolean... isReadOperations) {
1810            if (stackValue instanceof Delegate) {
1811                //TODO need to support
1812                throwUnsupportedComplexOperation(((Delegate) stackValue).variableDescriptor);
1813            }
1814    
1815            if (stackValue instanceof StackValueWithSimpleReceiver) {
1816                return new DelegatedForComplexReceiver(stackValue.type, (StackValueWithSimpleReceiver) stackValue,
1817                                     new ComplexReceiver((StackValueWithSimpleReceiver) stackValue, isReadOperations));
1818            }
1819            else {
1820                return stackValue;
1821            }
1822        }
1823    
1824        static class SafeCall extends StackValue {
1825    
1826            @NotNull private final Type type;
1827            private final StackValue receiver;
1828            @Nullable private final Label ifNull;
1829    
1830            public SafeCall(@NotNull Type type, @NotNull StackValue value, @Nullable Label ifNull) {
1831                super(type);
1832                this.type = type;
1833                this.receiver = value;
1834                this.ifNull = ifNull;
1835            }
1836    
1837            @Override
1838            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1839                receiver.put(this.type, v);
1840                if (ifNull != null) {
1841                    //not a primitive
1842                    v.dup();
1843                    v.ifnull(ifNull);
1844                }
1845                coerceTo(type, v);
1846            }
1847        }
1848    
1849        static class SafeFallback extends StackValueWithSimpleReceiver {
1850    
1851            @Nullable private final Label ifNull;
1852    
1853            public SafeFallback(@NotNull Type type, @Nullable Label ifNull, StackValue receiver) {
1854                super(type, false, false, receiver, true);
1855                this.ifNull = ifNull;
1856            }
1857    
1858            @Override
1859            public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
1860                Label end = new Label();
1861    
1862                v.goTo(end);
1863                v.mark(ifNull);
1864                v.pop();
1865                if (!this.type.equals(Type.VOID_TYPE)) {
1866                    v.aconst(null);
1867                }
1868                v.mark(end);
1869    
1870                coerceTo(type, v);
1871            }
1872    
1873            @Override
1874            public void store(
1875                    @NotNull StackValue rightSide, @NotNull InstructionAdapter v, boolean skipReceiver
1876            ) {
1877                receiver.store(rightSide, v, skipReceiver);
1878    
1879                Label end = new Label();
1880                v.goTo(end);
1881                v.mark(ifNull);
1882                v.pop();
1883                v.mark(end);
1884            }
1885        }
1886    
1887        private static void throwUnsupportedComplexOperation(
1888                @NotNull CallableDescriptor descriptor
1889        ) {
1890            throw new RuntimeException(
1891                    "Augment assignment and increment are not supported for local delegated properties ans inline properties: " +
1892                    descriptor);
1893        }
1894    }
1895