1 /*
   2  * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package org.graalvm.compiler.nodes;
  24 
  25 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_2;
  26 import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_2;
  27 
  28 import java.util.ArrayList;
  29 import java.util.Arrays;
  30 import java.util.Iterator;
  31 import java.util.List;
  32 
  33 import org.graalvm.compiler.core.common.calc.Condition;
  34 import org.graalvm.compiler.core.common.type.IntegerStamp;
  35 import org.graalvm.compiler.core.common.type.Stamp;
  36 import org.graalvm.compiler.core.common.type.StampFactory;
  37 import org.graalvm.compiler.debug.Debug;
  38 import org.graalvm.compiler.debug.DebugCounter;
  39 import org.graalvm.compiler.debug.GraalError;
  40 import org.graalvm.compiler.graph.Node;
  41 import org.graalvm.compiler.graph.NodeClass;
  42 import org.graalvm.compiler.graph.iterators.NodeIterable;
  43 import org.graalvm.compiler.graph.spi.Canonicalizable;
  44 import org.graalvm.compiler.graph.spi.Simplifiable;
  45 import org.graalvm.compiler.graph.spi.SimplifierTool;
  46 import org.graalvm.compiler.nodeinfo.InputType;
  47 import org.graalvm.compiler.nodeinfo.NodeInfo;
  48 import org.graalvm.compiler.nodes.calc.CompareNode;
  49 import org.graalvm.compiler.nodes.calc.ConditionalNode;
  50 import org.graalvm.compiler.nodes.calc.IntegerBelowNode;
  51 import org.graalvm.compiler.nodes.calc.IntegerEqualsNode;
  52 import org.graalvm.compiler.nodes.calc.IntegerLessThanNode;
  53 import org.graalvm.compiler.nodes.calc.IsNullNode;
  54 import org.graalvm.compiler.nodes.calc.NormalizeCompareNode;
  55 import org.graalvm.compiler.nodes.java.InstanceOfNode;
  56 import org.graalvm.compiler.nodes.spi.LIRLowerable;
  57 import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
  58 import org.graalvm.compiler.nodes.util.GraphUtil;
  59 import org.graalvm.util.EconomicMap;
  60 import org.graalvm.util.Equivalence;
  61 
  62 import jdk.vm.ci.meta.Constant;
  63 import jdk.vm.ci.meta.ConstantReflectionProvider;
  64 import jdk.vm.ci.meta.JavaConstant;
  65 import jdk.vm.ci.meta.JavaKind;
  66 import jdk.vm.ci.meta.PrimitiveConstant;
  67 
  68 /**
  69  * The {@code IfNode} represents a branch that can go one of two directions depending on the outcome
  70  * of a comparison.
  71  */
  72 @NodeInfo(cycles = CYCLES_2, size = SIZE_2, sizeRationale = "2 jmps")
  73 public final class IfNode extends ControlSplitNode implements Simplifiable, LIRLowerable {
  74     public static final NodeClass<IfNode> TYPE = NodeClass.create(IfNode.class);
  75 
  76     private static final DebugCounter CORRECTED_PROBABILITIES = Debug.counter("CorrectedProbabilities");
  77 
  78     @Successor AbstractBeginNode trueSuccessor;
  79     @Successor AbstractBeginNode falseSuccessor;
  80     @Input(InputType.Condition) LogicNode condition;
  81     protected double trueSuccessorProbability;
  82 
  83     public LogicNode condition() {
  84         return condition;
  85     }
  86 
  87     public void setCondition(LogicNode x) {
  88         updateUsages(condition, x);
  89         condition = x;
  90     }
  91 
  92     public IfNode(LogicNode condition, FixedNode trueSuccessor, FixedNode falseSuccessor, double trueSuccessorProbability) {
  93         this(condition, BeginNode.begin(trueSuccessor), BeginNode.begin(falseSuccessor), trueSuccessorProbability);
  94     }
  95 
  96     public IfNode(LogicNode condition, AbstractBeginNode trueSuccessor, AbstractBeginNode falseSuccessor, double trueSuccessorProbability) {
  97         super(TYPE, StampFactory.forVoid());
  98         this.condition = condition;
  99         this.falseSuccessor = falseSuccessor;
 100         this.trueSuccessor = trueSuccessor;
 101         setTrueSuccessorProbability(trueSuccessorProbability);
 102     }
 103 
 104     /**
 105      * Gets the true successor.
 106      *
 107      * @return the true successor
 108      */
 109     public AbstractBeginNode trueSuccessor() {
 110         return trueSuccessor;
 111     }
 112 
 113     /**
 114      * Gets the false successor.
 115      *
 116      * @return the false successor
 117      */
 118     public AbstractBeginNode falseSuccessor() {
 119         return falseSuccessor;
 120     }
 121 
 122     public double getTrueSuccessorProbability() {
 123         return this.trueSuccessorProbability;
 124     }
 125 
 126     public void setTrueSuccessor(AbstractBeginNode node) {
 127         updatePredecessor(trueSuccessor, node);
 128         trueSuccessor = node;
 129     }
 130 
 131     public void setFalseSuccessor(AbstractBeginNode node) {
 132         updatePredecessor(falseSuccessor, node);
 133         falseSuccessor = node;
 134     }
 135 
 136     /**
 137      * Gets the node corresponding to the specified outcome of the branch.
 138      *
 139      * @param istrue {@code true} if the true successor is requested, {@code false} otherwise
 140      * @return the corresponding successor
 141      */
 142     public AbstractBeginNode successor(boolean istrue) {
 143         return istrue ? trueSuccessor : falseSuccessor;
 144     }
 145 
 146     public void setTrueSuccessorProbability(double prob) {
 147         assert prob >= -0.000000001 && prob <= 1.000000001 : "Probability out of bounds: " + prob;
 148         trueSuccessorProbability = Math.min(1.0, Math.max(0.0, prob));
 149     }
 150 
 151     @Override
 152     public double probability(AbstractBeginNode successor) {
 153         return successor == trueSuccessor ? trueSuccessorProbability : 1 - trueSuccessorProbability;
 154     }
 155 
 156     @Override
 157     public void generate(NodeLIRBuilderTool gen) {
 158         gen.emitIf(this);
 159     }
 160 
 161     @Override
 162     public boolean verify() {
 163         assertTrue(condition() != null, "missing condition");
 164         assertTrue(trueSuccessor() != null, "missing trueSuccessor");
 165         assertTrue(falseSuccessor() != null, "missing falseSuccessor");
 166         return super.verify();
 167     }
 168 
 169     public void eliminateNegation() {
 170         AbstractBeginNode oldTrueSuccessor = trueSuccessor;
 171         AbstractBeginNode oldFalseSuccessor = falseSuccessor;
 172         trueSuccessor = oldFalseSuccessor;
 173         falseSuccessor = oldTrueSuccessor;
 174         trueSuccessorProbability = 1 - trueSuccessorProbability;
 175         setCondition(((LogicNegationNode) condition).getValue());
 176     }
 177 
 178     @Override
 179     public void simplify(SimplifierTool tool) {
 180         if (trueSuccessor().next() instanceof DeoptimizeNode) {
 181             if (trueSuccessorProbability != 0) {
 182                 CORRECTED_PROBABILITIES.increment();
 183                 trueSuccessorProbability = 0;
 184             }
 185         } else if (falseSuccessor().next() instanceof DeoptimizeNode) {
 186             if (trueSuccessorProbability != 1) {
 187                 CORRECTED_PROBABILITIES.increment();
 188                 trueSuccessorProbability = 1;
 189             }
 190         }
 191 
 192         if (condition() instanceof LogicNegationNode) {
 193             eliminateNegation();
 194         }
 195         if (condition() instanceof LogicConstantNode) {
 196             LogicConstantNode c = (LogicConstantNode) condition();
 197             if (c.getValue()) {
 198                 tool.deleteBranch(falseSuccessor());
 199                 tool.addToWorkList(trueSuccessor());
 200                 graph().removeSplit(this, trueSuccessor());
 201             } else {
 202                 tool.deleteBranch(trueSuccessor());
 203                 tool.addToWorkList(falseSuccessor());
 204                 graph().removeSplit(this, falseSuccessor());
 205             }
 206             return;
 207         }
 208         if (tool.allUsagesAvailable() && trueSuccessor().hasNoUsages() && falseSuccessor().hasNoUsages()) {
 209 
 210             pushNodesThroughIf(tool);
 211 
 212             if (checkForUnsignedCompare(tool) || removeOrMaterializeIf(tool)) {
 213                 return;
 214             }
 215         }
 216 
 217         if (removeIntermediateMaterialization(tool)) {
 218             return;
 219         }
 220 
 221         if (splitIfAtPhi(tool)) {
 222             return;
 223         }
 224 
 225         if (conditionalNodeOptimization(tool)) {
 226             return;
 227         }
 228 
 229         if (falseSuccessor().hasNoUsages() && (!(falseSuccessor() instanceof LoopExitNode)) && falseSuccessor().next() instanceof IfNode) {
 230             AbstractBeginNode intermediateBegin = falseSuccessor();
 231             IfNode nextIf = (IfNode) intermediateBegin.next();
 232             double probabilityB = (1.0 - this.trueSuccessorProbability) * nextIf.trueSuccessorProbability;
 233             if (this.trueSuccessorProbability < probabilityB) {
 234                 // Reordering of those two if statements is beneficial from the point of view of
 235                 // their probabilities.
 236                 if (prepareForSwap(tool.getConstantReflection(), condition(), nextIf.condition())) {
 237                     // Reordering is allowed from (if1 => begin => if2) to (if2 => begin => if1).
 238                     assert intermediateBegin.next() == nextIf;
 239                     AbstractBeginNode bothFalseBegin = nextIf.falseSuccessor();
 240                     nextIf.setFalseSuccessor(null);
 241                     intermediateBegin.setNext(null);
 242                     this.setFalseSuccessor(null);
 243 
 244                     this.replaceAtPredecessor(nextIf);
 245                     nextIf.setFalseSuccessor(intermediateBegin);
 246                     intermediateBegin.setNext(this);
 247                     this.setFalseSuccessor(bothFalseBegin);
 248                     nextIf.setTrueSuccessorProbability(probabilityB);
 249                     if (probabilityB == 1.0) {
 250                         this.setTrueSuccessorProbability(0.0);
 251                     } else {
 252                         double newProbability = this.trueSuccessorProbability / (1.0 - probabilityB);
 253                         this.setTrueSuccessorProbability(Math.min(1.0, newProbability));
 254                     }
 255                     return;
 256                 }
 257             }
 258         }
 259     }
 260 
 261     /**
 262      * Try to optimize this as if it were a {@link ConditionalNode}.
 263      */
 264     private boolean conditionalNodeOptimization(SimplifierTool tool) {
 265         if (trueSuccessor().next() instanceof AbstractEndNode && falseSuccessor().next() instanceof AbstractEndNode) {
 266             AbstractEndNode trueEnd = (AbstractEndNode) trueSuccessor().next();
 267             AbstractEndNode falseEnd = (AbstractEndNode) falseSuccessor().next();
 268             if (trueEnd.merge() != falseEnd.merge()) {
 269                 return false;
 270             }
 271             if (!(trueEnd.merge() instanceof MergeNode)) {
 272                 return false;
 273             }
 274             MergeNode merge = (MergeNode) trueEnd.merge();
 275             if (merge.usages().count() != 1 || merge.phis().count() != 1) {
 276                 return false;
 277             }
 278 
 279             if (trueSuccessor().anchored().isNotEmpty() || falseSuccessor().anchored().isNotEmpty()) {
 280                 return false;
 281             }
 282 
 283             PhiNode phi = merge.phis().first();
 284             ValueNode falseValue = phi.valueAt(falseEnd);
 285             ValueNode trueValue = phi.valueAt(trueEnd);
 286 
 287             ValueNode result = ConditionalNode.canonicalizeConditional(condition, trueValue, falseValue, phi.stamp());
 288             if (result != null) {
 289                 /*
 290                  * canonicalizeConditional returns possibly new nodes so add them to the graph.
 291                  */
 292                 if (result.graph() == null) {
 293                     result = graph().addOrUniqueWithInputs(result);
 294                 }
 295                 /*
 296                  * This optimization can be performed even if multiple values merge at this phi
 297                  * since the two inputs get simplified into one.
 298                  */
 299                 phi.setValueAt(trueEnd, result);
 300                 removeThroughFalseBranch(tool);
 301                 return true;
 302             }
 303         }
 304 
 305         return false;
 306     }
 307 
 308     private void pushNodesThroughIf(SimplifierTool tool) {
 309         assert trueSuccessor().hasNoUsages() && falseSuccessor().hasNoUsages();
 310         // push similar nodes upwards through the if, thereby deduplicating them
 311         do {
 312             AbstractBeginNode trueSucc = trueSuccessor();
 313             AbstractBeginNode falseSucc = falseSuccessor();
 314             if (trueSucc instanceof BeginNode && falseSucc instanceof BeginNode && trueSucc.next() instanceof FixedWithNextNode && falseSucc.next() instanceof FixedWithNextNode) {
 315                 FixedWithNextNode trueNext = (FixedWithNextNode) trueSucc.next();
 316                 FixedWithNextNode falseNext = (FixedWithNextNode) falseSucc.next();
 317                 NodeClass<?> nodeClass = trueNext.getNodeClass();
 318                 if (trueNext.getClass() == falseNext.getClass()) {
 319                     if (nodeClass.equalInputs(trueNext, falseNext) && trueNext.valueEquals(falseNext)) {
 320                         falseNext.replaceAtUsages(trueNext);
 321                         graph().removeFixed(falseNext);
 322                         GraphUtil.unlinkFixedNode(trueNext);
 323                         graph().addBeforeFixed(this, trueNext);
 324                         for (Node usage : trueNext.usages().snapshot()) {
 325                             if (usage.isAlive()) {
 326                                 NodeClass<?> usageNodeClass = usage.getNodeClass();
 327                                 if (usageNodeClass.valueNumberable() && !usageNodeClass.isLeafNode()) {
 328                                     Node newNode = graph().findDuplicate(usage);
 329                                     if (newNode != null) {
 330                                         usage.replaceAtUsagesAndDelete(newNode);
 331                                     }
 332                                 }
 333                                 if (usage.isAlive()) {
 334                                     tool.addToWorkList(usage);
 335                                 }
 336                             }
 337                         }
 338                         continue;
 339                     }
 340                 }
 341             }
 342             break;
 343         } while (true);
 344     }
 345 
 346     /**
 347      * Recognize a couple patterns that can be merged into an unsigned compare.
 348      *
 349      * @param tool
 350      * @return true if a replacement was done.
 351      */
 352     private boolean checkForUnsignedCompare(SimplifierTool tool) {
 353         assert trueSuccessor().hasNoUsages() && falseSuccessor().hasNoUsages();
 354         if (condition() instanceof IntegerLessThanNode) {
 355             IntegerLessThanNode lessThan = (IntegerLessThanNode) condition();
 356             Constant y = lessThan.getY().stamp().asConstant();
 357             if (y instanceof PrimitiveConstant && ((PrimitiveConstant) y).asLong() == 0 && falseSuccessor().next() instanceof IfNode) {
 358                 IfNode ifNode2 = (IfNode) falseSuccessor().next();
 359                 if (ifNode2.condition() instanceof IntegerLessThanNode) {
 360                     IntegerLessThanNode lessThan2 = (IntegerLessThanNode) ifNode2.condition();
 361                     AbstractBeginNode falseSucc = ifNode2.falseSuccessor();
 362                     AbstractBeginNode trueSucc = ifNode2.trueSuccessor();
 363                     IntegerBelowNode below = null;
 364                     /*
 365                      * Convert x >= 0 && x < positive which is represented as !(x < 0) && x <
 366                      * <positive> into an unsigned compare.
 367                      */
 368                     if (lessThan2.getX() == lessThan.getX() && lessThan2.getY().stamp() instanceof IntegerStamp && ((IntegerStamp) lessThan2.getY().stamp()).isPositive() &&
 369                                     sameDestination(trueSuccessor(), ifNode2.falseSuccessor)) {
 370                         below = graph().unique(new IntegerBelowNode(lessThan2.getX(), lessThan2.getY()));
 371                         // swap direction
 372                         AbstractBeginNode tmp = falseSucc;
 373                         falseSucc = trueSucc;
 374                         trueSucc = tmp;
 375                     } else if (lessThan2.getY() == lessThan.getX() && sameDestination(trueSuccessor(), ifNode2.trueSuccessor)) {
 376                         /*
 377                          * Convert x >= 0 && x <= positive which is represented as !(x < 0) &&
 378                          * !(<positive> > x), into x <| positive + 1. This can only be done for
 379                          * constants since there isn't a IntegerBelowEqualThanNode but that doesn't
 380                          * appear to be interesting.
 381                          */
 382                         JavaConstant positive = lessThan2.getX().asJavaConstant();
 383                         if (positive != null && positive.asLong() > 0 && positive.asLong() < positive.getJavaKind().getMaxValue()) {
 384                             ConstantNode newLimit = ConstantNode.forIntegerStamp(lessThan2.getX().stamp(), positive.asLong() + 1, graph());
 385                             below = graph().unique(new IntegerBelowNode(lessThan.getX(), newLimit));
 386                         }
 387                     }
 388                     if (below != null) {
 389                         ifNode2.setTrueSuccessor(null);
 390                         ifNode2.setFalseSuccessor(null);
 391 
 392                         IfNode newIfNode = graph().add(new IfNode(below, falseSucc, trueSucc, 1 - trueSuccessorProbability));
 393                         // Remove the < 0 test.
 394                         tool.deleteBranch(trueSuccessor);
 395                         graph().removeSplit(this, falseSuccessor);
 396 
 397                         // Replace the second test with the new one.
 398                         ifNode2.predecessor().replaceFirstSuccessor(ifNode2, newIfNode);
 399                         ifNode2.safeDelete();
 400                         return true;
 401                     }
 402                 }
 403             }
 404         }
 405         return false;
 406     }
 407 
 408     /**
 409      * Check it these two blocks end up at the same place. Meeting at the same merge, or
 410      * deoptimizing in the same way.
 411      */
 412     private static boolean sameDestination(AbstractBeginNode succ1, AbstractBeginNode succ2) {
 413         Node next1 = succ1.next();
 414         Node next2 = succ2.next();
 415         if (next1 instanceof EndNode && next2 instanceof EndNode) {
 416             EndNode end1 = (EndNode) next1;
 417             EndNode end2 = (EndNode) next2;
 418             if (end1.merge() == end2.merge()) {
 419                 for (PhiNode phi : end1.merge().phis()) {
 420                     if (phi.valueAt(end1) != phi.valueAt(end2)) {
 421                         return false;
 422                     }
 423                 }
 424                 // They go to the same MergeNode and merge the same values
 425                 return true;
 426             }
 427         } else if (next1 instanceof DeoptimizeNode && next2 instanceof DeoptimizeNode) {
 428             DeoptimizeNode deopt1 = (DeoptimizeNode) next1;
 429             DeoptimizeNode deopt2 = (DeoptimizeNode) next2;
 430             if (deopt1.reason() == deopt2.reason() && deopt1.action() == deopt2.action()) {
 431                 // Same deoptimization reason and action.
 432                 return true;
 433             }
 434         } else if (next1 instanceof LoopExitNode && next2 instanceof LoopExitNode) {
 435             LoopExitNode exit1 = (LoopExitNode) next1;
 436             LoopExitNode exit2 = (LoopExitNode) next2;
 437             if (exit1.loopBegin() == exit2.loopBegin() && exit1.stateAfter() == exit2.stateAfter() && exit1.stateAfter() == null && sameDestination(exit1, exit2)) {
 438                 // Exit the same loop and end up at the same place.
 439                 return true;
 440             }
 441         } else if (next1 instanceof ReturnNode && next2 instanceof ReturnNode) {
 442             ReturnNode exit1 = (ReturnNode) next1;
 443             ReturnNode exit2 = (ReturnNode) next2;
 444             if (exit1.result() == exit2.result()) {
 445                 // Exit the same loop and end up at the same place.
 446                 return true;
 447             }
 448         }
 449         return false;
 450     }
 451 
 452     private static boolean prepareForSwap(ConstantReflectionProvider constantReflection, LogicNode a, LogicNode b) {
 453         if (a instanceof InstanceOfNode) {
 454             InstanceOfNode instanceOfA = (InstanceOfNode) a;
 455             if (b instanceof IsNullNode) {
 456                 IsNullNode isNullNode = (IsNullNode) b;
 457                 if (isNullNode.getValue() == instanceOfA.getValue()) {
 458                     Debug.log("Can swap instanceof and isnull if");
 459                     return true;
 460                 }
 461             } else if (b instanceof InstanceOfNode) {
 462                 InstanceOfNode instanceOfB = (InstanceOfNode) b;
 463                 if (instanceOfA.getValue() == instanceOfB.getValue() && !instanceOfA.type().getType().isInterface() && !instanceOfB.type().getType().isInterface() &&
 464                                 !instanceOfA.type().getType().isAssignableFrom(instanceOfB.type().getType()) && !instanceOfB.type().getType().isAssignableFrom(instanceOfA.type().getType())) {
 465                     // Two instanceof on the same value with mutually exclusive types.
 466                     Debug.log("Can swap instanceof for types %s and %s", instanceOfA.type(), instanceOfB.type());
 467                     return true;
 468                 }
 469             }
 470         } else if (a instanceof CompareNode) {
 471             CompareNode compareA = (CompareNode) a;
 472             Condition conditionA = compareA.condition();
 473             if (compareA.unorderedIsTrue()) {
 474                 return false;
 475             }
 476             if (b instanceof CompareNode) {
 477                 CompareNode compareB = (CompareNode) b;
 478                 if (compareA == compareB) {
 479                     Debug.log("Same conditions => do not swap and leave the work for global value numbering.");
 480                     return false;
 481                 }
 482                 if (compareB.unorderedIsTrue()) {
 483                     return false;
 484                 }
 485                 Condition comparableCondition = null;
 486                 Condition conditionB = compareB.condition();
 487                 if (compareB.getX() == compareA.getX() && compareB.getY() == compareA.getY()) {
 488                     comparableCondition = conditionB;
 489                 } else if (compareB.getX() == compareA.getY() && compareB.getY() == compareA.getX()) {
 490                     comparableCondition = conditionB.mirror();
 491                 }
 492 
 493                 if (comparableCondition != null) {
 494                     Condition combined = conditionA.join(comparableCondition);
 495                     if (combined == null) {
 496                         // The two conditions are disjoint => can reorder.
 497                         Debug.log("Can swap disjoint coditions on same values: %s and %s", conditionA, comparableCondition);
 498                         return true;
 499                     }
 500                 } else if (conditionA == Condition.EQ && conditionB == Condition.EQ) {
 501                     boolean canSwap = false;
 502                     if ((compareA.getX() == compareB.getX() && valuesDistinct(constantReflection, compareA.getY(), compareB.getY()))) {
 503                         canSwap = true;
 504                     } else if ((compareA.getX() == compareB.getY() && valuesDistinct(constantReflection, compareA.getY(), compareB.getX()))) {
 505                         canSwap = true;
 506                     } else if ((compareA.getY() == compareB.getX() && valuesDistinct(constantReflection, compareA.getX(), compareB.getY()))) {
 507                         canSwap = true;
 508                     } else if ((compareA.getY() == compareB.getY() && valuesDistinct(constantReflection, compareA.getX(), compareB.getX()))) {
 509                         canSwap = true;
 510                     }
 511 
 512                     if (canSwap) {
 513                         Debug.log("Can swap equality condition with one shared and one disjoint value.");
 514                         return true;
 515                     }
 516                 }
 517             }
 518         }
 519 
 520         return false;
 521     }
 522 
 523     private static boolean valuesDistinct(ConstantReflectionProvider constantReflection, ValueNode a, ValueNode b) {
 524         if (a.isConstant() && b.isConstant()) {
 525             Boolean equal = constantReflection.constantEquals(a.asConstant(), b.asConstant());
 526             if (equal != null) {
 527                 return !equal.booleanValue();
 528             }
 529         }
 530 
 531         Stamp stampA = a.stamp();
 532         Stamp stampB = b.stamp();
 533         return stampA.alwaysDistinct(stampB);
 534     }
 535 
 536     /**
 537      * Tries to remove an empty if construct or replace an if construct with a materialization.
 538      *
 539      * @return true if a transformation was made, false otherwise
 540      */
 541     private boolean removeOrMaterializeIf(SimplifierTool tool) {
 542         assert trueSuccessor().hasNoUsages() && falseSuccessor().hasNoUsages();
 543         if (trueSuccessor().next() instanceof AbstractEndNode && falseSuccessor().next() instanceof AbstractEndNode) {
 544             AbstractEndNode trueEnd = (AbstractEndNode) trueSuccessor().next();
 545             AbstractEndNode falseEnd = (AbstractEndNode) falseSuccessor().next();
 546             AbstractMergeNode merge = trueEnd.merge();
 547             if (merge == falseEnd.merge() && trueSuccessor().anchored().isEmpty() && falseSuccessor().anchored().isEmpty()) {
 548                 PhiNode singlePhi = null;
 549                 int distinct = 0;
 550                 for (PhiNode phi : merge.phis()) {
 551                     ValueNode trueValue = phi.valueAt(trueEnd);
 552                     ValueNode falseValue = phi.valueAt(falseEnd);
 553                     if (trueValue != falseValue) {
 554                         distinct++;
 555                         singlePhi = phi;
 556                     }
 557                 }
 558                 if (distinct == 0) {
 559                     /*
 560                      * Multiple phis but merging same values for true and false, so simply delete
 561                      * the path
 562                      */
 563                     removeThroughFalseBranch(tool);
 564                     return true;
 565                 } else if (distinct == 1) {
 566                     ValueNode trueValue = singlePhi.valueAt(trueEnd);
 567                     ValueNode falseValue = singlePhi.valueAt(falseEnd);
 568                     ValueNode conditional = canonicalizeConditionalCascade(trueValue, falseValue);
 569                     if (conditional != null) {
 570                         singlePhi.setValueAt(trueEnd, conditional);
 571                         removeThroughFalseBranch(tool);
 572                         return true;
 573                     }
 574                 }
 575             }
 576         }
 577         if (trueSuccessor().next() instanceof ReturnNode && falseSuccessor().next() instanceof ReturnNode) {
 578             ReturnNode trueEnd = (ReturnNode) trueSuccessor().next();
 579             ReturnNode falseEnd = (ReturnNode) falseSuccessor().next();
 580             ValueNode trueValue = trueEnd.result();
 581             ValueNode falseValue = falseEnd.result();
 582             ValueNode value = null;
 583             if (trueValue != null) {
 584                 if (trueValue == falseValue) {
 585                     value = trueValue;
 586                 } else {
 587                     value = canonicalizeConditionalCascade(trueValue, falseValue);
 588                     if (value == null) {
 589                         return false;
 590                     }
 591                 }
 592             }
 593             ReturnNode newReturn = graph().add(new ReturnNode(value));
 594             replaceAtPredecessor(newReturn);
 595             GraphUtil.killCFG(this);
 596             return true;
 597         }
 598         return false;
 599     }
 600 
 601     protected void removeThroughFalseBranch(SimplifierTool tool) {
 602         AbstractBeginNode trueBegin = trueSuccessor();
 603         graph().removeSplitPropagate(this, trueBegin, tool);
 604         tool.addToWorkList(trueBegin);
 605         if (condition() != null) {
 606             GraphUtil.tryKillUnused(condition());
 607         }
 608     }
 609 
 610     private ValueNode canonicalizeConditionalCascade(ValueNode trueValue, ValueNode falseValue) {
 611         if (trueValue.getStackKind() != falseValue.getStackKind()) {
 612             return null;
 613         }
 614         if (trueValue.getStackKind() != JavaKind.Int && trueValue.getStackKind() != JavaKind.Long) {
 615             return null;
 616         }
 617         if (trueValue.isConstant() && falseValue.isConstant()) {
 618             return graph().unique(new ConditionalNode(condition(), trueValue, falseValue));
 619         } else {
 620             ConditionalNode conditional = null;
 621             ValueNode constant = null;
 622             boolean negateCondition;
 623             if (trueValue instanceof ConditionalNode && falseValue.isConstant()) {
 624                 conditional = (ConditionalNode) trueValue;
 625                 constant = falseValue;
 626                 negateCondition = true;
 627             } else if (falseValue instanceof ConditionalNode && trueValue.isConstant()) {
 628                 conditional = (ConditionalNode) falseValue;
 629                 constant = trueValue;
 630                 negateCondition = false;
 631             } else {
 632                 return null;
 633             }
 634             boolean negateConditionalCondition = false;
 635             ValueNode otherValue = null;
 636             if (constant == conditional.trueValue()) {
 637                 otherValue = conditional.falseValue();
 638                 negateConditionalCondition = false;
 639             } else if (constant == conditional.falseValue()) {
 640                 otherValue = conditional.trueValue();
 641                 negateConditionalCondition = true;
 642             }
 643             if (otherValue != null) {
 644                 if (otherValue.isConstant() && graph().allowShortCircuitOr()) {
 645                     double shortCutProbability = probability(trueSuccessor());
 646                     LogicNode newCondition = LogicNode.or(condition(), negateCondition, conditional.condition(), negateConditionalCondition, shortCutProbability);
 647                     return graph().unique(new ConditionalNode(newCondition, constant, otherValue));
 648                 }
 649             } else if (!negateCondition && constant.isJavaConstant() && conditional.trueValue().isJavaConstant() && conditional.falseValue().isJavaConstant()) {
 650                 IntegerLessThanNode lessThan = null;
 651                 IntegerEqualsNode equals = null;
 652                 if (condition() instanceof IntegerLessThanNode && conditional.condition() instanceof IntegerEqualsNode && constant.asJavaConstant().asLong() == -1 &&
 653                                 conditional.trueValue().asJavaConstant().asLong() == 0 && conditional.falseValue().asJavaConstant().asLong() == 1) {
 654                     lessThan = (IntegerLessThanNode) condition();
 655                     equals = (IntegerEqualsNode) conditional.condition();
 656                 } else if (condition() instanceof IntegerEqualsNode && conditional.condition() instanceof IntegerLessThanNode && constant.asJavaConstant().asLong() == 0 &&
 657                                 conditional.trueValue().asJavaConstant().asLong() == -1 && conditional.falseValue().asJavaConstant().asLong() == 1) {
 658                     lessThan = (IntegerLessThanNode) conditional.condition();
 659                     equals = (IntegerEqualsNode) condition();
 660                 }
 661                 if (lessThan != null) {
 662                     assert equals != null;
 663                     if ((lessThan.getX() == equals.getX() && lessThan.getY() == equals.getY()) || (lessThan.getX() == equals.getY() && lessThan.getY() == equals.getX())) {
 664                         return graph().unique(new NormalizeCompareNode(lessThan.getX(), lessThan.getY(), false));
 665                     }
 666                 }
 667             }
 668         }
 669         return null;
 670     }
 671 
 672     /**
 673      * Take an if that is immediately dominated by a merge with a single phi and split off any paths
 674      * where the test would be statically decidable creating a new merge below the approriate side
 675      * of the IfNode. Any undecidable tests will continue to use the original IfNode.
 676      *
 677      * @param tool
 678      */
 679     private boolean splitIfAtPhi(SimplifierTool tool) {
 680         if (graph().getGuardsStage().areFrameStatesAtSideEffects()) {
 681             // Disabled until we make sure we have no FrameState-less merges at this stage
 682             return false;
 683         }
 684 
 685         if (!(predecessor() instanceof MergeNode)) {
 686             return false;
 687         }
 688         MergeNode merge = (MergeNode) predecessor();
 689         if (merge.forwardEndCount() == 1) {
 690             // Don't bother.
 691             return false;
 692         }
 693         if (merge.usages().count() != 1 || merge.phis().count() != 1) {
 694             return false;
 695         }
 696         if (merge.stateAfter() != null) {
 697             /* We'll get the chance to simplify this after frame state assignment. */
 698             return false;
 699         }
 700         PhiNode phi = merge.phis().first();
 701         if (phi.usages().count() != 1) {
 702             /*
 703              * For simplicity the below code assumes assumes the phi goes dead at the end so skip
 704              * this case.
 705              */
 706             return false;
 707         }
 708 
 709         /*
 710          * Check that the condition uses the phi and that there is only one user of the condition
 711          * expression.
 712          */
 713         if (!conditionUses(condition(), phi)) {
 714             return false;
 715         }
 716 
 717         /*
 718          * We could additionally filter for the case that at least some of the Phi inputs or one of
 719          * the condition inputs are constants but there are cases where a non-constant is
 720          * simplifiable, usually where the stamp allows the question to be answered.
 721          */
 722 
 723         /* Each successor of the if gets a new merge if needed. */
 724         MergeNode trueMerge = null;
 725         MergeNode falseMerge = null;
 726         assert merge.stateAfter() == null;
 727 
 728         for (EndNode end : merge.forwardEnds().snapshot()) {
 729             Node value = phi.valueAt(end);
 730             LogicNode result = computeCondition(tool, condition, phi, value);
 731             if (result instanceof LogicConstantNode) {
 732                 merge.removeEnd(end);
 733                 if (((LogicConstantNode) result).getValue()) {
 734                     if (trueMerge == null) {
 735                         trueMerge = insertMerge(trueSuccessor());
 736                     }
 737                     trueMerge.addForwardEnd(end);
 738                 } else {
 739                     if (falseMerge == null) {
 740                         falseMerge = insertMerge(falseSuccessor());
 741                     }
 742                     falseMerge.addForwardEnd(end);
 743                 }
 744             } else if (result != condition) {
 745                 // Build a new IfNode using the new condition
 746                 BeginNode trueBegin = graph().add(new BeginNode());
 747                 BeginNode falseBegin = graph().add(new BeginNode());
 748 
 749                 if (result.graph() == null) {
 750                     result = graph().addOrUniqueWithInputs(result);
 751                 }
 752                 IfNode newIfNode = graph().add(new IfNode(result, trueBegin, falseBegin, trueSuccessorProbability));
 753                 merge.removeEnd(end);
 754                 ((FixedWithNextNode) end.predecessor()).setNext(newIfNode);
 755 
 756                 if (trueMerge == null) {
 757                     trueMerge = insertMerge(trueSuccessor());
 758                 }
 759                 trueBegin.setNext(graph().add(new EndNode()));
 760                 trueMerge.addForwardEnd((EndNode) trueBegin.next());
 761 
 762                 if (falseMerge == null) {
 763                     falseMerge = insertMerge(falseSuccessor());
 764                 }
 765                 falseBegin.setNext(graph().add(new EndNode()));
 766                 falseMerge.addForwardEnd((EndNode) falseBegin.next());
 767 
 768                 end.safeDelete();
 769             }
 770         }
 771 
 772         transferProxies(trueSuccessor(), trueMerge);
 773         transferProxies(falseSuccessor(), falseMerge);
 774 
 775         cleanupMerge(tool, merge);
 776         cleanupMerge(tool, trueMerge);
 777         cleanupMerge(tool, falseMerge);
 778 
 779         return true;
 780     }
 781 
 782     /**
 783      * @param condition
 784      * @param phi
 785      * @return true if the passed in {@code condition} uses {@code phi} and the condition is only
 786      *         used once. Since the phi will go dead the condition using it will also have to be
 787      *         dead after the optimization.
 788      */
 789     private static boolean conditionUses(LogicNode condition, PhiNode phi) {
 790         if (condition.usages().count() != 1) {
 791             return false;
 792         }
 793         if (condition instanceof ShortCircuitOrNode) {
 794             if (condition.graph().getGuardsStage().areDeoptsFixed()) {
 795                 /*
 796                  * It can be unsafe to simplify a ShortCircuitOr before deopts are fixed because
 797                  * conversion to guards assumes that all the required conditions are being tested.
 798                  * Simplfying the condition based on context before this happens may lose a
 799                  * condition.
 800                  */
 801                 ShortCircuitOrNode orNode = (ShortCircuitOrNode) condition;
 802                 return (conditionUses(orNode.x, phi) || conditionUses(orNode.y, phi));
 803             }
 804         } else if (condition instanceof Canonicalizable.Unary<?>) {
 805             Canonicalizable.Unary<?> unary = (Canonicalizable.Unary<?>) condition;
 806             return unary.getValue() == phi;
 807         } else if (condition instanceof Canonicalizable.Binary<?>) {
 808             Canonicalizable.Binary<?> binary = (Canonicalizable.Binary<?>) condition;
 809             return binary.getX() == phi || binary.getY() == phi;
 810         }
 811         return false;
 812     }
 813 
 814     /**
 815      * Canonicalize {@code} condition using {@code value} in place of {@code phi}.
 816      *
 817      * @param tool
 818      * @param condition
 819      * @param phi
 820      * @param value
 821      * @return an improved LogicNode or the original condition
 822      */
 823     @SuppressWarnings("unchecked")
 824     private static LogicNode computeCondition(SimplifierTool tool, LogicNode condition, PhiNode phi, Node value) {
 825         if (condition instanceof ShortCircuitOrNode) {
 826             if (condition.graph().getGuardsStage().areDeoptsFixed() && condition.graph().allowShortCircuitOr()) {
 827                 ShortCircuitOrNode orNode = (ShortCircuitOrNode) condition;
 828                 LogicNode resultX = computeCondition(tool, orNode.x, phi, value);
 829                 LogicNode resultY = computeCondition(tool, orNode.y, phi, value);
 830                 if (resultX != orNode.x || resultY != orNode.y) {
 831                     LogicNode result = orNode.canonical(tool, resultX, resultY);
 832                     if (result != orNode) {
 833                         return result;
 834                     }
 835                     /*
 836                      * Create a new node to carry the optimized inputs.
 837                      */
 838                     ShortCircuitOrNode newOr = new ShortCircuitOrNode(resultX, orNode.xNegated, resultY,
 839                                     orNode.yNegated, orNode.getShortCircuitProbability());
 840                     return newOr.canonical(tool);
 841                 }
 842                 return orNode;
 843             }
 844         } else if (condition instanceof Canonicalizable.Binary<?>) {
 845             Canonicalizable.Binary<Node> compare = (Canonicalizable.Binary<Node>) condition;
 846             if (compare.getX() == phi) {
 847                 return (LogicNode) compare.canonical(tool, value, compare.getY());
 848             } else if (compare.getY() == phi) {
 849                 return (LogicNode) compare.canonical(tool, compare.getX(), value);
 850             }
 851         } else if (condition instanceof Canonicalizable.Unary<?>) {
 852             Canonicalizable.Unary<Node> compare = (Canonicalizable.Unary<Node>) condition;
 853             if (compare.getValue() == phi) {
 854                 return (LogicNode) compare.canonical(tool, value);
 855             }
 856         }
 857         if (condition instanceof Canonicalizable) {
 858             return (LogicNode) ((Canonicalizable) condition).canonical(tool);
 859         }
 860         return condition;
 861     }
 862 
 863     private static void transferProxies(AbstractBeginNode successor, MergeNode falseMerge) {
 864         if (successor instanceof LoopExitNode && falseMerge != null) {
 865             LoopExitNode loopExitNode = (LoopExitNode) successor;
 866             for (ProxyNode proxy : loopExitNode.proxies().snapshot()) {
 867                 proxy.replaceFirstInput(successor, falseMerge);
 868             }
 869         }
 870     }
 871 
 872     private void cleanupMerge(SimplifierTool tool, MergeNode merge) {
 873         if (merge != null && merge.isAlive()) {
 874             if (merge.forwardEndCount() == 0) {
 875                 GraphUtil.killCFG(merge, tool);
 876             } else if (merge.forwardEndCount() == 1) {
 877                 graph().reduceTrivialMerge(merge);
 878             }
 879         }
 880     }
 881 
 882     private MergeNode insertMerge(AbstractBeginNode begin) {
 883         MergeNode merge = graph().add(new MergeNode());
 884         if (!begin.anchored().isEmpty()) {
 885             Object before = null;
 886             before = begin.anchored().snapshot();
 887             begin.replaceAtUsages(InputType.Guard, merge);
 888             begin.replaceAtUsages(InputType.Anchor, merge);
 889             assert begin.anchored().isEmpty() : before + " " + begin.anchored().snapshot();
 890         }
 891 
 892         AbstractBeginNode theBegin = begin;
 893         if (begin instanceof LoopExitNode) {
 894             // Insert an extra begin to make it easier.
 895             theBegin = graph().add(new BeginNode());
 896             begin.replaceAtPredecessor(theBegin);
 897             theBegin.setNext(begin);
 898         }
 899         FixedNode next = theBegin.next();
 900         next.replaceAtPredecessor(merge);
 901         theBegin.setNext(graph().add(new EndNode()));
 902         merge.addForwardEnd((EndNode) theBegin.next());
 903         merge.setNext(next);
 904         return merge;
 905     }
 906 
 907     /**
 908      * Tries to connect code that initializes a variable directly with the successors of an if
 909      * construct that switches on the variable. For example, the pseudo code below:
 910      *
 911      * <pre>
 912      * contains(list, e, yes, no) {
 913      *     if (list == null || e == null) {
 914      *         condition = false;
 915      *     } else {
 916      *         condition = false;
 917      *         for (i in list) {
 918      *             if (i.equals(e)) {
 919      *                 condition = true;
 920      *                 break;
 921      *             }
 922      *         }
 923      *     }
 924      *     if (condition) {
 925      *         return yes;
 926      *     } else {
 927      *         return no;
 928      *     }
 929      * }
 930      * </pre>
 931      *
 932      * will be transformed into:
 933      *
 934      * <pre>
 935      * contains(list, e, yes, no) {
 936      *     if (list == null || e == null) {
 937      *         return no;
 938      *     } else {
 939      *         condition = false;
 940      *         for (i in list) {
 941      *             if (i.equals(e)) {
 942      *                 return yes;
 943      *             }
 944      *         }
 945      *         return no;
 946      *     }
 947      * }
 948      * </pre>
 949      *
 950      * @return true if a transformation was made, false otherwise
 951      */
 952     private boolean removeIntermediateMaterialization(SimplifierTool tool) {
 953         if (!(predecessor() instanceof AbstractMergeNode) || predecessor() instanceof LoopBeginNode) {
 954             return false;
 955         }
 956         AbstractMergeNode merge = (AbstractMergeNode) predecessor();
 957 
 958         if (!(condition() instanceof CompareNode)) {
 959             return false;
 960         }
 961 
 962         CompareNode compare = (CompareNode) condition();
 963         if (compare.getUsageCount() != 1) {
 964             return false;
 965         }
 966 
 967         // Only consider merges with a single usage that is both a phi and an operand of the
 968         // comparison
 969         NodeIterable<Node> mergeUsages = merge.usages();
 970         if (mergeUsages.count() != 1) {
 971             return false;
 972         }
 973         Node singleUsage = mergeUsages.first();
 974         if (!(singleUsage instanceof ValuePhiNode) || (singleUsage != compare.getX() && singleUsage != compare.getY())) {
 975             return false;
 976         }
 977 
 978         // Ensure phi is used by at most the comparison and the merge's frame state (if any)
 979         ValuePhiNode phi = (ValuePhiNode) singleUsage;
 980         NodeIterable<Node> phiUsages = phi.usages();
 981         if (phiUsages.count() > 2) {
 982             return false;
 983         }
 984         for (Node usage : phiUsages) {
 985             if (usage != compare && usage != merge.stateAfter()) {
 986                 return false;
 987             }
 988         }
 989 
 990         List<EndNode> mergePredecessors = merge.cfgPredecessors().snapshot();
 991         assert phi.valueCount() == merge.forwardEndCount();
 992 
 993         Constant[] xs = constantValues(compare.getX(), merge, false);
 994         Constant[] ys = constantValues(compare.getY(), merge, false);
 995         if (xs == null || ys == null) {
 996             return false;
 997         }
 998 
 999         // Sanity check that both ends are not followed by a merge without frame state.
1000         if (!checkFrameState(trueSuccessor()) && !checkFrameState(falseSuccessor())) {
1001             return false;
1002         }
1003 
1004         List<EndNode> falseEnds = new ArrayList<>(mergePredecessors.size());
1005         List<EndNode> trueEnds = new ArrayList<>(mergePredecessors.size());
1006         EconomicMap<AbstractEndNode, ValueNode> phiValues = EconomicMap.create(Equivalence.IDENTITY, mergePredecessors.size());
1007 
1008         AbstractBeginNode oldFalseSuccessor = falseSuccessor();
1009         AbstractBeginNode oldTrueSuccessor = trueSuccessor();
1010 
1011         setFalseSuccessor(null);
1012         setTrueSuccessor(null);
1013 
1014         Iterator<EndNode> ends = mergePredecessors.iterator();
1015         for (int i = 0; i < xs.length; i++) {
1016             EndNode end = ends.next();
1017             phiValues.put(end, phi.valueAt(end));
1018             if (compare.condition().foldCondition(xs[i], ys[i], tool.getConstantReflection(), compare.unorderedIsTrue())) {
1019                 trueEnds.add(end);
1020             } else {
1021                 falseEnds.add(end);
1022             }
1023         }
1024         assert !ends.hasNext();
1025         assert falseEnds.size() + trueEnds.size() == xs.length;
1026 
1027         connectEnds(falseEnds, phiValues, oldFalseSuccessor, merge, tool);
1028         connectEnds(trueEnds, phiValues, oldTrueSuccessor, merge, tool);
1029 
1030         if (this.trueSuccessorProbability == 0.0) {
1031             for (AbstractEndNode endNode : trueEnds) {
1032                 propagateZeroProbability(endNode);
1033             }
1034         }
1035 
1036         if (this.trueSuccessorProbability == 1.0) {
1037             for (AbstractEndNode endNode : falseEnds) {
1038                 propagateZeroProbability(endNode);
1039             }
1040         }
1041 
1042         /*
1043          * Remove obsolete ends only after processing all ends, otherwise oldTrueSuccessor or
1044          * oldFalseSuccessor might have been removed if it is a LoopExitNode.
1045          */
1046         if (falseEnds.isEmpty()) {
1047             GraphUtil.killCFG(oldFalseSuccessor);
1048         }
1049         if (trueEnds.isEmpty()) {
1050             GraphUtil.killCFG(oldTrueSuccessor);
1051         }
1052         GraphUtil.killCFG(merge);
1053 
1054         assert !merge.isAlive() : merge;
1055         assert !phi.isAlive() : phi;
1056         assert !compare.isAlive() : compare;
1057         assert !this.isAlive() : this;
1058 
1059         return true;
1060     }
1061 
1062     private void propagateZeroProbability(FixedNode startNode) {
1063         Node prev = null;
1064         for (FixedNode node : GraphUtil.predecessorIterable(startNode)) {
1065             if (node instanceof IfNode) {
1066                 IfNode ifNode = (IfNode) node;
1067                 if (ifNode.trueSuccessor() == prev) {
1068                     if (ifNode.trueSuccessorProbability == 0.0) {
1069                         return;
1070                     } else if (ifNode.trueSuccessorProbability == 1.0) {
1071                         continue;
1072                     } else {
1073                         ifNode.setTrueSuccessorProbability(0.0);
1074                         return;
1075                     }
1076                 } else if (ifNode.falseSuccessor() == prev) {
1077                     if (ifNode.trueSuccessorProbability == 1.0) {
1078                         return;
1079                     } else if (ifNode.trueSuccessorProbability == 0.0) {
1080                         continue;
1081                     } else {
1082                         ifNode.setTrueSuccessorProbability(1.0);
1083                         return;
1084                     }
1085                 } else {
1086                     throw new GraalError("Illegal state");
1087                 }
1088             } else if (node instanceof AbstractMergeNode && !(node instanceof LoopBeginNode)) {
1089                 for (AbstractEndNode endNode : ((AbstractMergeNode) node).cfgPredecessors()) {
1090                     propagateZeroProbability(endNode);
1091                 }
1092                 return;
1093             }
1094             prev = node;
1095         }
1096     }
1097 
1098     private static boolean checkFrameState(FixedNode start) {
1099         FixedNode node = start;
1100         while (true) {
1101             if (node instanceof AbstractMergeNode) {
1102                 AbstractMergeNode mergeNode = (AbstractMergeNode) node;
1103                 if (mergeNode.stateAfter() == null) {
1104                     return false;
1105                 } else {
1106                     return true;
1107                 }
1108             } else if (node instanceof StateSplit) {
1109                 StateSplit stateSplitNode = (StateSplit) node;
1110                 if (stateSplitNode.stateAfter() != null) {
1111                     return true;
1112                 }
1113             }
1114 
1115             if (node instanceof ControlSplitNode) {
1116                 ControlSplitNode controlSplitNode = (ControlSplitNode) node;
1117                 for (Node succ : controlSplitNode.cfgSuccessors()) {
1118                     if (checkFrameState((FixedNode) succ)) {
1119                         return true;
1120                     }
1121                 }
1122                 return false;
1123             } else if (node instanceof FixedWithNextNode) {
1124                 FixedWithNextNode fixedWithNextNode = (FixedWithNextNode) node;
1125                 node = fixedWithNextNode.next();
1126             } else if (node instanceof AbstractEndNode) {
1127                 AbstractEndNode endNode = (AbstractEndNode) node;
1128                 node = endNode.merge();
1129             } else if (node instanceof ControlSinkNode) {
1130                 return true;
1131             } else {
1132                 return false;
1133             }
1134         }
1135     }
1136 
1137     /**
1138      * Connects a set of ends to a given successor, inserting a merge node if there is more than one
1139      * end. If {@code ends} is not empty, then {@code successor} is added to {@code tool}'s
1140      * {@linkplain SimplifierTool#addToWorkList(org.graalvm.compiler.graph.Node) work list}.
1141      *
1142      * @param oldMerge the merge being removed
1143      * @param phiValues the values of the phi at the merge, keyed by the merge ends
1144      */
1145     private void connectEnds(List<EndNode> ends, EconomicMap<AbstractEndNode, ValueNode> phiValues, AbstractBeginNode successor, AbstractMergeNode oldMerge, SimplifierTool tool) {
1146         if (!ends.isEmpty()) {
1147             if (ends.size() == 1) {
1148                 AbstractEndNode end = ends.get(0);
1149                 ((FixedWithNextNode) end.predecessor()).setNext(successor);
1150                 oldMerge.removeEnd(end);
1151                 GraphUtil.killCFG(end);
1152             } else {
1153                 // Need a new phi in case the frame state is used by more than the merge being
1154                 // removed
1155                 AbstractMergeNode newMerge = graph().add(new MergeNode());
1156                 PhiNode oldPhi = (PhiNode) oldMerge.usages().first();
1157                 PhiNode newPhi = graph().addWithoutUnique(new ValuePhiNode(oldPhi.stamp(), newMerge));
1158 
1159                 for (EndNode end : ends) {
1160                     newPhi.addInput(phiValues.get(end));
1161                     newMerge.addForwardEnd(end);
1162                 }
1163 
1164                 FrameState stateAfter = oldMerge.stateAfter();
1165                 if (stateAfter != null) {
1166                     stateAfter = stateAfter.duplicate();
1167                     stateAfter.replaceFirstInput(oldPhi, newPhi);
1168                     newMerge.setStateAfter(stateAfter);
1169                 }
1170 
1171                 newMerge.setNext(successor);
1172             }
1173             tool.addToWorkList(successor);
1174         }
1175     }
1176 
1177     /**
1178      * Gets an array of constants derived from a node that is either a {@link ConstantNode} or a
1179      * {@link PhiNode} whose input values are all constants. The length of the returned array is
1180      * equal to the number of ends terminating in a given merge node.
1181      *
1182      * @return null if {@code node} is neither a {@link ConstantNode} nor a {@link PhiNode} whose
1183      *         input values are all constants
1184      */
1185     public static Constant[] constantValues(ValueNode node, AbstractMergeNode merge, boolean allowNull) {
1186         if (node.isConstant()) {
1187             Constant[] result = new Constant[merge.forwardEndCount()];
1188             Arrays.fill(result, node.asConstant());
1189             return result;
1190         }
1191 
1192         if (node instanceof PhiNode) {
1193             PhiNode phi = (PhiNode) node;
1194             if (phi.merge() == merge && phi instanceof ValuePhiNode && phi.valueCount() == merge.forwardEndCount()) {
1195                 Constant[] result = new Constant[merge.forwardEndCount()];
1196                 int i = 0;
1197                 for (ValueNode n : phi.values()) {
1198                     if (!allowNull && !n.isConstant()) {
1199                         return null;
1200                     }
1201                     result[i++] = n.asConstant();
1202                 }
1203                 return result;
1204             }
1205         }
1206 
1207         return null;
1208     }
1209 
1210     @Override
1211     public AbstractBeginNode getPrimarySuccessor() {
1212         return this.trueSuccessor();
1213     }
1214 
1215     public AbstractBeginNode getSuccessor(boolean result) {
1216         return result ? this.trueSuccessor() : this.falseSuccessor();
1217     }
1218 
1219     @Override
1220     public boolean setProbability(AbstractBeginNode successor, double value) {
1221         if (successor == this.trueSuccessor()) {
1222             this.setTrueSuccessorProbability(value);
1223             return true;
1224         } else if (successor == this.falseSuccessor()) {
1225             this.setTrueSuccessorProbability(1.0 - value);
1226             return true;
1227         }
1228         return false;
1229     }
1230 
1231     @Override
1232     public int getSuccessorCount() {
1233         return 2;
1234     }
1235 }