JVM: introduce JvmBackendConfig

Move language version settings, compiler configuration and different
flags there, and use this config everywhere in both backends instead of
GenerationState.

This will hopefully make GenerationState less of a "god object" and
remove the need to have it available everywhere, in particular in JVM IR
lowerings code, in the future.

Also, future refactorings will make it easier to inject backend-specific
behavior into common code, so that we would not need to handle support
of new features in the old backend.
This commit is contained in:
Alexander Udalov
2023-07-21 18:18:42 +02:00
committed by Space Team
parent b6f8991072
commit 72d048bd62
70 changed files with 265 additions and 237 deletions
@@ -144,7 +144,7 @@ public class ClassFileFactory implements OutputFileCollection {
if (state.getLanguageVersionSettings().getFlag(JvmAnalysisFlags.getStrictMetadataVersionSemantics())) {
flags |= ModuleMapping.STRICT_METADATA_VERSION_SEMANTICS_FLAG;
}
return ModuleMappingKt.serializeToByteArray(moduleProto, state.getMetadataVersion(), flags);
return ModuleMappingKt.serializeToByteArray(moduleProto, state.getConfig().getMetadataVersion(), flags);
}
@Override
@@ -173,7 +173,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
v.defineClass(
element,
state.getClassFileVersion(),
state.getConfig().getClassFileVersion(),
ACC_FINAL | ACC_SUPER | visibilityFlag | getSyntheticAccessFlagForLambdaClass(classDescriptor),
asmType.getInternalName(),
sw.makeJavaGenericSignature(),
@@ -53,7 +53,7 @@ class CodeFragmentCodegen private constructor(
override fun generateDeclaration() {
v.defineClass(
codeFragment,
state.classFileVersion,
state.config.classFileVersion,
ACC_PUBLIC or ACC_SUPER,
info.classType.internalName,
null,
@@ -676,7 +676,7 @@ public class DescriptorAsmUtil {
@NotNull FunctionDescriptor descriptor,
@NotNull FrameMap frameMap
) {
if (state.isParamAssertionsDisabled()) return;
if (state.getConfig().isParamAssertionsDisabled()) return;
// currently when resuming a suspend function we pass default values instead of real arguments (i.e. nulls for references)
if (descriptor.isSuspend()) return;
@@ -688,7 +688,7 @@ public class DescriptorAsmUtil {
// Such functions can be invoked in operator conventions desugaring,
// which is currently done on ad hoc basis in ExpressionCodegen.
if (state.isReceiverAssertionsDisabled()) return;
if (state.getConfig().isReceiverAssertionsDisabled()) return;
if (descriptor.isOperator()) {
ReceiverParameterDescriptor receiverParameter = descriptor.getExtensionReceiverParameter();
if (receiverParameter != null) {
@@ -737,7 +737,7 @@ public class DescriptorAsmUtil {
}
value.put(asmType, v);
v.visitLdcInsn(name);
String methodName = state.getUnifiedNullChecks() ? "checkNotNullParameter" : "checkParameterIsNotNull";
String methodName = state.getConfig().getUnifiedNullChecks() ? "checkNotNullParameter" : "checkParameterIsNotNull";
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, methodName, "(Ljava/lang/Object;Ljava/lang/String;)V", false);
}
}
@@ -748,7 +748,7 @@ public class DescriptorAsmUtil {
@NotNull StackValue stackValue,
@Nullable RuntimeAssertionInfo runtimeAssertionInfo
) {
if (state.isCallAssertionsDisabled()) return stackValue;
if (state.getConfig().isCallAssertionsDisabled()) return stackValue;
if (runtimeAssertionInfo == null || !runtimeAssertionInfo.getNeedNotNullAssertion()) return stackValue;
return new StackValue(stackValue.type, stackValue.kotlinType) {
@@ -760,7 +760,8 @@ public class DescriptorAsmUtil {
if (innerType.getSort() == Type.OBJECT || innerType.getSort() == Type.ARRAY) {
v.dup();
v.visitLdcInsn(runtimeAssertionInfo.getMessage());
String methodName = state.getUnifiedNullChecks() ? "checkNotNullExpressionValue" : "checkExpressionValueIsNotNull";
String methodName =
state.getConfig().getUnifiedNullChecks() ? "checkNotNullExpressionValue" : "checkExpressionValueIsNotNull";
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, methodName, "(Ljava/lang/Object;Ljava/lang/String;)V", false);
}
StackValue.coerce(innerType, innerKotlinType, type, kotlinType, v);
@@ -13,7 +13,6 @@ import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.Stack;
import kotlin.Pair;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import kotlin.text.StringsKt;
@@ -38,7 +37,6 @@ import org.jetbrains.kotlin.codegen.range.RangeValue;
import org.jetbrains.kotlin.codegen.range.RangeValuesKt;
import org.jetbrains.kotlin.codegen.range.forLoop.ForLoopGenerator;
import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter;
import org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.codegen.when.SwitchCodegen;
@@ -62,14 +60,9 @@ import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
import org.jetbrains.kotlin.resolve.*;
import org.jetbrains.kotlin.resolve.calls.util.CallResolverUtilKt;
import org.jetbrains.kotlin.resolve.calls.util.CallUtilKt;
import org.jetbrains.kotlin.resolve.calls.inference.CapturedTypeConstructorKt;
import org.jetbrains.kotlin.resolve.calls.model.*;
import org.jetbrains.kotlin.resolve.calls.util.CallMaker;
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject;
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForTypeAliasObject;
import org.jetbrains.kotlin.resolve.calls.util.UnderscoreUtilKt;
import org.jetbrains.kotlin.resolve.calls.util.*;
import org.jetbrains.kotlin.resolve.checkers.PrimitiveNumericComparisonInfo;
import org.jetbrains.kotlin.resolve.constants.*;
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluatorKt;
@@ -857,12 +850,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Nullable
public ConstantValue<?> getCompileTimeConstant(@NotNull KtExpression expression) {
return getCompileTimeConstant(expression, bindingContext, state.getShouldInlineConstVals());
return getCompileTimeConstant(expression, bindingContext, state.getConfig().getShouldInlineConstVals());
}
@Nullable
public ConstantValue<?> getPrimitiveOrStringCompileTimeConstant(@NotNull KtExpression expression) {
return getPrimitiveOrStringCompileTimeConstant(expression, bindingContext, state.getShouldInlineConstVals());
return getPrimitiveOrStringCompileTimeConstant(expression, bindingContext, state.getConfig().getShouldInlineConstVals());
}
@Nullable
@@ -1686,7 +1679,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
CallableMemberDescriptor descriptor = getContext().getContextDescriptor();
NonLocalReturnInfo nonLocalReturn = getNonLocalReturnInfo(descriptor, expression);
boolean isNonLocalReturn = nonLocalReturn != null;
if (isNonLocalReturn && state.isInlineDisabled()) {
if (isNonLocalReturn && state.getConfig().isInlineDisabled()) {
state.getDiagnostics().report(Errors.NON_LOCAL_RETURN_IN_DISABLED_INLINE.on(expression));
genThrow(v, "java/lang/UnsupportedOperationException",
"Non-local returns are not allowed with inlining disabled");
@@ -2309,9 +2302,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
PropertyDescriptor originalPropertyDescriptor = DescriptorUtils.unwrapFakeOverride(propertyDescriptor);
boolean directAccessToGetter =
couldUseDirectAccessToProperty(propertyDescriptor, true, isDelegatedProperty, context, state.getShouldInlineConstVals());
couldUseDirectAccessToProperty(propertyDescriptor, true, isDelegatedProperty, context, state.getConfig().getShouldInlineConstVals());
boolean directAccessToSetter =
couldUseDirectAccessToProperty(propertyDescriptor, false, isDelegatedProperty, context, state.getShouldInlineConstVals());
couldUseDirectAccessToProperty(propertyDescriptor, false, isDelegatedProperty, context, state.getConfig().getShouldInlineConstVals());
if (fieldAccessorKind == AccessorKind.LATEINIT_INTRINSIC) {
skipPropertyAccessors =
@@ -2707,8 +2700,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull CallGenerator callGenerator,
@NotNull ArgumentGenerator argumentGenerator
) {
if (AssertCodegenUtilKt.isAssertCall(resolvedCall) && !state.getAssertionsMode().equals(JVMAssertionsMode.LEGACY)) {
AssertCodegenUtilKt.generateAssert(state.getAssertionsMode(), resolvedCall, this, parentCodegen);
if (AssertCodegenUtilKt.isAssertCall(resolvedCall) && !state.getConfig().getAssertionsMode().equals(JVMAssertionsMode.LEGACY)) {
AssertCodegenUtilKt.generateAssert(state.getConfig().getAssertionsMode(), resolvedCall, this, parentCodegen);
return;
}
@@ -2778,7 +2771,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
KotlinType returnType = resolvedCall.getResultingDescriptor().getReturnType();
if (returnType != null && KotlinBuiltIns.isNothing(returnType)) {
if (state.getUseKotlinNothingValueException()) {
if (state.getConfig().getUseKotlinNothingValueException()) {
v.anew(Type.getObjectType("kotlin/KotlinNothingValueException"));
v.dup();
v.invokespecial("kotlin/KotlinNothingValueException", "<init>", "()V", false);
@@ -2881,7 +2874,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
// We should inline callable containing reified type parameters even if inline is disabled
// because they may contain something to reify and straight call will probably fail at runtime
boolean shouldInline = isInline && (!state.isInlineDisabled() || InlineUtil.containsReifiedTypeParameters(descriptor));
boolean shouldInline = isInline && (!state.getConfig().isInlineDisabled() || InlineUtil.containsReifiedTypeParameters(descriptor));
if (!shouldInline) return defaultCallGenerator;
FunctionDescriptor original =
@@ -2994,7 +2987,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
else if (receiverValue instanceof ExpressionReceiver) {
ExpressionReceiver expressionReceiver = (ExpressionReceiver) receiverValue;
StackValue stackValue = gen(expressionReceiver.getExpression());
if (!state.isReceiverAssertionsDisabled()) {
if (!state.getConfig().isReceiverAssertionsDisabled()) {
RuntimeAssertionInfo runtimeAssertionInfo =
bindingContext.get(JvmBindingContextSlices.RECEIVER_RUNTIME_ASSERTION_INFO, expressionReceiver);
stackValue = genNotNullAssertions(state, stackValue, runtimeAssertionInfo);
@@ -4402,7 +4395,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return StackValue.operation(base.type, base.kotlinType, v -> {
base.put(base.type, base.kotlinType, v);
v.dup();
if (state.getUnifiedNullChecks()) {
if (state.getConfig().getUnifiedNullChecks()) {
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "checkNotNull", "(Ljava/lang/Object;)V", false);
} else {
Label ok = new Label();
@@ -5162,7 +5155,7 @@ The "returned" value of try expression with no finally is either the last expres
}
CodegenUtilKt.generateAsCast(
v, rightKotlinType, boxedRightType, safeAs, state.getUnifiedNullChecks()
v, rightKotlinType, boxedRightType, safeAs, state.getConfig().getUnifiedNullChecks()
);
return Unit.INSTANCE;
@@ -203,7 +203,7 @@ public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
iv.ifnull(ifNull);
}
genHashCode(mv, iv, asmType, generationState.getTarget());
genHashCode(mv, iv, asmType, generationState.getConfig().getTarget());
if (ifNull != null) {
Label end = new Label();
@@ -232,7 +232,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
v.defineClass(
myClass.getPsiOrParent(),
state.getClassFileVersion(),
state.getConfig().getClassFileVersion(),
access,
signature.getName(),
signature.getJavaGenericSignature(),
@@ -538,7 +538,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
) {
iv.load(index, classAsmType);
if (couldUseDirectAccessToProperty(propertyDescriptor, /* forGetter = */ true,
/* isDelegated = */ false, context, state.getShouldInlineConstVals())) {
/* isDelegated = */ false, context, state.getConfig().getShouldInlineConstVals())) {
KotlinType kotlinType = propertyDescriptor.getType();
Type type = state.getTypeMapper().mapType(kotlinType);
String fieldName = ((FieldOwnerContext) context.getParentContext()).getFieldName(propertyDescriptor, false);
@@ -47,9 +47,9 @@ class InterfaceImplBodyCodegen(
val codegenFlags = ACC_PUBLIC or ACC_FINAL or ACC_SUPER
val flags = if (state.classBuilderMode == ClassBuilderMode.LIGHT_CLASSES) codegenFlags or ACC_STATIC else codegenFlags
v.defineClass(
myClass.psiOrParent, state.classFileVersion, flags,
defaultImplType.internalName,
null, "java/lang/Object", ArrayUtil.EMPTY_STRING_ARRAY
myClass.psiOrParent, state.config.classFileVersion, flags,
defaultImplType.internalName,
null, "java/lang/Object", ArrayUtil.EMPTY_STRING_ARRAY
)
v.visitSource(myClass.containingKtFile.name, null)
}
@@ -191,7 +191,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
v.visitSMAP(getOrCreateSourceMapper(), !state.getLanguageVersionSettings().supportsFeature(LanguageFeature.CorrectSourceMappingSyntax));
}
v.done(state.getGenerateSmapCopyToAnnotation());
v.done(state.getConfig().getGenerateSmapCopyToAnnotation());
}
public void genSimpleMember(@NotNull KtDeclaration declaration) {
@@ -597,7 +597,9 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
KtExpression initializer = property.getInitializer();
ConstantValue<?> initializerValue =
initializer != null ? ExpressionCodegen.getCompileTimeConstant(initializer, bindingContext, state.getShouldInlineConstVals()) : null;
initializer != null
? ExpressionCodegen.getCompileTimeConstant(initializer, bindingContext, state.getConfig().getShouldInlineConstVals())
: null;
// we must write constant values for fields in light classes,
// because Java's completion for annotation arguments uses this information
if (initializerValue == null) return state.getClassBuilderMode().generateBodies;
@@ -692,7 +694,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
iv.dup();
List<Type> superCtorArgTypes = new ArrayList<>();
if (state.getGenerateOptimizedCallableReferenceSuperClasses()) {
if (state.getConfig().getGenerateOptimizedCallableReferenceSuperClasses()) {
CallableReferenceUtilKt.generateCallableReferenceDeclarationContainerClass(iv, property, state);
superCtorArgTypes.add(JAVA_CLASS_TYPE);
} else {
@@ -706,7 +708,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
superCtorArgTypes.add(JAVA_STRING_TYPE);
superCtorArgTypes.add(JAVA_STRING_TYPE);
if (state.getGenerateOptimizedCallableReferenceSuperClasses()) {
if (state.getConfig().getGenerateOptimizedCallableReferenceSuperClasses()) {
iv.aconst(CallableReferenceUtilKt.getCallableReferenceTopLevelFlag(property));
superCtorArgTypes.add(Type.INT_TYPE);
}
@@ -754,7 +756,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
}
protected void initDefaultSourceMappingIfNeeded() {
if (state.isInlineDisabled()) return;
if (state.getConfig().isInlineDisabled()) return;
CodegenContext parentContext = context.getParentContext();
while (parentContext != null) {
@@ -140,7 +140,7 @@ class MultifileClassCodegenImpl(
}
defineClass(
singleSourceFile, state.classFileVersion, attributes,
singleSourceFile, state.config.classFileVersion, attributes,
facadeClassType.internalName, null, superClassForFacade, emptyArray()
)
if (singleSourceFile != null) {
@@ -344,7 +344,7 @@ class MultifileClassCodegenImpl(
}
private fun done() {
classBuilder.done(state.generateSmapCopyToAnnotation)
classBuilder.done(state.config.generateSmapCopyToAnnotation)
if (classBuilder.isComputed) {
state.afterIndependentPart()
}
@@ -73,7 +73,7 @@ class MultifileClassPartCodegen(
val access = if (shouldGeneratePartHierarchy) 0 else Opcodes.ACC_SYNTHETIC or Opcodes.ACC_FINAL
v.defineClass(
element, state.classFileVersion, access or Opcodes.ACC_SUPER, partType.internalName, null, superClassInternalName,
element, state.config.classFileVersion, access or Opcodes.ACC_SUPER, partType.internalName, null, superClassInternalName,
ArrayUtil.EMPTY_STRING_ARRAY
)
v.visitSource(element.name, null)
@@ -77,7 +77,7 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
}
}
v.defineClass(element, state.getClassFileVersion(),
v.defineClass(element, state.getConfig().getClassFileVersion(),
ACC_PUBLIC | ACC_FINAL | ACC_SUPER | (isSynthetic ? ACC_SYNTHETIC : 0),
packagePartType.getInternalName(),
null,
@@ -299,7 +299,7 @@ public class PropertyCodegen {
KtExpression defaultValue = loadAnnotationArgumentDefaultValue(parameter, descriptor, expectedAnnotationConstructor);
if (defaultValue != null) {
ConstantValue<?> constant = ExpressionCodegen.getCompileTimeConstant(
defaultValue, bindingContext, true, state.getShouldInlineConstVals());
defaultValue, bindingContext, true, state.getConfig().getShouldInlineConstVals());
assert !state.getClassBuilderMode().generateBodies || constant != null
: "Default value for annotation parameter should be compile time value: " + defaultValue.getText();
if (constant != null) {
@@ -91,7 +91,7 @@ class PropertyReferenceCodegen(
override fun generateDeclaration() {
v.defineClass(
element,
state.classFileVersion,
state.config.classFileVersion,
ACC_FINAL or ACC_SUPER or
DescriptorAsmUtil.getVisibilityAccessFlagForClass(classDescriptor) or
DescriptorAsmUtil.getSyntheticAccessFlagForLambdaClass(classDescriptor),
@@ -129,7 +129,7 @@ public class SamWrapperCodegen {
: new String[] {samAsmType.getInternalName()};
cv.defineClass(
file,
state.getClassFileVersion(),
state.getConfig().getClassFileVersion(),
classFlags,
asmType.getInternalName(),
null,
@@ -166,7 +166,7 @@ public class SamWrapperCodegen {
generateDelegatesToDefaultImpl(asmType, classDescriptor, samType.getClassDescriptor(), functionCodegen, state);
}
cv.done(state.getGenerateSmapCopyToAnnotation());
cv.done(state.getConfig().getGenerateSmapCopyToAnnotation());
return asmType;
}
@@ -43,7 +43,7 @@ class ScriptCodegen private constructor(
override fun generateDeclaration() {
v.defineClass(
scriptDeclaration,
state.classFileVersion,
state.config.classFileVersion,
ACC_PUBLIC or ACC_SUPER,
classAsmType.internalName,
null,
@@ -1806,7 +1806,7 @@ public abstract class StackValue {
return inlineConstant(type, kotlinType, v);
}
if (descriptor.isConst() && codegen.getState().getShouldInlineConstVals()) {
if (descriptor.isConst() && codegen.getState().getConfig().getShouldInlineConstVals()) {
return inlineConstant(type, kotlinType, v);
}
@@ -17,7 +17,6 @@ import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import java.lang.StringBuilder
class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapter) {
@@ -236,7 +235,6 @@ class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapte
}
fun create(state: GenerationState, mv: InstructionAdapter) =
StringConcatGenerator(state.runtimeStringConcat, mv)
StringConcatGenerator(state.config.runtimeStringConcat, mv)
}
}
@@ -593,7 +593,7 @@ private fun generateLambdaForRunSuspend(
)
lambdaBuilder.defineClass(
originElement, state.classFileVersion,
originElement, state.config.classFileVersion,
ACC_FINAL or ACC_SUPER or ACC_SYNTHETIC,
internalName, null,
AsmTypes.LAMBDA.internalName,
@@ -676,7 +676,7 @@ private fun generateLambdaForRunSuspend(
writeSyntheticClassMetadata(lambdaBuilder, state, false)
lambdaBuilder.done(state.generateSmapCopyToAnnotation)
lambdaBuilder.done(state.config.generateSmapCopyToAnnotation)
return lambdaBuilder.thisName
}
@@ -30,7 +30,7 @@ fun generateParameterNames(
state: GenerationState,
isSynthetic: Boolean
) {
if (!state.generateParametersMetadata || isSynthetic) {
if (!state.config.generateParametersMetadata || isSynthetic) {
return
}
@@ -59,7 +59,9 @@ class AnonymousObjectTransformer(
createClassReader().accept(object : ClassVisitor(Opcodes.API_VERSION, classBuilder.visitor) {
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<String>) {
classBuilder.defineClass(null, maxOf(version, state.classFileVersion), access, name, signature, superName, interfaces)
classBuilder.defineClass(
null, maxOf(version, state.config.classFileVersion), access, name, signature, superName, interfaces
)
if (superName.isCoroutineSuperClass()) {
inliningContext.isContinuation = true
}
@@ -229,7 +231,7 @@ class AnonymousObjectTransformer(
if (continuationClassName == transformationInfo.oldClassName) {
coroutineTransformer.registerClassBuilder(continuationClassName)
} else {
classBuilder.done(state.generateSmapCopyToAnnotation)
classBuilder.done(state.config.generateSmapCopyToAnnotation)
}
return transformationResult
@@ -206,7 +206,7 @@ class MethodInliner(
}
for (classBuilder in childInliningContext.continuationBuilders.values) {
classBuilder.done(inliningContext.state.generateSmapCopyToAnnotation)
classBuilder.done(inliningContext.state.config.generateSmapCopyToAnnotation)
}
} else {
result.addNotChangedClass(oldClassName)
@@ -65,7 +65,9 @@ class WhenMappingTransformer(
val fieldNode = transformationInfo.fieldNode
classReader.accept(object : ClassVisitor(Opcodes.API_VERSION, classBuilder.visitor) {
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<String>) {
classBuilder.defineClass(null, maxOf(version, state.classFileVersion), access, name, signature, superName, interfaces)
classBuilder.defineClass(
null, maxOf(version, state.config.classFileVersion), access, name, signature, superName, interfaces
)
}
override fun visitField(access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor? {
@@ -104,7 +106,7 @@ class WhenMappingTransformer(
transformedClinit.signature, transformedClinit.exceptions.toTypedArray()
)
transformedClinit.accept(result)
classBuilder.done(state.generateSmapCopyToAnnotation)
classBuilder.done(state.config.generateSmapCopyToAnnotation)
return transformationResult
}
@@ -44,7 +44,7 @@ class PsiInlineCodegen(
codegen, state, signature, typeParameterMappings, sourceCompiler,
ReifiedTypeInliner(
typeParameterMappings, PsiInlineIntrinsicsSupport(state, reportErrorsOn), codegen.typeSystem,
state.languageVersionSettings, state.unifiedNullChecks
state.languageVersionSettings, state.config.unifiedNullChecks
),
), CallGenerator {
override fun generateAssertField() =
@@ -46,7 +46,7 @@ class PsiInlineIntrinsicsSupport(
}
private fun generateFunctionReference(v: InstructionAdapter, descriptor: FunctionDescriptor) {
check(state.generateOptimizedCallableReferenceSuperClasses) {
check(state.config.generateOptimizedCallableReferenceSuperClasses) {
"typeOf() of a non-reified type parameter is only allowed if optimized callable references are enabled.\n" +
"Please make sure API version is set to 1.4, and -Xno-optimized-callable-references is NOT used.\n" +
"Container: $descriptor"
@@ -61,11 +61,13 @@ class SamWrapperTransformer(transformationInfo: SamWrapperTransformationInfo, pr
classReader.accept(object : ClassVisitor(Opcodes.API_VERSION, classBuilder.visitor) {
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<String>) {
classBuilder.defineClass(null, maxOf(version, state.classFileVersion), access, name, signature, superName, interfaces)
classBuilder.defineClass(
null, maxOf(version, state.config.classFileVersion), access, name, signature, superName, interfaces
)
}
}, ClassReader.SKIP_FRAMES)
classBuilder.done(inliningContext.state.generateSmapCopyToAnnotation)
classBuilder.done(inliningContext.state.config.generateSmapCopyToAnnotation)
return transformationResult
}
@@ -142,7 +142,7 @@ class CoroutineTransformer(
}
fun replaceFakesWithReals(node: MethodNode) {
findFakeContinuationConstructorClassName(node)?.let(::unregisterClassBuilder)?.done(state.generateSmapCopyToAnnotation)
findFakeContinuationConstructorClassName(node)?.let(::unregisterClassBuilder)?.done(state.config.generateSmapCopyToAnnotation)
replaceFakeContinuationsWithRealOnes(
node, if (!inliningContext.isContinuation) getLastParameterIndex(node.desc, node.access) else 0
)
@@ -84,7 +84,7 @@ private fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateTypeO
intrinsicsSupport.reportSuspendTypeUnsupported()
}
if (intrinsicsSupport.state.stableTypeOf) {
if (intrinsicsSupport.state.config.stableTypeOf) {
if (intrinsicsSupport.isMutableCollectionType(type)) {
v.invokestatic(REFLECTION, "mutableCollectionType", Type.getMethodDescriptor(K_TYPE, K_TYPE), false)
} else if (type.typeConstructor().isNothingConstructor()) {
@@ -23,7 +23,7 @@ import org.jetbrains.org.objectweb.asm.tree.analysis.BasicVerifier
class MethodVerifier(private val checkPoint: String, private val generationState: GenerationState) : MethodTransformer() {
override fun transform(internalClassName: String, methodNode: MethodNode) {
if (!generationState.shouldValidateBytecode) return
if (!generationState.config.shouldValidateBytecode) return
try {
analyze(internalClassName, methodNode, BasicVerifier())
} catch (e: Throwable) {
@@ -69,7 +69,7 @@ class OptimizationMethodVisitor(
normalizationMethodTransformer.transform("fake", methodNode)
UninitializedStoresProcessor(methodNode).run()
if (!mandatoryTransformationsOnly && canBeOptimized(methodNode) && !generationState.disableOptimization) {
if (!mandatoryTransformationsOnly && canBeOptimized(methodNode) && !generationState.config.disableOptimization) {
optimizationTransformer.transform("fake", methodNode)
}
@@ -49,17 +49,17 @@ class JvmSerializerExtension @JvmOverloads constructor(
private val globalBindings = state.globalSerializationBindings
private val codegenBinding = state.bindingContext
override val stringTable = JvmCodegenStringTable(typeMapper)
private val useTypeTable = state.useTypeTableInSerializer
private val useTypeTable = state.config.useTypeTableInSerializer
private val moduleName = state.moduleName
private val classBuilderMode = state.classBuilderMode
private val languageVersionSettings = state.languageVersionSettings
private val isParamAssertionsDisabled = state.isParamAssertionsDisabled
private val unifiedNullChecks = state.unifiedNullChecks
private val functionsWithInlineClassReturnTypesMangled = state.functionsWithInlineClassReturnTypesMangled
override val metadataVersion = state.metadataVersion
private val isParamAssertionsDisabled = state.config.isParamAssertionsDisabled
private val unifiedNullChecks = state.config.unifiedNullChecks
private val functionsWithInlineClassReturnTypesMangled = state.config.functionsWithInlineClassReturnTypesMangled
override val metadataVersion = state.config.metadataVersion
private val jvmDefaultMode = state.jvmDefaultMode
private val approximator = state.typeApproximator
private val useOldManglingScheme = state.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
private val useOldManglingScheme = state.config.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
private val signatureSerializer = JvmSignatureSerializerImpl(stringTable)
override fun shouldUseTypeTable(): Boolean = useTypeTable
@@ -52,7 +52,6 @@ import org.jetbrains.kotlin.serialization.deserialization.DeserializationConfigu
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeApproximator
import org.jetbrains.kotlin.utils.metadataVersion
import org.jetbrains.org.objectweb.asm.Type
import java.io.File
@@ -179,7 +178,8 @@ class GenerationState private constructor(
}
}
val languageVersionSettings = configuration.languageVersionSettings
val config = JvmBackendConfig(configuration)
val languageVersionSettings = config.languageVersionSettings
val inlineCache: InlineCache = InlineCache()
@@ -219,7 +219,7 @@ class GenerationState private constructor(
}
}
val extraJvmDiagnosticsTrace: BindingTrace =
private val extraJvmDiagnosticsTrace: BindingTrace =
DelegatingBindingTrace(
originalFrontendBindingContext, "For extra diagnostics in ${this::class.java}", false,
customSuppressCache = if (isIrBackend) OnDemandSuppressCache(originalFrontendBindingContext) else null,
@@ -234,29 +234,6 @@ class GenerationState private constructor(
extraJvmDiagnosticsTrace.bindingContext.diagnostics
}
val useOldManglingSchemeForFunctionsWithInlineClassesInSignatures =
configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) ||
languageVersionSettings.languageVersion.run { major == 1 && minor < 4 }
val target = configuration.get(JVMConfigurationKeys.JVM_TARGET) ?: JvmTarget.DEFAULT
val runtimeStringConcat =
if (target.majorVersion >= JvmTarget.JVM_9.majorVersion)
configuration.get(JVMConfigurationKeys.STRING_CONCAT) ?: JvmStringConcat.INDY_WITH_CONSTANTS
else JvmStringConcat.INLINE
val samConversionsScheme: JvmClosureGenerationScheme =
configuration.get(JVMConfigurationKeys.SAM_CONVERSIONS)
?: if (languageVersionSettings.supportsFeature(LanguageFeature.SamWrapperClassesAreSynthetic))
JvmClosureGenerationScheme.INDY
else
JvmClosureGenerationScheme.CLASS
val lambdasScheme: JvmClosureGenerationScheme =
configuration.get(JVMConfigurationKeys.LAMBDAS)
?: if (languageVersionSettings.supportsFeature(LanguageFeature.LightweightLambdas))
JvmClosureGenerationScheme.INDY
else JvmClosureGenerationScheme.CLASS
val moduleName: String = moduleName ?: JvmCodegenUtil.getModuleName(module)
val classBuilderMode: ClassBuilderMode = builderFactory.classBuilderMode
val bindingTrace: BindingTrace = DelegatingBindingTrace(
@@ -270,27 +247,18 @@ class GenerationState private constructor(
classBuilderMode,
this.moduleName,
languageVersionSettings,
useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
target,
config.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
config.target,
isIrBackend
)
val canReplaceStdlibRuntimeApiBehavior = languageVersionSettings.apiVersion <= ApiVersion.parse(KotlinVersion.CURRENT.toString())!!
val intrinsics: IntrinsicMethods = IntrinsicMethods(canReplaceStdlibRuntimeApiBehavior)
val generateOptimizedCallableReferenceSuperClasses =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_OPTIMIZED_CALLABLE_REFERENCES)
val useKotlinNothingValueException =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_KOTLIN_NOTHING_VALUE_EXCEPTION)
// In 1.6, `typeOf` became stable and started to rely on a few internal stdlib functions which were missing before 1.6.
val stableTypeOf = languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_6
val intrinsics: IntrinsicMethods =
IntrinsicMethods(languageVersionSettings.apiVersion <= ApiVersion.parse(KotlinVersion.CURRENT.toString())!!)
val samWrapperClasses: SamWrapperClasses = SamWrapperClasses(this)
val globalInlineContext: GlobalInlineContext = GlobalInlineContext(diagnostics)
val mappingsClassesForWhenByEnum: MappingsClassesForWhenByEnum = MappingsClassesForWhenByEnum(this)
val jvmRuntimeTypes: JvmRuntimeTypes = JvmRuntimeTypes(
module, languageVersionSettings, generateOptimizedCallableReferenceSuperClasses
module, languageVersionSettings, config.generateOptimizedCallableReferenceSuperClasses
)
val factory: ClassFileFactory
private var duplicateSignatureFactory: BuilderFactoryForDuplicateSignatureDiagnostics? = null
@@ -307,53 +275,10 @@ class GenerationState private constructor(
var resultType: KotlinType? = null
}
val isCallAssertionsDisabled: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_CALL_ASSERTIONS)
val isReceiverAssertionsDisabled: Boolean =
configuration.getBoolean(JVMConfigurationKeys.DISABLE_RECEIVER_ASSERTIONS) ||
!languageVersionSettings.supportsFeature(LanguageFeature.NullabilityAssertionOnExtensionReceiver)
val isParamAssertionsDisabled: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS)
val assertionsMode: JVMAssertionsMode = configuration.get(JVMConfigurationKeys.ASSERTIONS_MODE, JVMAssertionsMode.DEFAULT)
val isInlineDisabled: Boolean = configuration.getBoolean(CommonConfigurationKeys.DISABLE_INLINE)
val useTypeTableInSerializer: Boolean = configuration.getBoolean(JVMConfigurationKeys.USE_TYPE_TABLE)
val unifiedNullChecks: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_UNIFIED_NULL_CHECKS)
val noSourceCodeInNotNullAssertionExceptions: Boolean =
(languageVersionSettings.supportsFeature(LanguageFeature.NoSourceCodeInNotNullAssertionExceptions)
// This check is needed because we generate calls to `Intrinsics.checkNotNull` which is only available since 1.4
// (when unified null checks were introduced).
&& unifiedNullChecks)
// Never generate source code in assertion exceptions in K2 to make behavior of FIR PSI & FIR light-tree equivalent
// (obtaining source code is not supported in light tree).
|| languageVersionSettings.languageVersion.usesK2
val generateSmapCopyToAnnotation: Boolean = !configuration.getBoolean(JVMConfigurationKeys.NO_SOURCE_DEBUG_EXTENSION)
val functionsWithInlineClassReturnTypesMangled: Boolean =
languageVersionSettings.supportsFeature(LanguageFeature.MangleClassMembersReturningInlineClasses)
val shouldValidateIr = configuration.getBoolean(JVMConfigurationKeys.VALIDATE_IR)
val shouldValidateBytecode = configuration.getBoolean(JVMConfigurationKeys.VALIDATE_BYTECODE)
val rootContext: CodegenContext<*> = RootContext(this)
val classFileVersion: Int = run {
val minorVersion = if (configuration.getBoolean(JVMConfigurationKeys.ENABLE_JVM_PREVIEW)) 0xffff else 0
(minorVersion shl 16) + target.majorVersion
}
val generateParametersMetadata: Boolean = configuration.getBoolean(JVMConfigurationKeys.PARAMETERS_METADATA)
val shouldInlineConstVals = languageVersionSettings.supportsFeature(LanguageFeature.InlineConstVals)
val jvmDefaultMode = languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
val disableOptimization = configuration.get(JVMConfigurationKeys.DISABLE_OPTIMIZATION, false)
val metadataVersion = configuration.metadataVersion()
val abiStability = configuration.get(JVMConfigurationKeys.ABI_STABILITY)
val noNewJavaAnnotationTargets = configuration.getBoolean(JVMConfigurationKeys.NO_NEW_JAVA_ANNOTATION_TARGETS)
val jvmDefaultMode: JvmDefaultMode
get() = config.jvmDefaultMode
val globalSerializationBindings = JvmSerializationBindings()
var mapInlineClass: (ClassDescriptor) -> Type = { descriptor -> typeMapper.mapType(descriptor.defaultType) }
@@ -372,8 +297,6 @@ class GenerationState private constructor(
else
null
val oldInnerClassesLogic = configuration.getBoolean(JVMConfigurationKeys.OLD_INNER_CLASSES_LOGIC)
init {
this.interceptedBuilderFactory = builderFactory
.wrapWith(
@@ -391,7 +314,7 @@ class GenerationState private constructor(
else
BuilderFactoryForDuplicateSignatureDiagnostics(
it, bindingContext, diagnostics, this.moduleName, languageVersionSettings,
useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
config.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
shouldGenerate = { origin -> !shouldOnlyCollectSignatures(origin) },
).apply { duplicateSignatureFactory = this }
},
@@ -0,0 +1,103 @@
/*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.codegen.state
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.utils.metadataVersion
class JvmBackendConfig(configuration: CompilerConfiguration) {
val languageVersionSettings: LanguageVersionSettings = configuration.languageVersionSettings
val target: JvmTarget =
configuration.get(JVMConfigurationKeys.JVM_TARGET) ?: JvmTarget.DEFAULT
val useOldManglingSchemeForFunctionsWithInlineClassesInSignatures: Boolean =
configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) ||
languageVersionSettings.languageVersion.run { major == 1 && minor < 4 }
val runtimeStringConcat: JvmStringConcat =
if (target.majorVersion >= JvmTarget.JVM_9.majorVersion)
configuration.get(JVMConfigurationKeys.STRING_CONCAT) ?: JvmStringConcat.INDY_WITH_CONSTANTS
else JvmStringConcat.INLINE
val samConversionsScheme: JvmClosureGenerationScheme =
configuration.get(JVMConfigurationKeys.SAM_CONVERSIONS)
?: if (languageVersionSettings.supportsFeature(LanguageFeature.SamWrapperClassesAreSynthetic))
JvmClosureGenerationScheme.INDY
else
JvmClosureGenerationScheme.CLASS
val lambdasScheme: JvmClosureGenerationScheme =
configuration.get(JVMConfigurationKeys.LAMBDAS)
?: if (languageVersionSettings.supportsFeature(LanguageFeature.LightweightLambdas))
JvmClosureGenerationScheme.INDY
else JvmClosureGenerationScheme.CLASS
val useKotlinNothingValueException: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_KOTLIN_NOTHING_VALUE_EXCEPTION)
// In 1.6, `typeOf` became stable and started to rely on a few internal stdlib functions which were missing before 1.6.
val stableTypeOf: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_6
val generateOptimizedCallableReferenceSuperClasses: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_OPTIMIZED_CALLABLE_REFERENCES)
val isCallAssertionsDisabled: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_CALL_ASSERTIONS)
val isReceiverAssertionsDisabled: Boolean =
configuration.getBoolean(JVMConfigurationKeys.DISABLE_RECEIVER_ASSERTIONS) ||
!languageVersionSettings.supportsFeature(LanguageFeature.NullabilityAssertionOnExtensionReceiver)
val isParamAssertionsDisabled: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS)
val assertionsMode: JVMAssertionsMode = configuration.get(JVMConfigurationKeys.ASSERTIONS_MODE, JVMAssertionsMode.DEFAULT)
val isInlineDisabled: Boolean = configuration.getBoolean(CommonConfigurationKeys.DISABLE_INLINE)
val useTypeTableInSerializer: Boolean = configuration.getBoolean(JVMConfigurationKeys.USE_TYPE_TABLE)
val unifiedNullChecks: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_UNIFIED_NULL_CHECKS)
val noSourceCodeInNotNullAssertionExceptions: Boolean =
(languageVersionSettings.supportsFeature(LanguageFeature.NoSourceCodeInNotNullAssertionExceptions)
// This check is needed because we generate calls to `Intrinsics.checkNotNull` which is only available since 1.4
// (when unified null checks were introduced).
&& unifiedNullChecks)
// Never generate source code in assertion exceptions in K2 to make behavior of FIR PSI & FIR light-tree equivalent
// (obtaining source code is not supported in light tree).
|| languageVersionSettings.languageVersion.usesK2
val generateSmapCopyToAnnotation: Boolean = !configuration.getBoolean(JVMConfigurationKeys.NO_SOURCE_DEBUG_EXTENSION)
val functionsWithInlineClassReturnTypesMangled: Boolean =
languageVersionSettings.supportsFeature(LanguageFeature.MangleClassMembersReturningInlineClasses)
val shouldValidateIr: Boolean = configuration.getBoolean(JVMConfigurationKeys.VALIDATE_IR)
val shouldValidateBytecode: Boolean = configuration.getBoolean(JVMConfigurationKeys.VALIDATE_BYTECODE)
val classFileVersion: Int = run {
val minorVersion = if (configuration.getBoolean(JVMConfigurationKeys.ENABLE_JVM_PREVIEW)) 0xffff else 0
(minorVersion shl 16) + target.majorVersion
}
val generateParametersMetadata: Boolean = configuration.getBoolean(JVMConfigurationKeys.PARAMETERS_METADATA)
val shouldInlineConstVals: Boolean = languageVersionSettings.supportsFeature(LanguageFeature.InlineConstVals)
val jvmDefaultMode: JvmDefaultMode = languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
val disableOptimization: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_OPTIMIZATION)
val metadataVersion: BinaryVersion = configuration.metadataVersion()
val abiStability: JvmAbiStability? = configuration.get(JVMConfigurationKeys.ABI_STABILITY)
val noNewJavaAnnotationTargets: Boolean = configuration.getBoolean(JVMConfigurationKeys.NO_NEW_JAVA_ANNOTATION_TARGETS)
val oldInnerClassesLogic: Boolean = configuration.getBoolean(JVMConfigurationKeys.OLD_INNER_CLASSES_LOGIC)
}
@@ -46,7 +46,7 @@ public class MappingClassesForWhenByEnumCodegen {
ClassBuilder cb = state.getFactory().newVisitor(JvmDeclarationOrigin.NO_ORIGIN, mappingsClass, srcFile);
cb.defineClass(
srcFile,
state.getClassFileVersion(),
state.getConfig().getClassFileVersion(),
ACC_PUBLIC | ACC_FINAL | ACC_SUPER | ACC_SYNTHETIC,
mappingsClass.getInternalName(),
null,
@@ -60,7 +60,7 @@ public class MappingClassesForWhenByEnumCodegen {
boolean publicAbi = mappings.stream().anyMatch(WhenByEnumsMapping::isPublicAbi);
WriteAnnotationUtilKt.writeSyntheticClassMetadata(cb, state, publicAbi);
cb.done(state.getGenerateSmapCopyToAnnotation());
cb.done(state.getConfig().getGenerateSmapCopyToAnnotation());
}
private static void generateFields(@NotNull ClassBuilder cb, @NotNull List<WhenByEnumsMapping> mappings) {
@@ -34,8 +34,8 @@ private constructor(
private val shouldInlineConstVals: Boolean,
private val codegen: ExpressionCodegen?
) {
constructor(state: GenerationState) : this(state.bindingContext, state.shouldInlineConstVals, null)
constructor(codegen: ExpressionCodegen) : this(codegen.bindingContext, codegen.state.shouldInlineConstVals, codegen)
constructor(state: GenerationState) : this(state.bindingContext, state.config.shouldInlineConstVals, null)
constructor(codegen: ExpressionCodegen) : this(codegen.bindingContext, codegen.state.config.shouldInlineConstVals, codegen)
fun checkAllItemsAreConstantsSatisfying(expression: KtWhenExpression, predicate: Function1<ConstantValue<*>, Boolean>): Boolean =
expression.entries.all { entry ->
@@ -32,8 +32,8 @@ fun writeKotlinMetadata(
action: (AnnotationVisitor) -> Unit
) {
val av = cb.newAnnotation(JvmAnnotationNames.METADATA_DESC, true)
av.visit(JvmAnnotationNames.METADATA_VERSION_FIELD_NAME, state.metadataVersion.toArray())
if (!state.metadataVersion.isAtLeast(1, 5, 0)) {
av.visit(JvmAnnotationNames.METADATA_VERSION_FIELD_NAME, state.config.metadataVersion.toArray())
if (!state.config.metadataVersion.isAtLeast(1, 5, 0)) {
av.visit("bv", JvmBytecodeBinaryVersion.INSTANCE.toArray())
}
av.visit(JvmAnnotationNames.KIND_FIELD_NAME, kind.id)