summaryrefslogtreecommitdiff
path: root/test/junit
diff options
context:
space:
mode:
Diffstat (limited to 'test/junit')
-rw-r--r--test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala19
-rw-r--r--test/junit/scala/tools/nsc/backend/jvm/analysis/NullnessAnalyzerTest.scala2
-rw-r--r--test/junit/scala/tools/nsc/backend/jvm/opt/AnalyzerTest.scala63
-rw-r--r--test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala40
-rw-r--r--test/junit/scala/tools/nsc/backend/jvm/opt/InlinerSeparateCompilationTest.scala1
-rw-r--r--test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala323
-rw-r--r--test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOpts.scala92
-rw-r--r--test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOptsTest.scala562
8 files changed, 970 insertions, 132 deletions
diff --git a/test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala b/test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala
index 1f2ec274d3..69c3f69380 100644
--- a/test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala
+++ b/test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala
@@ -166,6 +166,19 @@ object CodeGenTools {
assertTrue(s"\nExpected: $expected\nActual : $actual", actual === expected)
}
+ def assertNoInvoke(m: Method): Unit = assertNoInvoke(m.instructions)
+ def assertNoInvoke(ins: List[Instruction]): Unit = {
+ assert(!ins.exists(_.isInstanceOf[Invoke]), ins.stringLines)
+ }
+
+ def assertInvoke(m: Method, receiver: String, method: String): Unit = assertInvoke(m.instructions, receiver, method)
+ def assertInvoke(l: List[Instruction], receiver: String, method: String): Unit = {
+ assert(l.exists {
+ case Invoke(_, `receiver`, `method`, _, _) => true
+ case _ => false
+ }, l.stringLines)
+ }
+
def getSingleMethod(classNode: ClassNode, name: String): Method =
convertMethod(classNode.methods.asScala.toList.find(_.name == name).get)
@@ -179,7 +192,7 @@ object CodeGenTools {
def findInstr(method: MethodNode, query: String): List[AbstractInsnNode] = {
val useNext = query(0) == '+'
val instrPart = if (useNext) query.drop(1) else query
- val insns = method.instructions.iterator.asScala.find(i => textify(i) contains instrPart).toList
+ val insns = method.instructions.iterator.asScala.filter(i => textify(i) contains instrPart).toList
if (useNext) insns.map(_.getNext) else insns
}
@@ -195,4 +208,8 @@ object CodeGenTools {
implicit class MortalInstruction(val ins: Instruction) extends AnyVal {
def dead: (Instruction, Boolean) = (ins, false)
}
+
+ implicit class listStringLines[T](val l: List[T]) extends AnyVal {
+ def stringLines = l.mkString("\n")
+ }
}
diff --git a/test/junit/scala/tools/nsc/backend/jvm/analysis/NullnessAnalyzerTest.scala b/test/junit/scala/tools/nsc/backend/jvm/analysis/NullnessAnalyzerTest.scala
index a7d1dc168a..daff6fc223 100644
--- a/test/junit/scala/tools/nsc/backend/jvm/analysis/NullnessAnalyzerTest.scala
+++ b/test/junit/scala/tools/nsc/backend/jvm/analysis/NullnessAnalyzerTest.scala
@@ -33,7 +33,7 @@ class NullnessAnalyzerTest extends ClearAfterClass {
val noOptCompiler = NullnessAnalyzerTest.noOptCompiler
import noOptCompiler.genBCode.bTypes.backendUtils._
- def newNullnessAnalyzer(methodNode: MethodNode, classInternalName: InternalName = "C") = new AsmAnalyzer(methodNode, classInternalName, new NullnessAnalyzer)
+ def newNullnessAnalyzer(methodNode: MethodNode, classInternalName: InternalName = "C") = new AsmAnalyzer(methodNode, classInternalName, new NullnessAnalyzer(noOptCompiler.genBCode.bTypes))
def testNullness(analyzer: AsmAnalyzer[NullnessValue], method: MethodNode, query: String, index: Int, nullness: NullnessValue): Unit = {
for (i <- findInstr(method, query)) {
diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/AnalyzerTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/AnalyzerTest.scala
new file mode 100644
index 0000000000..11014f5e64
--- /dev/null
+++ b/test/junit/scala/tools/nsc/backend/jvm/opt/AnalyzerTest.scala
@@ -0,0 +1,63 @@
+package scala.tools.nsc
+package backend.jvm
+package opt
+
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import org.junit.Test
+import org.junit.Assert._
+
+import scala.tools.asm.tree._
+import scala.tools.asm.tree.analysis._
+import scala.tools.nsc.backend.jvm.analysis.{AliasingFrame, AliasingAnalyzer}
+
+import CodeGenTools._
+import scala.tools.partest.ASMConverters
+import ASMConverters._
+import AsmUtils._
+import BackendReporting._
+import BytecodeUtils._
+
+import scala.collection.convert.decorateAsScala._
+import scala.tools.testing.ClearAfterClass
+
+object AnalyzerTest extends ClearAfterClass.Clearable {
+ var noOptCompiler = newCompiler(extraArgs = "-Yopt:l:none")
+ def clear(): Unit = { noOptCompiler = null }
+}
+
+@RunWith(classOf[JUnit4])
+class AnalyzerTest extends ClearAfterClass {
+ ClearAfterClass.stateToClear = AnalyzerTest
+ val noOptCompiler = AnalyzerTest.noOptCompiler
+
+ @Test
+ def aliasingOfPrimitives(): Unit = {
+ val code =
+ """class C {
+ | def f(a: Int, b: Long) = {
+ | val c = a - b // a is converted with i2l
+ | val d = c
+ | val e = a
+ | // locals: 0 this -- 1 a -- 2-3 b -- 4-5 c -- 6-7 d -- 8 e
+ | e + d // e is converted with i2l
+ | }
+ |}
+ """.stripMargin
+
+ val List(c) = compileClasses(noOptCompiler)(code)
+ val a = new AliasingAnalyzer(new BasicInterpreter)
+ val f = findAsmMethod(c, "f")
+ a.analyze("C", f)
+
+ val List(_, i2l) = findInstr(f, "I2L")
+ val aliasesAtI2l = a.frameAt(i2l, f).asInstanceOf[AliasingFrame[_]].aliases
+ assertEquals(aliasesAtI2l(1).iterator.toList, List(1, 8, 9)) // a, e and stack top
+ assertEquals(aliasesAtI2l(4).iterator.toList, List(4, 6))
+
+ val List(add) = findInstr(f, "LADD")
+ val aliasesAtAdd = a.frameAt(add, f).asInstanceOf[AliasingFrame[_]].aliases
+ assertEquals(aliasesAtAdd(1).iterator.toList, List(1, 8)) // after i2l the value on the stack is no longer an alias
+ assertEquals(aliasesAtAdd(4).iterator.toList, List(4, 6, 10)) // c, d and stack top
+ }
+}
diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala
index 735bbefbbb..b314643fb1 100644
--- a/test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala
+++ b/test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala
@@ -49,7 +49,7 @@ class ClosureOptimizerTest extends ClearAfterClass {
""".stripMargin
val List(c) = compileClasses(compiler)(code)
- val t = c.methods.asScala.toList.find(_.name == "t").get
+ val t = findAsmMethod(c, "t")
val List(bodyCall) = findInstr(t, "INVOKESTATIC C.C$$$anonfun$1 ()Lscala/runtime/Nothing$")
assert(bodyCall.getNext.getOpcode == ATHROW)
}
@@ -65,9 +65,45 @@ class ClosureOptimizerTest extends ClearAfterClass {
""".stripMargin
val List(c) = compileClasses(compiler)(code)
- val t = c.methods.asScala.toList.find(_.name == "t").get
+ val t = findAsmMethod(c, "t")
val List(bodyCall) = findInstr(t, "INVOKESTATIC C.C$$$anonfun$1 ()Lscala/runtime/Null$")
assert(bodyCall.getNext.getOpcode == POP)
assert(bodyCall.getNext.getNext.getOpcode == ACONST_NULL)
}
+
+ @Test
+ def makeLMFCastExplicit(): Unit = {
+ val code =
+ """class C {
+ | def t(l: List[String]) = {
+ | val fun: String => String = s => s
+ | fun(l.head)
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(compiler)(code)
+ assertSameCode(getSingleMethod(c, "t").instructions.dropNonOp,
+ List(VarOp(ALOAD, 1), Invoke(INVOKEVIRTUAL, "scala/collection/immutable/List", "head", "()Ljava/lang/Object;", false),
+ TypeOp(CHECKCAST, "java/lang/String"), Invoke(INVOKESTATIC, "C", "C$$$anonfun$1", "(Ljava/lang/String;)Ljava/lang/String;", false),
+ Op(ARETURN)))
+ }
+
+ @Test
+ def closureOptWithUnreachableCode(): Unit = {
+ // this example used to crash the ProdCons analysis in the closure optimizer - ProdCons
+ // expects no unreachable code.
+ val code =
+ """class C {
+ | @inline final def m = throw new Error("")
+ | def t = {
+ | val f = (x: Int) => x + 1
+ | m
+ | f(10) // unreachable after inlining m
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(compiler)(code)
+ assertEquals(getSingleMethod(c, "t").instructions.summary,
+ List(NEW, DUP, LDC, "<init>", ATHROW))
+ }
}
diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerSeparateCompilationTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerSeparateCompilationTest.scala
index 5c9bd1c188..44b6c7ca9e 100644
--- a/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerSeparateCompilationTest.scala
+++ b/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerSeparateCompilationTest.scala
@@ -22,7 +22,6 @@ object InlinerSeparateCompilationTest {
@RunWith(classOf[JUnit4])
class InlinerSeparateCompilationTest {
import InlinerSeparateCompilationTest._
- import InlinerTest.{listStringLines, assertInvoke, assertNoInvoke}
@Test
def inlnieMixedinMember(): Unit = {
diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala
index 1e01627969..192a036d5b 100644
--- a/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala
+++ b/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala
@@ -23,8 +23,9 @@ import scala.collection.convert.decorateAsScala._
import scala.tools.testing.ClearAfterClass
object InlinerTest extends ClearAfterClass.Clearable {
- val args = "-Ybackend:GenBCode -Yopt:l:classpath -Yopt-warnings"
+ val args = "-Yopt:l:classpath -Yopt-warnings"
var compiler = newCompiler(extraArgs = args)
+ var inlineOnlyCompiler = newCompiler(extraArgs = "-Yopt:inline-project")
// allows inspecting the caches after a compilation run
def notPerRun: List[Clearable] = List(
@@ -34,37 +35,20 @@ object InlinerTest extends ClearAfterClass.Clearable {
compiler.genBCode.bTypes.callGraph.callsites)
notPerRun foreach compiler.perRunCaches.unrecordCache
- def clear(): Unit = { compiler = null }
-
- implicit class listStringLines[T](val l: List[T]) extends AnyVal {
- def stringLines = l.mkString("\n")
- }
-
- def assertNoInvoke(m: Method): Unit = assertNoInvoke(m.instructions)
- def assertNoInvoke(ins: List[Instruction]): Unit = {
- assert(!ins.exists(_.isInstanceOf[Invoke]), ins.stringLines)
- }
-
- def assertInvoke(m: Method, receiver: String, method: String): Unit = assertInvoke(m.instructions, receiver, method)
- def assertInvoke(l: List[Instruction], receiver: String, method: String): Unit = {
- assert(l.exists {
- case Invoke(_, `receiver`, `method`, _, _) => true
- case _ => false
- }, l.stringLines)
- }
+ def clear(): Unit = { compiler = null; inlineOnlyCompiler = null }
}
@RunWith(classOf[JUnit4])
class InlinerTest extends ClearAfterClass {
ClearAfterClass.stateToClear = InlinerTest
- import InlinerTest.{listStringLines, assertInvoke, assertNoInvoke}
-
val compiler = InlinerTest.compiler
import compiler.genBCode.bTypes._
import compiler.genBCode.bTypes.backendUtils._
import inlinerHeuristics._
+ val inlineOnlyCompiler = InlinerTest.inlineOnlyCompiler
+
def compile(scalaCode: String, javaCode: List[(String, String)] = Nil, allowMessage: StoreReporter#Info => Boolean = _ => false): List[ClassNode] = {
InlinerTest.notPerRun.foreach(_.clear())
compileClasses(compiler)(scalaCode, javaCode, allowMessage)
@@ -148,15 +132,22 @@ class InlinerTest extends ClearAfterClass {
// See also discussion around ATHROW in BCodeBodyBuilder
val g = inlineTest(code)
- val expectedInlined = List(
- VarOp(ALOAD, 0), VarOp(ASTORE, 1), // store this
- Field(GETSTATIC, "scala/Predef$", "MODULE$", "Lscala/Predef$;"), Invoke(INVOKEVIRTUAL, "scala/Predef$", "$qmark$qmark$qmark", "()Lscala/runtime/Nothing$;", false)) // inlined call to ???
- assertSameCode(convertMethod(g).instructions.dropNonOp.take(4), expectedInlined)
+ val invokeQQQ = List(
+ Field(GETSTATIC, "scala/Predef$", "MODULE$", "Lscala/Predef$;"),
+ Invoke(INVOKEVIRTUAL, "scala/Predef$", "$qmark$qmark$qmark", "()Lscala/runtime/Nothing$;", false))
+
+ val gBeforeLocalOpt = VarOp(ALOAD, 0) :: VarOp(ASTORE, 1) :: invokeQQQ ::: List(
+ VarOp(ASTORE, 2),
+ Jump(GOTO, Label(11)),
+ Label(11),
+ VarOp(ALOAD, 2),
+ Op(ATHROW))
+
+ assertSameCode(convertMethod(g).instructions.dropNonOp, gBeforeLocalOpt)
compiler.genBCode.bTypes.localOpt.methodOptimizations(g, "C")
- assertSameCode(convertMethod(g).instructions.dropNonOp,
- expectedInlined ++ List(VarOp(ASTORE, 2), VarOp(ALOAD, 2), Op(ATHROW)))
+ assertSameCode(convertMethod(g).instructions.dropNonOp, invokeQQQ :+ Op(ATHROW))
}
@Test
@@ -396,7 +387,8 @@ class InlinerTest extends ClearAfterClass {
|}
""".stripMargin
- val List(c) = compile(code)
+ // use a compiler without local optimizations (cleanups)
+ val List(c) = compileClasses(inlineOnlyCompiler)(code)
val ms @ List(f1, f2, g1, g2) = c.methods.asScala.filter(_.name.length == 2).toList
// stack height at callsite of f1 is 1, so max of g1 after inlining is max of f1 + 1
@@ -959,7 +951,7 @@ class InlinerTest extends ClearAfterClass {
val List(c) = compile(code)
val t = getSingleMethod(c, "t").instructions
assertNoInvoke(t)
- assert(2 == t.collect({case Ldc(_, "hai!") => }).size) // twice the body of f
+ assert(1 == t.collect({case Ldc(_, "hai!") => }).size) // push-pop eliminates the first LDC("hai!")
assert(1 == t.collect({case Jump(IFNONNULL, _) => }).size) // one single null check
}
@@ -985,17 +977,17 @@ class InlinerTest extends ClearAfterClass {
val List(c, _, _) = compile(code)
val t1 = getSingleMethod(c, "t1")
- assert(t1.instructions exists {
- case _: InvokeDynamic => true
- case _ => false
+ assert(t1.instructions forall { // indy is eliminated by push-pop
+ case _: InvokeDynamic => false
+ case _ => true
})
// the indy call is inlined into t, and the closure elimination rewrites the closure invocation to the body method
assertInvoke(t1, "C", "C$$$anonfun$2")
val t2 = getSingleMethod(c, "t2")
- assert(t2.instructions exists {
- case _: InvokeDynamic => true
- case _ => false
+ assert(t2.instructions forall { // indy is eliminated by push-pop
+ case _: InvokeDynamic => false
+ case _ => true
})
assertInvoke(t2, "M$", "M$$$anonfun$1")
}
@@ -1215,4 +1207,265 @@ class InlinerTest extends ClearAfterClass {
assertNoInvoke(getSingleMethod(c, "g"))
assertNoInvoke(getSingleMethod(d, "t"))
}
+
+ @Test
+ def optimizeSpecializedClosures(): Unit = {
+ val code =
+ """class ValKl(val x: Int) extends AnyVal
+ |
+ |class C {
+ | def t1 = {
+ | // IndyLambda: SAM type is JFunction1$mcII$sp, SAM is apply$mcII$sp(I)I, body method is $anonfun(I)I
+ | val f = (x: Int) => x + 1
+ | // invocation of apply$mcII$sp(I)I, matches the SAM in IndyLambda. no boxing / unboxing needed.
+ | f(10)
+ | // opt: re-write the invocation to the body method
+ | }
+ |
+ | @inline final def m1a(f: Long => Int) = f(1l)
+ | def t1a = m1a(l => l.toInt) // after inlining m1a, we have the same situation as in t1
+ |
+ | def t2 = {
+ | // there is no specialized variant of Function2 for this combination of types, so the IndyLambda has to create a generic Function2.
+ | // IndyLambda: SAM type is JFunction2, SAM is apply(ObjectObject)Object, body method is $anonfun$adapted(ObjectObject)Object
+ | val f = (b: Byte, i: Int) => i + b
+ | // invocation of apply(ObjectOjbect)Object, matches SAM in IndyLambda. arguments are boxed, result unboxed.
+ | f(1, 2)
+ | // opt: re-wrtie to $anonfun$adapted
+ | // inline that call, then we get box-unbox pairs (can be eliminated) and a call to $anonfun(BI)I
+ | }
+ |
+ | def t3 = {
+ | // similar to t2: for functions with value class parameters, IndyLambda always uses the generic Function version.
+ | // IndyLambda: SAM type is JFunction1, SAM is apply(Object)Object, body method is $anonfun$adapted(Object)Object
+ | val f = (a: ValKl) => a
+ | // invocation of apply(Object)Object, ValKl instance is created, result extracted
+ | f(new ValKl(1))
+ | // opt: re-write to $anonfun$adapted.
+ | // inline that call, then we get value class instantiation-extraction pairs and a call to $anonfun(I)I
+ | }
+ |
+ | def t4 = {
+ | // IndyLambda: SAM type is JFunction1$mcII$sp, SAM is apply$mcII$sp(I)I, body method is $anonfun(I)I
+ | val f: Int => Any = (x: Int) => 1
+ | // invocation of apply(Object)Object, argument is boxed. method name and type doesn't match IndyLambda.
+ | f(10)
+ | // opt: rewriting to the body method requires inserting an unbox operation for the argument, and a box operation for the result
+ | // that produces a box-unbox pair and a call to $anonfun(I)I
+ | }
+ |
+ |
+ | @inline final def m4a[T, U, V](f: (T, U) => V, x: T, y: U) = f(x, y) // invocation to generic apply(ObjectObject)Object
+ | def t4a = m4a((x: Int, y: Double) => 1l + x + y.toLong, 1, 2d) // IndyLambda uses specilized JFunction2$mcJID$sp. after inlining m4a, similar to t4.
+ |
+ | def t5 = {
+ | // no specialization for the comibnation of primitives
+ | // IndyLambda: SAM type is JFunction2, SAM is generic apply, body method is $anonfun$adapted
+ | val f: (Int, Byte) => Any = (x: Int, b: Byte) => 1
+ | // invocation of generic apply.
+ | f(10, 3)
+ | // opt: re-write to $anonfun$adapted, inline that method. generates box-unbox pairs and a call to $anonfun(IB)I
+ | }
+ |
+ | def t5a = m4a((x: Int, y: Byte) => 1, 12, 31.toByte) // similar to t5 after inlining m4a
+ |
+ | // m6$mIVc$sp invokes apply$mcVI$sp
+ | @inline final def m6[@specialized(Int) T, @specialized(Unit) U](f: T => U, x: T): Unit = f(x)
+ | // IndyLambda: JFunction1$mcVI$sp, SAM is apply$mcVI$sp, body method $anonfun(I)V
+ | // invokes m6$mIVc$sp (Lscala/Function1;I)V
+ | def t6 = m6((x: Int) => (), 10)
+ | // opt: after inlining m6, the closure method invocation (apply$mcVI$sp) matches the IndyLambda, the call can be rewritten, no boxing
+ |
+ | // m7 invokes apply
+ | @inline final def m7[@specialized(Boolean) T, @specialized(Int) U](f: T => U, x: T): Unit = f(x)
+ | // IndyLambda: JFunction1, SAM is apply(Object)Object, body method is $anonfun$adapted(Obj)Obj
+ | // `true` is boxed before passing to m7
+ | def t7 = m7((x: Boolean) => (), true)
+ | // opt: after inlining m7, the apply call is re-written to $anonfun$adapted, which is then inlined.
+ | // we get a box-unbox pair and a call to $anonfun(Z)V
+ |
+ |
+ | // invokes the generic apply(ObjObj)Obj
+ | @inline final def m8[T, U, V](f: (T, U) => V, x: T, y: U) = f(x, y)
+ | // IndyLambda: JFunction2$mcJID$sp, SAM is apply$mcJID$sp, body method $anonfun(ID)J
+ | // boxes the int and double arguments and calls m8, unboxToLong the result
+ | def t8 = m8((x: Int, y: Double) => 1l + x + y.toLong, 1, 2d)
+ | // opt: after inlining m8, rewrite to the body method $anonfun(ID)J, which requires inserting unbox operations for the params, box for the result
+ | // the box-unbox pairs can then be optimized away
+ |
+ | // m9$mVc$sp invokes apply$mcVI$sp
+ | @inline final def m9[@specialized(Unit) U](f: Int => U): Unit = f(1)
+ | // IndyLambda: JFunction1, SAM is apply(Obj)Obj, body method $anonfun$adapted(Ojb)Obj
+ | // invocation of m9$mVc$sp
+ | def t9 = m9(println)
+ | // opt: after inlining m9, rewrite to $anonfun$adapted(Ojb)Obj, which requires inserting a box operation for the parameter.
+ | // then we inline $adapted, which has signature (Obj)V. the `BoxedUnit.UNIT` from the body of $anonfun$adapted is eliminated by push-pop
+ |
+ | def t9a = (1 to 10) foreach println // similar to t9
+ |
+ | def intCons(i: Int): Unit = ()
+ | // IndyLambda: JFunction1$mcVI$sp, SAM is apply$mcVI$sp, body method $anonfun(I)V
+ | def t10 = m9(intCons)
+ | // after inlining m9, rewrite the apply$mcVI$sp call to the body method, no adaptations required
+ |
+ | def t10a = (1 to 10) foreach intCons // similar to t10
+ |}
+ """.stripMargin
+ val List(c, _, _) = compile(code)
+
+ assertEquals(getSingleMethod(c, "t1").instructions.summary,
+ List(BIPUSH, "C$$$anonfun$1", IRETURN))
+
+ assertEquals(getSingleMethod(c, "t1a").instructions.summary,
+ List(LCONST_1, "C$$$anonfun$2", IRETURN))
+
+ assertEquals(getSingleMethod(c, "t2").instructions.summary, List(
+ ICONST_1, ICONST_2, "C$$$anonfun$3",IRETURN))
+
+ // val a = new ValKl(n); new ValKl(anonfun(a.x)).x
+ // value class instantiation-extraction should be optimized by boxing elim
+ assertEquals(getSingleMethod(c, "t3").instructions.summary, List(
+ NEW, DUP, ICONST_1, "<init>", ASTORE,
+ NEW, DUP, ALOAD, "x",
+ "C$$$anonfun$4",
+ "<init>",
+ "x", IRETURN))
+
+ assertEquals(getSingleMethod(c, "t4").instructions.summary, List(
+ BIPUSH, "C$$$anonfun$5", "boxToInteger", ARETURN))
+
+ assertEquals(getSingleMethod(c, "t4a").instructions.summary, List(
+ ICONST_1, LDC, "C$$$anonfun$6", LRETURN))
+
+ assertEquals(getSingleMethod(c, "t5").instructions.summary, List(
+ BIPUSH, ICONST_3, "C$$$anonfun$7", "boxToInteger", ARETURN))
+
+ assertEquals(getSingleMethod(c, "t5a").instructions.summary, List(
+ BIPUSH, BIPUSH, I2B, "C$$$anonfun$8", IRETURN))
+
+ assertEquals(getSingleMethod(c, "t6").instructions.summary, List(
+ BIPUSH, "C$$$anonfun$9", RETURN))
+
+ assertEquals(getSingleMethod(c, "t7").instructions.summary, List(
+ ICONST_1, "C$$$anonfun$10", RETURN))
+
+ assertEquals(getSingleMethod(c, "t8").instructions.summary, List(
+ ICONST_1, LDC, "C$$$anonfun$11", LRETURN))
+
+ assertEquals(getSingleMethod(c, "t9").instructions.summary, List(
+ ICONST_1, "boxToInteger", "C$$$anonfun$12", RETURN))
+
+ // t9a inlines Range.foreach, which is quite a bit of code, so just testing the core
+ assertInvoke(getSingleMethod(c, "t9a"), "C", "C$$$anonfun$13")
+ assert(getSingleMethod(c, "t9a").instructions.summary.contains("boxToInteger"))
+
+ assertEquals(getSingleMethod(c, "t10").instructions.summary, List(
+ ICONST_1, ISTORE,
+ ALOAD, ILOAD,
+ "C$$$anonfun$14", RETURN))
+
+ // t10a inlines Range.foreach
+ assertInvoke(getSingleMethod(c, "t10a"), "C", "C$$$anonfun$15")
+ assert(!getSingleMethod(c, "t10a").instructions.summary.contains("boxToInteger"))
+ }
+
+ @Test
+ def refElimination(): Unit = {
+ val code =
+ """class C {
+ | def t1 = {
+ | var i = 0
+ | @inline def inner() = i += 1
+ | inner()
+ | i
+ | }
+ |
+ | final def m(f: Int => Unit) = f(10)
+ | def t2 = {
+ | var x = -1 // IntRef not yet eliminated: closure elimination does not
+ | m(i => if (i == 10) x = 1) // yet inline the anonfun method, need to improve the heuristsics
+ | x
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compile(code)
+ assertSameCode(getSingleMethod(c, "t1").instructions.dropNonOp, List(Op(ICONST_0), Op(ICONST_1), Op(IADD), Op(IRETURN)))
+ assertEquals(getSingleMethod(c, "t2").instructions collect { case i: Invoke => i.owner +"."+ i.name }, List(
+ "scala/runtime/IntRef.create", "C.C$$$anonfun$1"))
+ }
+
+ @Test
+ def tupleElimination(): Unit = {
+ val code =
+ """class C {
+ | @inline final def tpl[A, B](a: A, b: B) = (a, b)
+ | @inline final def t_1[A, B](t: (A, B)) = t._1
+ | @inline final def t_2[A, B](t: (A, B)) = t._2
+ |
+ | def t1 = {
+ | val t = (3, 4) // specialized tuple
+ | t_1(t) + t_2(t) // invocations to generic _1 / _2, box operation inserted when eliminated
+ | }
+ |
+ | def t2 = {
+ | val t = tpl(1, 2) // generic Tuple2[Integer, Integer] created
+ | t._1 + t._2 // invokes the specialized _1$mcI$sp, eliminating requires adding an unbox operation
+ | }
+ |
+ | @inline final def m = (1, 3)
+ | def t3 = {
+ | val (a, b) = m
+ | a - b
+ | }
+ |
+ | def t4 = {
+ | val ((a, b), (c, d)) = (m, m)
+ | a + b + c + d
+ | }
+ |
+ | def t5 = m match {
+ | case (1, y) => y
+ | case (x, y) => x * y
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compile(code)
+ assertSameCode(getSingleMethod(c, "t1").instructions.dropNonOp, List(Op(ICONST_3), Op(ICONST_4), Op(IADD), Op(IRETURN)))
+ assertSameCode(getSingleMethod(c, "t2").instructions.dropNonOp, List(Op(ICONST_1), Op(ICONST_2), Op(IADD), Op(IRETURN)))
+ assertSameCode(getSingleMethod(c, "t3").instructions.dropNonOp, List(Op(ICONST_1), Op(ICONST_3), Op(ISUB), Op(IRETURN)))
+ assertNoInvoke(getSingleMethod(c, "t4"))
+ assertNoInvoke(getSingleMethod(c, "t5"))
+ }
+
+ @Test
+ def redundantCasts(): Unit = {
+
+ // we go through the hoop of inlining the casts because erasure eliminates `asInstanceOf` calls
+ // that are statically known to succeed. For example the following cast is removed by erasure:
+ // `(if (b) c else d).asInstanceOf[C]`
+
+ val code =
+ """class C {
+ | @inline final def asO(a: Any) = a.asInstanceOf[Object]
+ | @inline final def asC(a: Any) = a.asInstanceOf[C]
+ | @inline final def asD(a: Any) = a.asInstanceOf[D]
+ |
+ | def t1(c: C) = asC(c) // eliminated
+ | def t2(c: C) = asO(c) // eliminated
+ | def t3(c: Object) = asC(c) // not elimianted
+ | def t4(c: C, d: D, b: Boolean) = asC(if (b) c else d) // not eliminated: lub of two non-equal reference types approximated with Object
+ | def t5(c: C, d: D, b: Boolean) = asO(if (b) c else d)
+ | def t6(c: C, cs: Array[C], b: Boolean) = asO(if (b) c else cs)
+ |}
+ |class D extends C
+ """.stripMargin
+ val List(c, _) = compile(code)
+ def casts(m: String) = getSingleMethod(c, m).instructions collect { case TypeOp(CHECKCAST, tp) => tp }
+ assertSameCode(getSingleMethod(c, "t1").instructions.dropNonOp, List(VarOp(ALOAD, 1), Op(ARETURN)))
+ assertSameCode(getSingleMethod(c, "t2").instructions.dropNonOp, List(VarOp(ALOAD, 1), Op(ARETURN)))
+ assertSameCode(getSingleMethod(c, "t3").instructions.dropNonOp, List(VarOp(ALOAD, 1), TypeOp(CHECKCAST, "C"), Op(ARETURN)))
+ assertEquals(casts("t4"), List("C"))
+ assertEquals(casts("t5"), Nil)
+ assertEquals(casts("t6"), Nil)
+ }
}
diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOpts.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOpts.scala
deleted file mode 100644
index 8d910629ca..0000000000
--- a/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOpts.scala
+++ /dev/null
@@ -1,92 +0,0 @@
-package scala.tools.nsc
-package backend.jvm
-package opt
-
-import org.junit.runner.RunWith
-import org.junit.runners.JUnit4
-import org.junit.Test
-import scala.tools.asm.Opcodes._
-import org.junit.Assert._
-
-import scala.tools.testing.AssertUtil._
-
-import CodeGenTools._
-import scala.tools.partest.ASMConverters
-import ASMConverters._
-import scala.tools.testing.ClearAfterClass
-
-object MethodLevelOpts extends ClearAfterClass.Clearable {
- var methodOptCompiler = newCompiler(extraArgs = "-Ybackend:GenBCode -Yopt:l:method")
- def clear(): Unit = { methodOptCompiler = null }
-}
-
-@RunWith(classOf[JUnit4])
-class MethodLevelOpts extends ClearAfterClass {
- ClearAfterClass.stateToClear = MethodLevelOpts
-
- val methodOptCompiler = MethodLevelOpts.methodOptCompiler
-
- def wrapInDefault(code: Instruction*) = List(Label(0), LineNumber(1, Label(0))) ::: code.toList ::: List(Label(1))
-
- @Test
- def eliminateEmptyTry(): Unit = {
- val code = "def f = { try {} catch { case _: Throwable => 0; () }; 1 }"
- val warn = "a pure expression does nothing in statement position"
- assertSameCode(singleMethodInstructions(methodOptCompiler)(code, allowMessage = _.msg contains warn), wrapInDefault(Op(ICONST_1), Op(IRETURN)))
- }
-
- @Test
- def cannotEliminateLoadBoxedUnit(): Unit = {
- // the compiler inserts a boxed into the try block. it's therefore non-empty (and live) and not eliminated.
- val code = "def f = { try {} catch { case _: Throwable => 0 }; 1 }"
- val m = singleMethod(methodOptCompiler)(code)
- assertTrue(m.handlers.length == 1)
- assertSameCode(m.instructions.take(3), List(Label(0), LineNumber(1, Label(0)), Field(GETSTATIC, "scala/runtime/BoxedUnit", "UNIT", "Lscala/runtime/BoxedUnit;")))
- }
-
- @Test
- def inlineThrowInCatchNotTry(): Unit = {
- // the try block does not contain the `ATHROW` instruction, but in the catch block, `ATHROW` is inlined
- val code = "def f(e: Exception) = throw { try e catch { case _: Throwable => e } }"
- val m = singleMethod(methodOptCompiler)(code)
- assertHandlerLabelPostions(m.handlers.head, m.instructions, 0, 3, 5)
- assertSameCode(m.instructions,
- wrapInDefault(VarOp(ALOAD, 1), Label(3), Op(ATHROW), Label(5), FrameEntry(4, List(), List("java/lang/Throwable")), Op(POP), VarOp(ALOAD, 1), Op(ATHROW))
- )
- }
-
- @Test
- def inlineReturnInCatchNotTry(): Unit = {
- val code = "def f: Int = return { try 1 catch { case _: Throwable => 2 } }"
- // cannot inline the IRETURN into the try block (because RETURN may throw IllegalMonitorState)
- val m = singleMethod(methodOptCompiler)(code)
- assertHandlerLabelPostions(m.handlers.head, m.instructions, 0, 3, 5)
- assertSameCode(m.instructions,
- wrapInDefault(Op(ICONST_1), Label(3), Op(IRETURN), Label(5), FrameEntry(4, List(), List("java/lang/Throwable")), Op(POP), Op(ICONST_2), Op(IRETURN)))
- }
-
- @Test
- def simplifyJumpsInTryCatchFinally(): Unit = {
- val code =
- """def f: Int =
- | try {
- | return 1
- | } catch {
- | case _: Throwable =>
- | return 2
- | } finally {
- | return 2
- | // dead
- | val x = try 10 catch { case _: Throwable => 11 }
- | println(x)
- | }
- """.stripMargin
- val m = singleMethod(methodOptCompiler)(code)
- assertTrue(m.handlers.length == 2)
- assertSameCode(m.instructions.dropNonOp, // drop line numbers and labels that are only used by line numbers
-
- // one single label left :-)
- List(Op(ICONST_1), VarOp(ISTORE, 2), Jump(GOTO, Label(20)), Op(POP), Op(ICONST_2), VarOp(ISTORE, 2), Jump(GOTO, Label(20)), VarOp(ASTORE, 3), Op(ICONST_2), Op(IRETURN), Label(20), Op(ICONST_2), Op(IRETURN))
- )
- }
-}
diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOptsTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOptsTest.scala
new file mode 100644
index 0000000000..46e1cebfc4
--- /dev/null
+++ b/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOptsTest.scala
@@ -0,0 +1,562 @@
+package scala.tools.nsc
+package backend.jvm
+package opt
+
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import org.junit.Test
+import scala.tools.asm.Opcodes._
+import org.junit.Assert._
+
+import scala.tools.nsc.backend.jvm.AsmUtils._
+import scala.tools.testing.AssertUtil._
+
+import CodeGenTools._
+import scala.tools.partest.ASMConverters
+import ASMConverters._
+import scala.tools.testing.ClearAfterClass
+
+object MethodLevelOptsTest extends ClearAfterClass.Clearable {
+ var methodOptCompiler = newCompiler(extraArgs = "-Ybackend:GenBCode -Yopt:l:method")
+ def clear(): Unit = { methodOptCompiler = null }
+}
+
+@RunWith(classOf[JUnit4])
+class MethodLevelOptsTest extends ClearAfterClass {
+ ClearAfterClass.stateToClear = MethodLevelOptsTest
+
+ val methodOptCompiler = MethodLevelOptsTest.methodOptCompiler
+
+ def wrapInDefault(code: Instruction*) = List(Label(0), LineNumber(1, Label(0))) ::: code.toList ::: List(Label(1))
+
+ @Test
+ def eliminateEmptyTry(): Unit = {
+ val code = "def f = { try {} catch { case _: Throwable => 0; () }; 1 }"
+ val warn = "a pure expression does nothing in statement position"
+ assertSameCode(singleMethodInstructions(methodOptCompiler)(code, allowMessage = _.msg contains warn), wrapInDefault(Op(ICONST_1), Op(IRETURN)))
+ }
+
+ @Test
+ def eliminateLoadBoxedUnit(): Unit = {
+ // the compiler inserts a boxed into the try block. it's therefore non-empty (and live) and not eliminated.
+ val code = "def f = { try {} catch { case _: Throwable => 0 }; 1 }"
+ val m = singleMethod(methodOptCompiler)(code)
+ assertTrue(m.handlers.length == 0)
+ assertSameCode(m.instructions.dropNonOp,
+ List(Op(ICONST_1), Op(IRETURN)))
+ }
+
+ @Test
+ def inlineThrowInCatchNotTry(): Unit = {
+ // the try block does not contain the `ATHROW` instruction, but in the catch block, `ATHROW` is inlined
+ val code = "def f(e: Exception) = throw { try e catch { case _: Throwable => e } }"
+ val m = singleMethod(methodOptCompiler)(code)
+ assertHandlerLabelPostions(m.handlers.head, m.instructions, 0, 3, 5)
+ assertSameCode(m.instructions,
+ wrapInDefault(VarOp(ALOAD, 1), Label(3), Op(ATHROW), Label(5), FrameEntry(4, List(), List("java/lang/Throwable")), Op(POP), VarOp(ALOAD, 1), Op(ATHROW))
+ )
+ }
+
+ @Test
+ def inlineReturnInCatchNotTry(): Unit = {
+ val code = "def f: Int = return { try 1 catch { case _: Throwable => 2 } }"
+ // cannot inline the IRETURN into the try block (because RETURN may throw IllegalMonitorState)
+ val m = singleMethod(methodOptCompiler)(code)
+ assertHandlerLabelPostions(m.handlers.head, m.instructions, 0, 3, 5)
+ assertSameCode(m.instructions,
+ wrapInDefault(Op(ICONST_1), Label(3), Op(IRETURN), Label(5), FrameEntry(4, List(), List("java/lang/Throwable")), Op(POP), Op(ICONST_2), Op(IRETURN)))
+ }
+
+ @Test
+ def simplifyJumpsInTryCatchFinally(): Unit = {
+ val code =
+ """def f: Int =
+ | try {
+ | return 1
+ | } catch {
+ | case _: Throwable =>
+ | return 2
+ | } finally {
+ | return 3
+ | // dead
+ | val x = try 10 catch { case _: Throwable => 11 }
+ | println(x)
+ | }
+ """.stripMargin
+ val m = singleMethod(methodOptCompiler)(code)
+ assertTrue(m.handlers.isEmpty)
+ assertSameCode(m.instructions.dropNonOp, List(Op(ICONST_3), Op(IRETURN)))
+ }
+
+ @Test
+ def nullStoreLoadElim(): Unit = {
+ // point of this test: we have two cleanups
+ // - remove `ACONST_NULL; ASTORE x` if x is otherwise not live
+ // - remove `ASTORE x; ALOAD x` if x is otherwise not live
+ // in the example below, we have `ACONST_NULL; ASTORE x; ALOAD x`. in this case the store-load
+ // should be removed (even though it looks like a null-store at first).
+ val code =
+ """class C {
+ | def t = {
+ | val x = null
+ | x.toString
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertSameCode(getSingleMethod(c, "t").instructions.dropNonOp,
+ List(Op(ACONST_NULL), Invoke(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;", false), Op(ARETURN)))
+ }
+
+ @Test
+ def deadStoreReferenceElim(): Unit = {
+ val code =
+ """class C {
+ | def t = {
+ | var a = "a" // assign to non-initialized, directly removed by dead store
+ | a = "b" // assign to initialized, replaced by null-store, which is then removed: the var is not live, the uses are null-store or store-load
+ | a = "c"
+ | a // store-load pair will be eliminated
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertSameCode(
+ getSingleMethod(c, "t").instructions.dropNonOp,
+ List(Ldc(LDC, "c"), Op(ARETURN)))
+ }
+
+ @Test
+ def deadStoreReferenceKeepNull(): Unit = {
+ val code =
+ """class C {
+ | def t = {
+ | var a = "el" // this store is live, used in the println.
+ | println(a)
+ | a = "met" // since it's an ASTORE to a live variable, cannot elim the store (SI-5313), but store null instead.
+ | // so we get `LDC met; POP; ACONST_NULL; ASTORE 1`. the `LDC met; POP` is eliminated by push-pop.
+ | a = "zit" // this store is live, so we get `LDC zit; ASOTRE 1; ALOAD 1; ARETURN`.
+ | // we cannot eliminated the store-load sequence, because the local is live (again SI-5313).
+ | a
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+
+ assertEquals(
+ getSingleMethod(c, "t").instructions.dropNonOp,
+ List(
+ Ldc(LDC, "el"), VarOp(ASTORE, 1),
+ Field(GETSTATIC, "scala/Predef$", "MODULE$", "Lscala/Predef$;"), VarOp(ALOAD, 1), Invoke(INVOKEVIRTUAL, "scala/Predef$", "println", "(Ljava/lang/Object;)V", false),
+ Op(ACONST_NULL), VarOp(ASTORE, 1),
+ Ldc(LDC, "zit"), VarOp(ASTORE, 1), VarOp(ALOAD, 1), Op(ARETURN)))
+ }
+
+ @Test
+ def elimUnusedTupleObjectStringBox(): Unit = {
+ val code =
+ """class C {
+ | def t(x: Int, y: Int): Int = {
+ | val a = (x, y) // Tuple2$mcII$sp
+ | val b = (a, y) // Tuple2
+ | val c = (new Object, "krik", new String) // unused java/lang/Object, java/lang/String allocation and string constant is also eliminated
+ | val d = new java.lang.Integer(x)
+ | val e = new String(new Array[Char](23)) // array allocation not eliminated, as it may throw (negative size, SI-8601)
+ | val f = new scala.runtime.IntRef(11)
+ | x + y
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertEquals(getSingleMethod(c, "t").instructions.dropNonOp,
+ List(IntOp(BIPUSH, 23), IntOp(NEWARRAY, 5), Op(POP), VarOp(ILOAD, 1), VarOp(ILOAD, 2), Op(IADD), Op(IRETURN)))
+ }
+
+ @Test
+ def noElimImpureConstructor(): Unit = {
+ val code =
+ """class C {
+ | def t(x: Int, y: Int): Int = {
+ | val a = new java.lang.Integer("nono")
+ | x + y
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertEquals(getSingleMethod(c, "t").instructions.dropNonOp,
+ List(TypeOp(NEW, "java/lang/Integer"), Ldc(LDC, "nono"), Invoke(INVOKESPECIAL, "java/lang/Integer", "<init>", "(Ljava/lang/String;)V", false),
+ VarOp(ILOAD, 1), VarOp(ILOAD, 2), Op(IADD), Op(IRETURN)))
+ }
+
+ @Test
+ def elimUnusedBoxUnbox(): Unit = {
+ val code =
+ """class C {
+ | def t(a: Long): Int = {
+ | val t = 3 + a
+ | val u = a + t
+ | val v: Any = u // scala/runtime/BoxesRunTime.boxToLong
+ |
+ | val w = (v, a) // a Tuple2 (not specialized because first value is Any)
+ | // so calls scala/runtime/BoxesRunTime.boxToLong on the second value
+ |
+ | val x = v.asInstanceOf[Long] // scala/runtime/BoxesRunTime.unboxToLong
+ |
+ | val z = (java.lang.Long.valueOf(a), t) // java box call on the left, scala/runtime/BoxesRunTime.boxToLong on the right
+ |
+ | 0
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertEquals(getSingleMethod(c, "t").instructions.dropNonOp,
+ List(Op(ICONST_0), Op(IRETURN)))
+ }
+
+ @Test
+ def elimUnusedClosure(): Unit = {
+ val code =
+ """class C {
+ | def t(x: Int, y: Int): Int = {
+ | val f = (a: Int) => a + x + y
+ | val g = (b: Int) => b - x
+ | val h = (s: String) => println(s)
+ | f(30)
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertEquals(
+ getSingleMethod(c, "t").instructions.dropNonOp,
+ List(
+ IntOp(BIPUSH, 30), VarOp(ISTORE, 3), // no constant propagation, so we keep the store (and load below) of a const
+ VarOp(ILOAD, 1),
+ VarOp(ILOAD, 2),
+ VarOp(ILOAD, 3),
+ Invoke(INVOKESTATIC, "C", "C$$$anonfun$1", "(III)I", false), Op(IRETURN)))
+ }
+
+ @Test
+ def rewriteSpecializedClosureCall(): Unit = {
+ val code =
+ """class C {
+ | def t = {
+ | val f1 = (x: Int) => println(x) // int-unit specialization
+ | val f2 = (x: Int, y: Long) => x == y // int-long-boolean
+ | f1(1)
+ | f2(3, 4)
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ val t = getSingleMethod(c, "t")
+ assert(!t.instructions.exists(_.opcode == INVOKEDYNAMIC), t)
+ }
+
+ @Test
+ def boxUnboxPrimitive(): Unit = {
+ val code =
+ """class C {
+ | def t1 = {
+ | val a: Any = runtime.BoxesRunTime.boxToInteger(1)
+ | runtime.BoxesRunTime.unboxToInt(a) + 1
+ | }
+ |
+ | // two box and two unbox operations
+ | def t2(b: Boolean) = {
+ | val a = if (b) (3l: Any) else 2l
+ | a.asInstanceOf[Long] + 1 + a.asInstanceOf[Long]
+ | }
+ |
+ | def t3(i: Integer): Int = i.asInstanceOf[Int]
+ |
+ | def t4(l: Long): Any = l
+ |
+ | def t5(i: Int): Int = {
+ | val b = Integer.valueOf(i)
+ | val c: Integer = i
+ | b.asInstanceOf[Int] + c.intValue
+ | }
+ |
+ | def t6: Long = {
+ | val y = new java.lang.Boolean(true)
+ | val i: Integer = if (y) new Integer(10) else 13
+ | val j: java.lang.Long = 3l
+ | j + i
+ | }
+ |
+ | def t7: Int = {
+ | val a: Any = 3
+ | a.asInstanceOf[Int] + a.asInstanceOf[Int]
+ | }
+ |
+ | def t8 = null.asInstanceOf[Int]
+ |
+ | def t9: Int = {
+ | val a = Integer.valueOf(10)
+ | val b = runtime.BoxesRunTime.unboxToInt(a)
+ | a + b
+ | }
+ |
+ | @noinline def escape(a: Any) = ()
+ |
+ | // example E4 in BoxUnbox doc comment
+ | def t10: Int = {
+ | val a = Integer.valueOf(10) // int 10 is stored into local
+ | escape(a)
+ | a // no unbox, 10 is read from local
+ | }
+ |
+ | // the boxes here cannot be eliminated. see doc comment in BoxUnbox, example E1.
+ | def t11(b: Boolean): Int = {
+ | val i = Integer.valueOf(10)
+ | val j = Integer.valueOf(41)
+ | escape(i) // force rewrite method M1 (see doc in BoxUnbox)
+ | val res: Integer = if (b) i else j
+ | res.toInt // cannot be re-written to a local variable read - we don't know which local to read
+ | }
+ |
+ | // both boxes have a single unboxing consumer, and the escape. note that the escape does
+ | // NOT put the two boxes into the same set of rewrite operations: we can rewrite both
+ | // boxes with their unbox individually. in both cases the box also escapes, so method
+ | // M1 will keep the box around.
+ | def t12(b: Boolean): Int = {
+ | val i = Integer.valueOf(10)
+ | val j = Integer.valueOf(32)
+ | escape(if (b) i else j) // force method M1. the escape here is a consumer for both boxes
+ | if (b) i.toInt else j.toInt // both boxes (i, j) have their own unboxing consumer
+ | }
+ |}
+ """.stripMargin
+
+ val List(c) = compileClasses(methodOptCompiler)(code)
+
+ assertNoInvoke(getSingleMethod(c, "t1"))
+ assertNoInvoke(getSingleMethod(c, "t2"))
+ assertInvoke(getSingleMethod(c, "t3"), "scala/runtime/BoxesRunTime", "unboxToInt")
+ assertInvoke(getSingleMethod(c, "t4"), "scala/runtime/BoxesRunTime", "boxToLong")
+ assertNoInvoke(getSingleMethod(c, "t5"))
+ assertNoInvoke(getSingleMethod(c, "t6"))
+ assertNoInvoke(getSingleMethod(c, "t7"))
+ assertEquals(getSingleMethod(c, "t8").instructions.summary, List(ICONST_0, IRETURN))
+ assertNoInvoke(getSingleMethod(c, "t9"))
+ // t10: no invocation of unbox
+ assertEquals(getSingleMethod(c, "t10").instructions collect { case Invoke(_, owner, name, _, _) => (owner, name) }, List(
+ ("java/lang/Integer", "valueOf"),
+ ("C", "escape")))
+
+ assertEquals(getSingleMethod(c, "t11").instructions.summary, List(
+ BIPUSH, "valueOf", ASTORE /*2*/,
+ BIPUSH, "valueOf", ASTORE /*3*/,
+ ALOAD /*0*/, ALOAD /*2*/, "escape",
+ ILOAD /*1*/, IFEQ /*L1*/, ALOAD /*2*/, GOTO /*L2*/, /*Label L1*/ -1, ALOAD /*3*/, /*Label L2*/ -1,
+ ASTORE /*4*/, GETSTATIC /*Predef*/, ALOAD /*4*/, "Integer2int", IRETURN))
+
+ // no unbox invocations
+ assertEquals(getSingleMethod(c, "t12").instructions collect { case Invoke(_, owner, name, _, _) => (owner, name) }, List(
+ ("java/lang/Integer", "valueOf"),
+ ("java/lang/Integer", "valueOf"),
+ ("C", "escape")))
+ }
+
+ @Test
+ def refEliminiation(): Unit = {
+ val code =
+ """class C {
+ | import runtime._
+ | @noinline def escape(a: Any) = ()
+ |
+ | def t1 = { // box eliminated
+ | val r = new IntRef(0)
+ | r.elem
+ | }
+ |
+ | def t2(b: Boolean) = {
+ | val r1 = IntRef.zero() // both eliminated
+ | val r2 = IntRef.create(1)
+ | val res: IntRef = if (b) r1 else r2
+ | res.elem
+ | }
+ |
+ | def t3 = {
+ | val r = LongRef.create(10l) // eliminated
+ | r.elem += 3
+ | r.elem
+ | }
+ |
+ | def t4(b: Boolean) = {
+ | val x = BooleanRef.create(false) // eliminated
+ | if (b) x.elem = true
+ | if (x.elem) "a" else "b"
+ | }
+ |
+ | def t5 = {
+ | val r = IntRef.create(10) // not eliminated: the box might be modified in the escape
+ | escape(r)
+ | r.elem
+ | }
+ |
+ | def t6(b: Boolean) = {
+ | val r1 = IntRef.zero()
+ | val r2 = IntRef.create(1)
+ | r1.elem = 39
+ | val res: IntRef = if (b) r1 else r2
+ | res.elem // boxes remain: can't rewrite this read, don't know which local
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertEquals(getSingleMethod(c, "t1").instructions.summary, List(ICONST_0, IRETURN))
+ assertNoInvoke(getSingleMethod(c, "t2"))
+ assertEquals(getSingleMethod(c, "t3").instructions.summary, List(LDC, LDC, LADD, LRETURN))
+ assertNoInvoke(getSingleMethod(c, "t4"))
+ assertEquals(getSingleMethod(c, "t5").instructions collect { case Field(_, owner, name, _) => s"$owner.$name" },
+ List("scala/runtime/IntRef.elem"))
+ assertEquals(getSingleMethod(c, "t6").instructions collect { case Field(op, owner, name, _) => s"$op $owner.$name" },
+ List(s"$PUTFIELD scala/runtime/IntRef.elem", s"$GETFIELD scala/runtime/IntRef.elem"))
+ }
+
+ @Test
+ def tupleElimination(): Unit = {
+ val code =
+ """class C {
+ | def t1(b: Boolean) = {
+ | val t = ("hi", "fish")
+ | if (b) t._1 else t._2
+ | }
+ |
+ | def t2 = {
+ | val t = (1, 3) // specialized tuple
+ | t._1 + t._2 // specialized accessors (_1$mcII$sp)
+ | }
+ |
+ | def t3 = {
+ | // boxed before tuple creation, a non-specialized tuple is created
+ | val t = (new Integer(3), Integer.valueOf(4))
+ | t._1 + t._2 // invokes the generic `_1` / `_2` getters, both values unboxed by Integer2int
+ | }
+ |
+ | def t4: Any = {
+ | val t = (3, 3) // specialized tuple is created, ints are not boxed
+ | (t: Tuple2[Any, Any])._1 // when eliminating the _1 call, need to insert a boxing operation
+ | }
+ |
+ | // the inverse of t4 also happens: an Tuple[Integer] where _1$mcI$sp is invoked. In this
+ | // case, an unbox operation needs to be added when eliminating the extraction. The only
+ | // way I found to test this is with an inlined generic method, see InlinerTest.tupleElimination.
+ | def tpl[A, B](a: A, b: B) = (a, b)
+ | def t5: Int = tpl(1, 2)._1 // invokes _1$mcI$sp
+ |
+ | def t6 = {
+ | val (a, b) = (1, 2)
+ | a - b
+ | }
+ |
+ | def t7 = {
+ | // this example is more tricky to handle than it looks, see doc comment in BoxUnbox.
+ | val ((a, b), c) = ((1, 2), 3)
+ | a + b + c
+ | }
+ |
+ | def t8 = {
+ | val ((a, b), (c, d)) = ((1, 2), (3, Integer.valueOf(10)))
+ | a + b + c + d
+ | }
+ |
+ | def t9(a: Int, b: Int) = (a, b) match { // tuple is optimized away
+ | case (x, y) if x == y => 0
+ | case (x, y) => x + y
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertNoInvoke(getSingleMethod(c, "t1"))
+ assertEquals(getSingleMethod(c, "t2").instructions.summary, List(ICONST_1, ICONST_3, IADD, IRETURN))
+ assertEquals(getSingleMethod(c, "t3").instructions.summary, List(ICONST_3, ICONST_4, IADD, IRETURN))
+ assertEquals(getSingleMethod(c, "t4").instructions.summary, List(ICONST_3, "boxToInteger", ARETURN))
+ assertEquals(getSingleMethod(c, "t5").instructions collect { case Invoke(_, owner, name, _, _) => (owner, name) }, List(
+ ("scala/runtime/BoxesRunTime", "boxToInteger"),
+ ("scala/runtime/BoxesRunTime", "boxToInteger"),
+ ("C", "tpl"),
+ ("scala/Tuple2", "_1$mcI$sp")))
+ assertEquals(getSingleMethod(c, "t6").instructions.summary, List(ICONST_1, ICONST_2, ISUB, IRETURN))
+ assertEquals(getSingleMethod(c, "t7").instructions.summary, List(
+ ICONST_1, ICONST_2, ISTORE, ISTORE,
+ ICONST_3, ISTORE,
+ ILOAD, ILOAD, IADD, ILOAD, IADD, IRETURN))
+ assertNoInvoke(getSingleMethod(c, "t8"))
+ assertNoInvoke(getSingleMethod(c, "t9"))
+ }
+
+ @Test
+ def nullnessOpts(): Unit = {
+ val code =
+ """class C {
+ | def t1 = {
+ | val a = new C
+ | if (a == null)
+ | println() // eliminated
+ | a
+ | }
+ |
+ | def t2 = null.asInstanceOf[Long] // replaced by zero value
+ |
+ | def t3 = {
+ | val t = (1, 3)
+ | val a = null
+ | if (t ne a) t._1
+ | else throw new Error()
+ | }
+ |
+ | def t4 = {
+ | val i = Integer.valueOf(1)
+ | val a = null
+ | if (i eq a) throw new Error()
+ | else i.toInt
+ | }
+ |
+ | def t5 = {
+ | val i = runtime.DoubleRef.zero()
+ | if (i == null) throw new Error()
+ | else i.elem
+ | }
+ |
+ | def t6 = {
+ | var a = null
+ | var i = null
+ | a = i // eliminated (store of null to variable that is already null)
+ | a // replaced by ACONST_NULL (load of variable that is known null)
+ | }
+ |
+ | def t7 = {
+ | val a = null
+ | a.isInstanceOf[String] // eliminated, replaced by 0 (null.isInstanceOf is always false)
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertEquals(getSingleMethod(c, "t1").instructions.summary, List(NEW, DUP, "<init>", ARETURN))
+ assertSameCode(getSingleMethod(c, "t2").instructions.dropNonOp, List(Op(LCONST_0), Op(LRETURN)))
+ assertSameCode(getSingleMethod(c, "t3").instructions.dropNonOp, List(Op(ICONST_1), Op(IRETURN)))
+ assertSameCode(getSingleMethod(c, "t4").instructions.dropNonOp, List(Op(ICONST_1), Op(IRETURN)))
+ assertSameCode(getSingleMethod(c, "t5").instructions.dropNonOp, List(Op(DCONST_0), Op(DRETURN)))
+ assertSameCode(getSingleMethod(c, "t6").instructions.dropNonOp, List(Op(ACONST_NULL), Op(ARETURN)))
+ assertSameCode(getSingleMethod(c, "t7").instructions.dropNonOp, List(Op(ICONST_0), Op(IRETURN)))
+ }
+
+ @Test
+ def elimRedundantNullCheck(): Unit = {
+ val code =
+ """class C {
+ | def t(x: Object) = {
+ | val bool = x == null
+ | if (x != null) 1 else 0
+ | }
+ |}
+ """.stripMargin
+ val List(c) = compileClasses(methodOptCompiler)(code)
+ assertSameCode(
+ getSingleMethod(c, "t").instructions.dropNonOp,
+ List(VarOp(ALOAD, 1), Jump(IFNULL, Label(6)), Op(ICONST_1), Op(IRETURN), Label(6), Op(ICONST_0), Op(IRETURN)))
+ }
+}