diff --git a/backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/IrToBitcode.kt b/backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/IrToBitcode.kt index 061294d1616..757a49345f3 100644 --- a/backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/IrToBitcode.kt +++ b/backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/IrToBitcode.kt @@ -1151,9 +1151,13 @@ internal class CodeGeneratorVisitor(val context: Context) : IrElementVisitorVoid if (!isNothing) // If "when" has "exit". bbExit = codegen.basicBlock() // Create basic block to process "exit". - val resultPhi = if (isUnit || isNothing) null else + val hasNoValue = !isUnconditional(expression.branches.last()) + // (It is possible if IrWhen is used as statement). + + val llvmType = codegen.getLLVMType(expression.type) + val resultPhi = if (isUnit || isNothing || hasNoValue) null else codegen.appendingTo(bbExit!!) { - codegen.phi(codegen.getLLVMType(expression.type)) + codegen.phi(llvmType) } expression.branches.forEach { // Iterate through "when" branches (clauses). @@ -1167,6 +1171,7 @@ internal class CodeGeneratorVisitor(val context: Context) : IrElementVisitorVoid // FIXME: remove the hacks. isUnit -> codegen.theUnitInstanceRef.llvm isNothing -> codegen.kNothingFakeValue + hasNoValue -> LLVMGetUndef(llvmType)!! else -> resultPhi!! } } diff --git a/backend.native/tests/build.gradle b/backend.native/tests/build.gradle index 99331dfdbae..2fd9aecb9f4 100644 --- a/backend.native/tests/build.gradle +++ b/backend.native/tests/build.gradle @@ -330,6 +330,11 @@ task when8(type: RunKonanTest) { goldValue = "true\n" } +task when9(type: RunKonanTest) { + goldValue = "Ok\n" + source = "codegen/branching/when9.kt" +} + task when_through(type: RunKonanTest) { source = "codegen/branching/when_through.kt" } diff --git a/backend.native/tests/codegen/branching/when9.kt b/backend.native/tests/codegen/branching/when9.kt new file mode 100644 index 00000000000..02ad49de4c8 --- /dev/null +++ b/backend.native/tests/codegen/branching/when9.kt @@ -0,0 +1,10 @@ +fun main(args: Array) { + foo(0) + println("Ok") +} + +fun foo(x: Int) { + when (x) { + 0 -> 0 + } +} \ No newline at end of file