when: emit switch for String if possible

Effectively, the following when structure:

  when (s) {
    s1, s2 -> e1,
    s3 -> e2,
    s4 -> e3,
    ...
    else -> e
  }

is implemented as:

  when (s.hashCode()) {
    h1 -> {
      if (s == s1)
        e1
      else if (s == s2)
        e1
      else if (s == s3)
        e2
      else
        e
    }
    h2 -> if (s == s3) e2 else e,
    ...
    else -> e
  }

where s1.hashCode() == s2.hashCode() == s3.hashCode() == h1,
      s4.hashCode() == h2.

A tableswitch or lookupswitch is used for the hash code lookup.

Change-Id: I087bf623dbb4a41d3cc64399a1b42342a50757a6
This commit is contained in:
Ting-Yuan Huang
2019-03-07 17:26:58 -08:00
committed by max-kammerer
parent 1a9ed88be4
commit f6cf434650
22 changed files with 570 additions and 70 deletions
@@ -3418,6 +3418,11 @@ public class BytecodeTextTestGenerated extends AbstractBytecodeTextTest {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/bytecodeText/when"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.JVM, true);
}
@TestMetadata("edgeCases.kt")
public void testEdgeCases() throws Exception {
runTest("compiler/testData/codegen/bytecodeText/when/edgeCases.kt");
}
@TestMetadata("exhaustiveWhenInitialization.kt")
public void testExhaustiveWhenInitialization() throws Exception {
runTest("compiler/testData/codegen/bytecodeText/when/exhaustiveWhenInitialization.kt");
@@ -3498,6 +3503,11 @@ public class BytecodeTextTestGenerated extends AbstractBytecodeTextTest {
runTest("compiler/testData/codegen/bytecodeText/when/subjectValInStringWhenHasLocalVariableSlot.kt");
}
@TestMetadata("switchOptimizationDuplicates.kt")
public void testSwitchOptimizationDuplicates() throws Exception {
runTest("compiler/testData/codegen/bytecodeText/when/switchOptimizationDuplicates.kt");
}
@TestMetadata("tableSwitch.kt")
public void testTableSwitch() throws Exception {
runTest("compiler/testData/codegen/bytecodeText/when/tableSwitch.kt");
@@ -3629,6 +3639,16 @@ public class BytecodeTextTestGenerated extends AbstractBytecodeTextTest {
runTest("compiler/testData/codegen/bytecodeText/whenStringOptimization/duplicatingItemsSameHashCode.kt");
}
@TestMetadata("duplicatingItemsSameHashCode2.kt")
public void testDuplicatingItemsSameHashCode2() throws Exception {
runTest("compiler/testData/codegen/bytecodeText/whenStringOptimization/duplicatingItemsSameHashCode2.kt");
}
@TestMetadata("duplicatingItemsSameHashCode3.kt")
public void testDuplicatingItemsSameHashCode3() throws Exception {
runTest("compiler/testData/codegen/bytecodeText/whenStringOptimization/duplicatingItemsSameHashCode3.kt");
}
@TestMetadata("expression.kt")
public void testExpression() throws Exception {
runTest("compiler/testData/codegen/bytecodeText/whenStringOptimization/expression.kt");