Merge "Redundant const number removal"
diff --git a/src/main/java/com/android/tools/r8/ir/analysis/type/TypeLatticeElement.java b/src/main/java/com/android/tools/r8/ir/analysis/type/TypeLatticeElement.java
index 1544570..9c3bcc3 100644
--- a/src/main/java/com/android/tools/r8/ir/analysis/type/TypeLatticeElement.java
+++ b/src/main/java/com/android/tools/r8/ir/analysis/type/TypeLatticeElement.java
@@ -107,7 +107,6 @@
     throw new Unreachable("unless a new type lattice is introduced.");
   }
 
-
   public static TypeLatticeElement join(
       Iterable<TypeLatticeElement> typeLattices, AppInfo appInfo) {
     TypeLatticeElement result = BOTTOM;
diff --git a/src/main/java/com/android/tools/r8/ir/code/If.java b/src/main/java/com/android/tools/r8/ir/code/If.java
index 2979039..25d1fc4 100644
--- a/src/main/java/com/android/tools/r8/ir/code/If.java
+++ b/src/main/java/com/android/tools/r8/ir/code/If.java
@@ -142,6 +142,7 @@
     return super.toString()
         + " "
         + type
+        + (isZeroTest() ? "Z" : " ")
         + " block "
         + getTrueTarget().getNumberAsString()
         + " (fallthrough "
diff --git a/src/main/java/com/android/tools/r8/ir/code/Value.java b/src/main/java/com/android/tools/r8/ir/code/Value.java
index f95b988..374acd5 100644
--- a/src/main/java/com/android/tools/r8/ir/code/Value.java
+++ b/src/main/java/com/android/tools/r8/ir/code/Value.java
@@ -797,7 +797,17 @@
   }
 
   public boolean knownToBeBoolean() {
-    return knownToBeBoolean;
+    if (knownToBeBoolean) {
+      return true;
+    }
+    if (getTypeLattice().isInt()) {
+      Value aliasedValue = getAliasedValue();
+      if (!aliasedValue.isPhi() && aliasedValue.definition.isConstNumber()) {
+        ConstNumber definition = aliasedValue.definition.asConstNumber();
+        return definition.isZero() || definition.getRawValue() == 1;
+      }
+    }
+    return false;
   }
 
   public void markAsThis(boolean receiverCanBeNull) {
diff --git a/src/main/java/com/android/tools/r8/ir/conversion/IRConverter.java b/src/main/java/com/android/tools/r8/ir/conversion/IRConverter.java
index b1ea3f9..7b55543 100644
--- a/src/main/java/com/android/tools/r8/ir/conversion/IRConverter.java
+++ b/src/main/java/com/android/tools/r8/ir/conversion/IRConverter.java
@@ -997,6 +997,7 @@
     codeRewriter.rewriteSwitch(code);
     codeRewriter.processMethodsNeverReturningNormally(code);
     codeRewriter.simplifyIf(code);
+    codeRewriter.redundantConstNumberRemoval(code);
     new RedundantFieldLoadElimination(appInfo, code, enableWholeProgramOptimizations).run();
 
     if (options.testing.invertConditionals) {
diff --git a/src/main/java/com/android/tools/r8/ir/optimize/CodeRewriter.java b/src/main/java/com/android/tools/r8/ir/optimize/CodeRewriter.java
index 7447f76..3227d45 100644
--- a/src/main/java/com/android/tools/r8/ir/optimize/CodeRewriter.java
+++ b/src/main/java/com/android/tools/r8/ir/optimize/CodeRewriter.java
@@ -26,6 +26,7 @@
 import com.android.tools.r8.graph.DexEncodedMethod.TrivialInitializer.TrivialInstanceInitializer;
 import com.android.tools.r8.graph.DexField;
 import com.android.tools.r8.graph.DexItemFactory;
+import com.android.tools.r8.graph.DexItemFactory.ThrowableMethods;
 import com.android.tools.r8.graph.DexMethod;
 import com.android.tools.r8.graph.DexProto;
 import com.android.tools.r8.graph.DexString;
@@ -120,6 +121,8 @@
 import it.unimi.dsi.fastutil.ints.IntArrayList;
 import it.unimi.dsi.fastutil.ints.IntIterator;
 import it.unimi.dsi.fastutil.ints.IntList;
+import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
+import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap;
 import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
 import it.unimi.dsi.fastutil.objects.Object2IntMap;
 import it.unimi.dsi.fastutil.objects.Reference2IntMap;
@@ -3144,6 +3147,210 @@
     simplifyIfWithKnownCondition(code, block, theIf, theIf.targetFromCondition(cond));
   }
 
+  /**
+   * This optimization exploits that we can sometimes learn the constant value of an SSA value that
+   * flows into an if-eq of if-neq instruction.
+   *
+   * <p>Consider the following example:
+   *
+   * <pre>
+   * 1. if (obj != null) {
+   * 2.  return doStuff();
+   * 3. }
+   * 4. return null;
+   * </pre>
+   *
+   * <p>Since we know that `obj` is null in all blocks that are dominated by the false-target of the
+   * if-instruction in line 1, we can safely replace the null-constant in line 4 by `obj`, and
+   * thereby save a const-number instruction.
+   */
+  public void redundantConstNumberRemoval(IRCode code) {
+    Supplier<Long2ReferenceMap<List<ConstNumber>>> constantsByValue =
+        Suppliers.memoize(() -> getConstantsByValue(code));
+    Supplier<DominatorTree> dominatorTree = Suppliers.memoize(() -> new DominatorTree(code));
+
+    boolean changed = false;
+    for (BasicBlock block : code.blocks) {
+      Instruction lastInstruction = block.getInstructions().getLast();
+      if (!lastInstruction.isIf()) {
+        continue;
+      }
+
+      If ifInstruction = lastInstruction.asIf();
+      Type type = ifInstruction.getType();
+
+      Value lhs = ifInstruction.inValues().get(0);
+      Value rhs = !ifInstruction.isZeroTest() ? ifInstruction.inValues().get(1) : null;
+
+      if (!ifInstruction.isZeroTest() && !lhs.isConstNumber() && !rhs.isConstNumber()) {
+        // We can only conclude anything from an if-instruction if it is a zero-test or if one of
+        // the two operands is a constant.
+        continue;
+      }
+
+      // If the type is neither EQ nor NE, we cannot conclude anything about any of the in-values
+      // of the if-instruction from the outcome of the if-instruction.
+      if (type != Type.EQ && type != Type.NE) {
+        continue;
+      }
+
+      BasicBlock trueTarget, falseTarget;
+      if (type == Type.EQ) {
+        trueTarget = ifInstruction.getTrueTarget();
+        falseTarget = ifInstruction.fallthroughBlock();
+      } else {
+        falseTarget = ifInstruction.getTrueTarget();
+        trueTarget = ifInstruction.fallthroughBlock();
+      }
+
+      if (ifInstruction.isZeroTest()) {
+        changed |=
+            replaceDominatedConstNumbers(0, lhs, trueTarget, constantsByValue, dominatorTree);
+        if (lhs.knownToBeBoolean()) {
+          changed |=
+              replaceDominatedConstNumbers(1, lhs, falseTarget, constantsByValue, dominatorTree);
+        }
+      } else {
+        assert rhs != null;
+        if (lhs.isConstNumber()) {
+          ConstNumber lhsAsNumber = lhs.getConstInstruction().asConstNumber();
+          changed |=
+              replaceDominatedConstNumbers(
+                  lhsAsNumber.getRawValue(), rhs, trueTarget, constantsByValue, dominatorTree);
+          if (lhs.knownToBeBoolean() && rhs.knownToBeBoolean()) {
+            changed |=
+                replaceDominatedConstNumbers(
+                    negateBoolean(lhsAsNumber), rhs, falseTarget, constantsByValue, dominatorTree);
+          }
+        } else {
+          assert rhs.isConstNumber();
+          ConstNumber rhsAsNumber = rhs.getConstInstruction().asConstNumber();
+          changed |=
+              replaceDominatedConstNumbers(
+                  rhsAsNumber.getRawValue(), lhs, trueTarget, constantsByValue, dominatorTree);
+          if (lhs.knownToBeBoolean() && rhs.knownToBeBoolean()) {
+            changed |=
+                replaceDominatedConstNumbers(
+                    negateBoolean(rhsAsNumber), lhs, falseTarget, constantsByValue, dominatorTree);
+          }
+        }
+      }
+
+      if (constantsByValue.get().isEmpty()) {
+        break;
+      }
+    }
+
+    if (changed) {
+      code.removeAllTrivialPhis();
+    }
+    assert code.isConsistentSSA();
+  }
+
+  private static Long2ReferenceMap<List<ConstNumber>> getConstantsByValue(IRCode code) {
+    // A map from the raw value of constants in `code` to the const number instructions that define
+    // the given raw value (irrespective of the type of the raw value).
+    Long2ReferenceMap<List<ConstNumber>> constantsByValue = new Long2ReferenceOpenHashMap<>();
+
+    // Initialize `constantsByValue`.
+    Iterable<Instruction> instructions = code::instructionIterator;
+    for (Instruction instruction : instructions) {
+      if (instruction.isConstNumber()) {
+        ConstNumber constNumber = instruction.asConstNumber();
+        if (constNumber.outValue().hasLocalInfo()) {
+          // Not necessarily constant, because it could be changed in the debugger.
+          continue;
+        }
+        long rawValue = constNumber.getRawValue();
+        if (constantsByValue.containsKey(rawValue)) {
+          constantsByValue.get(rawValue).add(constNumber);
+        } else {
+          List<ConstNumber> list = new ArrayList<>();
+          list.add(constNumber);
+          constantsByValue.put(rawValue, list);
+        }
+      }
+    }
+    return constantsByValue;
+  }
+
+  private static int negateBoolean(ConstNumber number) {
+    assert number.outValue().knownToBeBoolean();
+    return number.getRawValue() == 0 ? 1 : 0;
+  }
+
+  private boolean replaceDominatedConstNumbers(
+      long withValue,
+      Value newValue,
+      BasicBlock dominator,
+      Supplier<Long2ReferenceMap<List<ConstNumber>>> constantsByValueSupplier,
+      Supplier<DominatorTree> dominatorTree) {
+    if (newValue.hasLocalInfo()) {
+      // We cannot replace a constant with a value that has local info, because that could change
+      // debugging behavior.
+      return false;
+    }
+
+    Long2ReferenceMap<List<ConstNumber>> constantsByValue = constantsByValueSupplier.get();
+    List<ConstNumber> constantsWithValue = constantsByValue.get(withValue);
+    if (constantsWithValue == null || constantsWithValue.isEmpty()) {
+      return false;
+    }
+
+    boolean changed = false;
+
+    ListIterator<ConstNumber> constantWithValueIterator = constantsWithValue.listIterator();
+    while (constantWithValueIterator.hasNext()) {
+      ConstNumber constNumber = constantWithValueIterator.next();
+      Value value = constNumber.outValue();
+      assert !value.hasLocalInfo();
+      assert constNumber.getRawValue() == withValue;
+
+      BasicBlock block = constNumber.getBlock();
+
+      // If the following condition does not hold, then the if-instruction does not dominate the
+      // block containing the constant, although the true or false target does.
+      if (block == dominator && block.getPredecessors().size() != 1) {
+        // This should generally not happen, but it is possible to write bytecode where it does.
+        assert false;
+        continue;
+      }
+
+      if (value.knownToBeBoolean() && !newValue.knownToBeBoolean()) {
+        // We cannot replace a boolean by a none-boolean since that can lead to verification
+        // errors. For example, the following code fails with "register v1 has type Imprecise
+        // Constant: 127 but expected Boolean return-1nr".
+        //
+        //   public boolean convertIntToBoolean(int v1) {
+        //       const/4 v0, 0x1
+        //       if-eq v1, v0, :eq_true
+        //       const/4 v1, 0x0
+        //     :eq_true
+        //       return v1
+        //   }
+        continue;
+      }
+
+      if (dominatorTree.get().dominatedBy(block, dominator)) {
+        if (newValue.getTypeLattice().lessThanOrEqual(value.getTypeLattice(), appInfo)) {
+          value.replaceUsers(newValue);
+          block.listIterator(constNumber).removeOrReplaceByDebugLocalRead();
+          constantWithValueIterator.remove();
+          changed = true;
+        } else if (value.getTypeLattice().isNullType()) {
+          // TODO(b/120257211): Need a mechanism to determine if `newValue` can be used at all of
+          // the use sites of `value` without introducing a type error.
+        }
+      }
+    }
+
+    if (constantsWithValue.isEmpty()) {
+      constantsByValue.remove(withValue);
+    }
+
+    return changed;
+  }
+
   // Find all method invocations that never returns normally, split the block
   // after each such invoke instruction and follow it with a block throwing a
   // null value (which should result in NPE). Note that this throw is not
@@ -3439,7 +3646,7 @@
   // Note that addSuppressed() and getSuppressed() methods are final in
   // Throwable, so these changes don't have to worry about overrides.
   public void rewriteThrowableAddAndGetSuppressed(IRCode code) {
-    DexItemFactory.ThrowableMethods throwableMethods = dexItemFactory.throwableMethods;
+    ThrowableMethods throwableMethods = dexItemFactory.throwableMethods;
 
     for (BasicBlock block : code.blocks) {
       InstructionListIterator iterator = block.listIterator();
@@ -3579,7 +3786,7 @@
       } else {
         // Insert "if (argument != null) ...".
         successor = block.unlinkSingleSuccessor();
-        If theIf = new If(If.Type.NE, argument);
+        If theIf = new If(Type.NE, argument);
         theIf.setPosition(position);
         BasicBlock ifBlock = BasicBlock.createIfBlock(code.blocks.size(), theIf);
         code.blocks.add(ifBlock);
diff --git a/src/test/java/com/android/tools/r8/TestRunResult.java b/src/test/java/com/android/tools/r8/TestRunResult.java
index 65a57e6..a032fd6 100644
--- a/src/test/java/com/android/tools/r8/TestRunResult.java
+++ b/src/test/java/com/android/tools/r8/TestRunResult.java
@@ -29,6 +29,10 @@
 
   abstract RR self();
 
+  public AndroidApp app() {
+    return app;
+  }
+
   public String getStdOut() {
     return result.stdout;
   }
diff --git a/src/test/java/com/android/tools/r8/ir/analysis/type/ConstrainedPrimitiveTypeTest.java b/src/test/java/com/android/tools/r8/ir/analysis/type/ConstrainedPrimitiveTypeTest.java
index c140610..798f1b0 100644
--- a/src/test/java/com/android/tools/r8/ir/analysis/type/ConstrainedPrimitiveTypeTest.java
+++ b/src/test/java/com/android/tools/r8/ir/analysis/type/ConstrainedPrimitiveTypeTest.java
@@ -10,10 +10,12 @@
 import static com.android.tools.r8.ir.analysis.type.TypeLatticeElement.LONG;
 import static org.junit.Assert.assertEquals;
 
+import com.android.tools.r8.NeverInline;
 import com.android.tools.r8.ir.analysis.AnalysisTestBase;
 import com.android.tools.r8.ir.code.ConstNumber;
 import com.android.tools.r8.ir.code.IRCode;
 import com.android.tools.r8.ir.code.Instruction;
+import com.android.tools.r8.utils.StringUtils;
 import com.google.common.collect.Streams;
 import java.util.function.Consumer;
 import org.junit.Test;
@@ -25,6 +27,21 @@
   }
 
   @Test
+  public void testOutput() throws Exception {
+    String expectedOutput =
+        StringUtils.lines("1", "2", "3", "1.0", "1.0", "2.0", "1", "1", "2", "1.0", "1.0", "2.0");
+
+    testForJvm().addTestClasspath().run(TestClass.class).assertSuccessWithOutput(expectedOutput);
+
+    testForR8(Backend.DEX)
+        .addInnerClasses(ConstrainedPrimitiveTypeTest.class)
+        .addKeepMainRule(TestClass.class)
+        .enableInliningAnnotations()
+        .run(TestClass.class)
+        .assertSuccessWithOutput(expectedOutput);
+  }
+
+  @Test
   public void testIntWithInvokeUser() throws Exception {
     buildAndCheckIR("intWithInvokeUserTest", testInspector(INT, 1));
   }
@@ -83,26 +100,47 @@
 
   static class TestClass {
 
-    public static void intWithInvokeUserTest() {
-      int x = 1;
-      Integer.toString(x);
+    public static void main(String[] args) {
+      boolean unknownButTrue = args.length >= 0;
+      boolean unknownButFalse = args.length < 0;
+      intWithInvokeUserTest();
+      intWithIndirectInvokeUserTest(unknownButTrue);
+      intWithIndirectInvokeUserTest(unknownButFalse);
+      floatWithInvokeUserTest();
+      floatWithIndirectInvokeUserTest(unknownButTrue);
+      floatWithIndirectInvokeUserTest(unknownButFalse);
+      longWithInvokeUserTest();
+      longWithIndirectInvokeUserTest(unknownButTrue);
+      longWithIndirectInvokeUserTest(unknownButFalse);
+      doubleWithInvokeUserTest();
+      doubleWithIndirectInvokeUserTest(unknownButTrue);
+      doubleWithIndirectInvokeUserTest(unknownButFalse);
     }
 
+    @NeverInline
+    public static void intWithInvokeUserTest() {
+      int x = 1;
+      System.out.println(Integer.toString(x));
+    }
+
+    @NeverInline
     public static void intWithIndirectInvokeUserTest(boolean unknown) {
       int x;
       if (unknown) {
-        x = 1;
-      } else {
         x = 2;
+      } else {
+        x = 3;
       }
-      Integer.toString(x);
+      System.out.println(Integer.toString(x));
     }
 
+    @NeverInline
     public static void floatWithInvokeUserTest() {
       float x = 1f;
-      Float.toString(x);
+      System.out.println(Float.toString(x));
     }
 
+    @NeverInline
     public static void floatWithIndirectInvokeUserTest(boolean unknown) {
       float x;
       if (unknown) {
@@ -110,14 +148,16 @@
       } else {
         x = 2f;
       }
-      Float.toString(x);
+      System.out.println(Float.toString(x));
     }
 
+    @NeverInline
     public static void longWithInvokeUserTest() {
       long x = 1L;
-      Long.toString(x);
+      System.out.println(Long.toString(x));
     }
 
+    @NeverInline
     public static void longWithIndirectInvokeUserTest(boolean unknown) {
       long x;
       if (unknown) {
@@ -125,14 +165,16 @@
       } else {
         x = 2L;
       }
-      Long.toString(x);
+      System.out.println(Long.toString(x));
     }
 
+    @NeverInline
     public static void doubleWithInvokeUserTest() {
       double x = 1.0;
-      Double.toString(x);
+      System.out.println(Double.toString(x));
     }
 
+    @NeverInline
     public static void doubleWithIndirectInvokeUserTest(boolean unknown) {
       double x;
       if (unknown) {
@@ -140,7 +182,7 @@
       } else {
         x = 2f;
       }
-      Double.toString(x);
+      System.out.println(Double.toString(x));
     }
   }
 }
diff --git a/src/test/java/com/android/tools/r8/ir/optimize/RedundantConstNumberRemovalTest.java b/src/test/java/com/android/tools/r8/ir/optimize/RedundantConstNumberRemovalTest.java
new file mode 100644
index 0000000..fc382ee
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/ir/optimize/RedundantConstNumberRemovalTest.java
@@ -0,0 +1,248 @@
+// Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+package com.android.tools.r8.ir.optimize;
+
+import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import com.android.tools.r8.NeverInline;
+import com.android.tools.r8.R8TestRunResult;
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.ir.code.BasicBlock;
+import com.android.tools.r8.ir.code.IRCode;
+import com.android.tools.r8.ir.code.Instruction;
+import com.android.tools.r8.utils.StringUtils;
+import com.android.tools.r8.utils.codeinspector.ClassSubject;
+import com.android.tools.r8.utils.codeinspector.InstructionSubject;
+import com.android.tools.r8.utils.codeinspector.MethodSubject;
+import com.google.common.collect.Streams;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+@RunWith(Parameterized.class)
+public class RedundantConstNumberRemovalTest extends TestBase {
+
+  private final Backend backend;
+
+  @Parameters(name = "Backend: {0}")
+  public static Backend[] data() {
+    return Backend.values();
+  }
+
+  public RedundantConstNumberRemovalTest(Backend backend) {
+    this.backend = backend;
+  }
+
+  @Test
+  public void test() throws Exception {
+    String expectedOutput =
+        StringUtils.lines(
+            "true", "true", "true", "true", "true", "true", "true", "true", "true", "true", "true",
+            "true", "true", "true", "true", "true");
+
+    if (backend == Backend.CF) {
+      testForJvm().addTestClasspath().run(TestClass.class).assertSuccessWithOutput(expectedOutput);
+    }
+
+    R8TestRunResult result =
+        testForR8(backend)
+            .addInnerClasses(RedundantConstNumberRemovalTest.class)
+            .addKeepMainRule(TestClass.class)
+            .enableInliningAnnotations()
+            .run(TestClass.class)
+            .assertSuccessWithOutput(expectedOutput);
+
+    ClassSubject classSubject = result.inspector().clazz(TestClass.class);
+    verifyBooleanCheckTest(classSubject.uniqueMethodWithName("booleanCheckTest"));
+    verifyBooleanCheckTest(classSubject.uniqueMethodWithName("negateBooleanCheckTest"));
+    verifyIntCheckTest(classSubject.uniqueMethodWithName("intCheckTest"));
+    verifyIntCheckTest(classSubject.uniqueMethodWithName("negateIntCheckTest"));
+    verifyNullCheckTest(classSubject.uniqueMethodWithName("nullCheckTest"));
+    verifyNullCheckTest(classSubject.uniqueMethodWithName("invertedNullCheckTest"));
+    verifyNullCheckTest(classSubject.uniqueMethodWithName("nonNullCheckTest"));
+    verifyNullCheckWithWrongTypeTest(
+        classSubject.uniqueMethodWithName("nullCheckWithWrongTypeTest"));
+  }
+
+  private void verifyBooleanCheckTest(MethodSubject methodSubject) {
+    assertThat(methodSubject, isPresent());
+
+    if (backend == Backend.DEX) {
+      // Check that the generated code for booleanCheckTest() only has a return instruction.
+      assertEquals(1, methodSubject.streamInstructions().count());
+      assertTrue(methodSubject.iterateInstructions().next().isReturn());
+    } else {
+      assert backend == Backend.CF;
+      // Check that the generated code for booleanCheckTest() only has return instructions that
+      // return the argument.
+      // TODO(christofferqa): CF backend does not share identical prefix of successors.
+      IRCode code = methodSubject.buildIR();
+      assertTrue(
+          Streams.stream(code.instructionIterator())
+              .filter(Instruction::isReturn)
+              .allMatch(
+                  instruction -> instruction.asReturn().returnValue().definition.isArgument()));
+    }
+  }
+
+  private void verifyIntCheckTest(MethodSubject methodSubject) {
+    assertThat(methodSubject, isPresent());
+    IRCode code = methodSubject.buildIR();
+
+    if (backend == Backend.DEX) {
+      // Only a single basic block.
+      assertEquals(1, code.blocks.size());
+      // The block only has three instructions.
+      BasicBlock entryBlock = code.blocks.get(0);
+      assertEquals(3, entryBlock.getInstructions().size());
+      // The first one is the `argument` instruction.
+      Instruction argument = entryBlock.getInstructions().getFirst();
+      assertTrue(argument.isArgument());
+      // The next one is a `const-number` instruction is not used for anything.
+      // TODO(christofferqa): D8 should be able to get rid of the unused const-number instruction.
+      Instruction unused = entryBlock.getInstructions().get(1);
+      assertTrue(unused.isConstNumber());
+      assertEquals(0, unused.outValue().numberOfAllUsers());
+      // The `return` instruction returns the argument.
+      Instruction ret = entryBlock.getInstructions().getLast();
+      assertTrue(ret.isReturn());
+      assertTrue(ret.asReturn().returnValue().definition.isArgument());
+    } else {
+      // Check that the generated code for intCheckTest() only has return instructions that
+      // return the argument.
+      // TODO(christofferqa): CF backend does not share identical prefix of successors.
+      assertTrue(
+          Streams.stream(code.instructionIterator())
+              .filter(Instruction::isReturn)
+              .allMatch(
+                  instruction -> instruction.asReturn().returnValue().definition.isArgument()));
+    }
+  }
+
+  private void verifyNullCheckTest(MethodSubject methodSubject) {
+    // Check that the generated code for nullCheckTest() only has a single `const-null` instruction.
+    assertThat(methodSubject, isPresent());
+    assertEquals(
+        1, methodSubject.streamInstructions().filter(InstructionSubject::isConstNull).count());
+
+    // Also check that one of the return instructions actually returns the argument.
+    IRCode code = methodSubject.buildIR();
+    assertEquals(1, code.collectArguments().size());
+    // TODO(b/120257211): D8 should replace `return null` by `return arg`.
+    assertFalse(
+        code.collectArguments().get(0).uniqueUsers().stream().anyMatch(Instruction::isReturn));
+  }
+
+  private void verifyNullCheckWithWrongTypeTest(MethodSubject methodSubject) {
+    // Check that the generated code for nullCheckWithWrongTypeTest() still has a `return null`
+    // instruction.
+    assertThat(methodSubject, isPresent());
+    IRCode code = methodSubject.buildIR();
+
+    // Check that the code returns null.
+    assertTrue(
+        Streams.stream(code.instructionIterator())
+            .anyMatch(
+                instruction ->
+                    instruction.isReturn()
+                        && instruction.asReturn().returnValue().definition.isConstNumber()));
+
+    // Also check that none of the return instructions actually returns the argument.
+    assertEquals(1, code.collectArguments().size());
+    assertTrue(
+        code.collectArguments().get(0).uniqueUsers().stream().noneMatch(Instruction::isReturn));
+  }
+
+  static class TestClass {
+
+    public static void main(String[] args) {
+      System.out.println(booleanCheckTest(true) == true);
+      System.out.println(booleanCheckTest(false) == false);
+      System.out.println(negateBooleanCheckTest(true) == true);
+      System.out.println(negateBooleanCheckTest(false) == false);
+      System.out.println(intCheckTest(0) == 0);
+      System.out.println(intCheckTest(42) == 42);
+      System.out.println(negateIntCheckTest(0) == 0);
+      System.out.println(negateIntCheckTest(42) == 42);
+      System.out.println(nullCheckTest(new Object()) != null);
+      System.out.println(nullCheckTest(null) == null);
+      System.out.println(invertedNullCheckTest(new Object()) != null);
+      System.out.println(invertedNullCheckTest(null) == null);
+      System.out.println(nonNullCheckTest(new Object()) != null);
+      System.out.println(nonNullCheckTest(null) == null);
+      System.out.println(nullCheckWithWrongTypeTest(new Object()) != null);
+      System.out.println(nullCheckWithWrongTypeTest(null) == null);
+    }
+
+    @NeverInline
+    private static boolean booleanCheckTest(boolean x) {
+      if (x) {
+        return true; // should be replaced by `x`.
+      }
+      return false; // should be replaced by `x`.
+    }
+
+    @NeverInline
+    private static boolean negateBooleanCheckTest(boolean x) {
+      if (!x) {
+        return false; // should be replaced by `x`
+      }
+      return true; // should be replaced by `x`
+    }
+
+    @NeverInline
+    private static int intCheckTest(int x) {
+      if (x == 42) {
+        return 42; // should be replaced by `x`.
+      }
+      return x;
+    }
+
+    @NeverInline
+    private static int negateIntCheckTest(int x) {
+      if (x != 42) {
+        return x;
+      }
+      return 42; // should be replaced by `x`
+    }
+
+    @NeverInline
+    private static Object nullCheckTest(Object x) {
+      if (x != null) {
+        return new Object();
+      }
+      return null; // should be replaced by `x`.
+    }
+
+    @NeverInline
+    private static Object invertedNullCheckTest(Object x) {
+      if (null == x) {
+        return null; // should be replaced by `x`.
+      }
+      return new Object();
+    }
+
+    @NeverInline
+    private static Object nonNullCheckTest(Object x) {
+      if (x == null) {
+        return null; // should be replaced by `x`
+      }
+      return new Object();
+    }
+
+    @NeverInline
+    private static Throwable nullCheckWithWrongTypeTest(Object x) {
+      if (x != null) {
+        return new Throwable();
+      }
+      return null; // cannot be replaced by `x` because Object is not a subtype of Throwable.
+    }
+  }
+}
diff --git a/src/test/java/com/android/tools/r8/utils/codeinspector/AbsentMethodSubject.java b/src/test/java/com/android/tools/r8/utils/codeinspector/AbsentMethodSubject.java
index c2ced01..8e24088 100644
--- a/src/test/java/com/android/tools/r8/utils/codeinspector/AbsentMethodSubject.java
+++ b/src/test/java/com/android/tools/r8/utils/codeinspector/AbsentMethodSubject.java
@@ -6,12 +6,18 @@
 
 import com.android.tools.r8.errors.Unreachable;
 import com.android.tools.r8.graph.DexEncodedMethod;
+import com.android.tools.r8.ir.code.IRCode;
 import com.android.tools.r8.naming.MemberNaming.MethodSignature;
 import com.android.tools.r8.naming.MemberNaming.Signature;
 
 public class AbsentMethodSubject extends MethodSubject {
 
   @Override
+  public IRCode buildIR() {
+    throw new Unreachable("Cannot build IR for an absent method");
+  }
+
+  @Override
   public boolean isPresent() {
     return false;
   }
diff --git a/src/test/java/com/android/tools/r8/utils/codeinspector/CfInstructionSubject.java b/src/test/java/com/android/tools/r8/utils/codeinspector/CfInstructionSubject.java
index 924ec2d..ee2155e 100644
--- a/src/test/java/com/android/tools/r8/utils/codeinspector/CfInstructionSubject.java
+++ b/src/test/java/com/android/tools/r8/utils/codeinspector/CfInstructionSubject.java
@@ -4,7 +4,6 @@
 
 package com.android.tools.r8.utils.codeinspector;
 
-import static org.junit.Assert.assertTrue;
 
 import com.android.tools.r8.cf.code.CfArithmeticBinop;
 import com.android.tools.r8.cf.code.CfCheckCast;
@@ -31,7 +30,6 @@
 import com.android.tools.r8.cf.code.CfStackInstruction;
 import com.android.tools.r8.cf.code.CfSwitch;
 import com.android.tools.r8.cf.code.CfThrow;
-import com.android.tools.r8.graph.CfCode;
 import com.android.tools.r8.graph.DexField;
 import com.android.tools.r8.graph.DexMethod;
 import com.android.tools.r8.ir.code.Monitor.Type;
@@ -167,6 +165,11 @@
   }
 
   @Override
+  public boolean isReturn() {
+    return instruction instanceof CfReturn;
+  }
+
+  @Override
   public boolean isReturnVoid() {
     return instruction instanceof CfReturnVoid;
   }
diff --git a/src/test/java/com/android/tools/r8/utils/codeinspector/CodeInspector.java b/src/test/java/com/android/tools/r8/utils/codeinspector/CodeInspector.java
index 1f520ff..9983320 100644
--- a/src/test/java/com/android/tools/r8/utils/codeinspector/CodeInspector.java
+++ b/src/test/java/com/android/tools/r8/utils/codeinspector/CodeInspector.java
@@ -58,7 +58,7 @@
 
 public class CodeInspector {
 
-  private final DexApplication application;
+  final DexApplication application;
   final DexItemFactory dexItemFactory;
   private final ClassNameMapper mapping;
   final Map<String, String> originalToObfuscatedMapping;
diff --git a/src/test/java/com/android/tools/r8/utils/codeinspector/DexInstructionSubject.java b/src/test/java/com/android/tools/r8/utils/codeinspector/DexInstructionSubject.java
index 6d463da..7051226 100644
--- a/src/test/java/com/android/tools/r8/utils/codeinspector/DexInstructionSubject.java
+++ b/src/test/java/com/android/tools/r8/utils/codeinspector/DexInstructionSubject.java
@@ -70,6 +70,7 @@
 import com.android.tools.r8.code.NewInstance;
 import com.android.tools.r8.code.Nop;
 import com.android.tools.r8.code.PackedSwitch;
+import com.android.tools.r8.code.Return;
 import com.android.tools.r8.code.ReturnObject;
 import com.android.tools.r8.code.ReturnVoid;
 import com.android.tools.r8.code.Sget;
@@ -275,6 +276,11 @@
   }
 
   @Override
+  public boolean isReturn() {
+    return instruction instanceof Return;
+  }
+
+  @Override
   public boolean isReturnVoid() {
     return instruction instanceof ReturnVoid;
   }
diff --git a/src/test/java/com/android/tools/r8/utils/codeinspector/FoundMethodSubject.java b/src/test/java/com/android/tools/r8/utils/codeinspector/FoundMethodSubject.java
index 6c23162..796532d 100644
--- a/src/test/java/com/android/tools/r8/utils/codeinspector/FoundMethodSubject.java
+++ b/src/test/java/com/android/tools/r8/utils/codeinspector/FoundMethodSubject.java
@@ -9,6 +9,7 @@
 import com.android.tools.r8.code.Instruction;
 import com.android.tools.r8.errors.Unimplemented;
 import com.android.tools.r8.errors.Unreachable;
+import com.android.tools.r8.graph.AppInfo;
 import com.android.tools.r8.graph.CfCode;
 import com.android.tools.r8.graph.Code;
 import com.android.tools.r8.graph.DexCode;
@@ -17,10 +18,14 @@
 import com.android.tools.r8.graph.DexDebugPositionState;
 import com.android.tools.r8.graph.DexEncodedMethod;
 import com.android.tools.r8.graph.DexString;
+import com.android.tools.r8.graph.GraphLense;
 import com.android.tools.r8.graph.JarCode;
+import com.android.tools.r8.ir.code.IRCode;
 import com.android.tools.r8.naming.MemberNaming;
 import com.android.tools.r8.naming.MemberNaming.MethodSignature;
 import com.android.tools.r8.naming.signature.GenericSignatureParser;
+import com.android.tools.r8.origin.Origin;
+import com.android.tools.r8.utils.InternalOptions;
 import it.unimi.dsi.fastutil.objects.Reference2IntMap;
 import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
 import java.util.Arrays;
@@ -41,6 +46,19 @@
   }
 
   @Override
+  public IRCode buildIR() {
+    DexEncodedMethod method = getMethod();
+    return method
+        .getCode()
+        .buildIR(
+            method,
+            new AppInfo(codeInspector.application),
+            GraphLense.getIdentityLense(),
+            new InternalOptions(),
+            Origin.unknown());
+  }
+
+  @Override
   public boolean isPresent() {
     return true;
   }
diff --git a/src/test/java/com/android/tools/r8/utils/codeinspector/InstructionSubject.java b/src/test/java/com/android/tools/r8/utils/codeinspector/InstructionSubject.java
index 6abeacf..294cc8c 100644
--- a/src/test/java/com/android/tools/r8/utils/codeinspector/InstructionSubject.java
+++ b/src/test/java/com/android/tools/r8/utils/codeinspector/InstructionSubject.java
@@ -58,6 +58,8 @@
 
   boolean isIfEqz();
 
+  boolean isReturn();
+
   boolean isReturnVoid();
 
   boolean isReturnObject();
diff --git a/src/test/java/com/android/tools/r8/utils/codeinspector/MethodSubject.java b/src/test/java/com/android/tools/r8/utils/codeinspector/MethodSubject.java
index b0d2c9b..8fb4001 100644
--- a/src/test/java/com/android/tools/r8/utils/codeinspector/MethodSubject.java
+++ b/src/test/java/com/android/tools/r8/utils/codeinspector/MethodSubject.java
@@ -5,6 +5,7 @@
 package com.android.tools.r8.utils.codeinspector;
 
 import com.android.tools.r8.graph.DexEncodedMethod;
+import com.android.tools.r8.ir.code.IRCode;
 import com.android.tools.r8.naming.MemberNaming.MethodSignature;
 import com.google.common.collect.Streams;
 import java.util.Iterator;
@@ -13,6 +14,8 @@
 
 public abstract class MethodSubject extends MemberSubject {
 
+  public abstract IRCode buildIR();
+
   public abstract boolean isAbstract();
 
   public abstract boolean isBridge();