1 /*
   2  * Copyright (c) 2009, 2014, 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.calc;
  24 
  25 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_1;
  26 import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_1;
  27 
  28 import java.io.Serializable;
  29 import java.util.function.Function;
  30 
  31 import org.graalvm.compiler.core.common.type.ArithmeticOpTable;
  32 import org.graalvm.compiler.core.common.type.ArithmeticOpTable.BinaryOp;
  33 import org.graalvm.compiler.core.common.type.Stamp;
  34 import org.graalvm.compiler.debug.GraalError;
  35 import org.graalvm.compiler.graph.Graph;
  36 import org.graalvm.compiler.graph.Node;
  37 import org.graalvm.compiler.graph.NodeClass;
  38 import org.graalvm.compiler.graph.iterators.NodePredicate;
  39 import org.graalvm.compiler.graph.spi.Canonicalizable;
  40 import org.graalvm.compiler.graph.spi.CanonicalizerTool;
  41 import org.graalvm.compiler.nodeinfo.NodeInfo;
  42 import org.graalvm.compiler.nodes.ArithmeticOperation;
  43 import org.graalvm.compiler.nodes.ConstantNode;
  44 import org.graalvm.compiler.nodes.StructuredGraph;
  45 import org.graalvm.compiler.nodes.ValueNode;
  46 import org.graalvm.compiler.nodes.ValuePhiNode;
  47 import org.graalvm.compiler.nodes.spi.ArithmeticLIRLowerable;
  48 import org.graalvm.compiler.nodes.spi.NodeValueMap;
  49 
  50 import jdk.vm.ci.meta.Constant;
  51 
  52 @NodeInfo(cycles = CYCLES_1, size = SIZE_1)
  53 public abstract class BinaryArithmeticNode<OP> extends BinaryNode implements ArithmeticOperation, ArithmeticLIRLowerable, Canonicalizable.Binary<ValueNode> {
  54 
  55     @SuppressWarnings("rawtypes") public static final NodeClass<BinaryArithmeticNode> TYPE = NodeClass.create(BinaryArithmeticNode.class);
  56 
  57     protected interface SerializableBinaryFunction<T> extends Function<ArithmeticOpTable, BinaryOp<T>>, Serializable {
  58     }
  59 
  60     protected final SerializableBinaryFunction<OP> getOp;
  61 
  62     protected BinaryArithmeticNode(NodeClass<? extends BinaryArithmeticNode<OP>> c, SerializableBinaryFunction<OP> getOp, ValueNode x, ValueNode y) {
  63         super(c, getOp.apply(ArithmeticOpTable.forStamp(x.stamp())).foldStamp(x.stamp(), y.stamp()), x, y);
  64         this.getOp = getOp;
  65     }
  66 
  67     protected final BinaryOp<OP> getOp(ValueNode forX, ValueNode forY) {
  68         ArithmeticOpTable table = ArithmeticOpTable.forStamp(forX.stamp());
  69         assert table.equals(ArithmeticOpTable.forStamp(forY.stamp()));
  70         return getOp.apply(table);
  71     }
  72 
  73     @Override
  74     public final BinaryOp<OP> getArithmeticOp() {
  75         return getOp(getX(), getY());
  76     }
  77 
  78     public boolean isAssociative() {
  79         return getArithmeticOp().isAssociative();
  80     }
  81 
  82     @Override
  83     public ValueNode canonical(CanonicalizerTool tool, ValueNode forX, ValueNode forY) {
  84         ValueNode result = tryConstantFold(getOp(forX, forY), forX, forY, stamp());
  85         if (result != null) {
  86             return result;
  87         }
  88         return this;
  89     }
  90 
  91     public static <OP> ConstantNode tryConstantFold(BinaryOp<OP> op, ValueNode forX, ValueNode forY, Stamp stamp) {
  92         if (forX.isConstant() && forY.isConstant()) {
  93             Constant ret = op.foldConstant(forX.asConstant(), forY.asConstant());
  94             return ConstantNode.forPrimitive(stamp, ret);
  95         }
  96         return null;
  97     }
  98 
  99     @Override
 100     public Stamp foldStamp(Stamp stampX, Stamp stampY) {
 101         assert stampX.isCompatible(x.stamp()) && stampY.isCompatible(y.stamp());
 102         return getArithmeticOp().foldStamp(stampX, stampY);
 103     }
 104 
 105     public static AddNode add(StructuredGraph graph, ValueNode v1, ValueNode v2) {
 106         return graph.unique(new AddNode(v1, v2));
 107     }
 108 
 109     public static AddNode add(ValueNode v1, ValueNode v2) {
 110         return new AddNode(v1, v2);
 111     }
 112 
 113     public static MulNode mul(StructuredGraph graph, ValueNode v1, ValueNode v2) {
 114         return graph.unique(new MulNode(v1, v2));
 115     }
 116 
 117     public static MulNode mul(ValueNode v1, ValueNode v2) {
 118         return new MulNode(v1, v2);
 119     }
 120 
 121     public static SubNode sub(StructuredGraph graph, ValueNode v1, ValueNode v2) {
 122         return graph.unique(new SubNode(v1, v2));
 123     }
 124 
 125     public static SubNode sub(ValueNode v1, ValueNode v2) {
 126         return new SubNode(v1, v2);
 127     }
 128 
 129     private enum ReassociateMatch {
 130         x,
 131         y;
 132 
 133         public ValueNode getValue(BinaryNode binary) {
 134             switch (this) {
 135                 case x:
 136                     return binary.getX();
 137                 case y:
 138                     return binary.getY();
 139                 default:
 140                     throw GraalError.shouldNotReachHere();
 141             }
 142         }
 143 
 144         public ValueNode getOtherValue(BinaryNode binary) {
 145             switch (this) {
 146                 case x:
 147                     return binary.getY();
 148                 case y:
 149                     return binary.getX();
 150                 default:
 151                     throw GraalError.shouldNotReachHere();
 152             }
 153         }
 154     }
 155 
 156     private static ReassociateMatch findReassociate(BinaryNode binary, NodePredicate criterion) {
 157         boolean resultX = criterion.apply(binary.getX());
 158         boolean resultY = criterion.apply(binary.getY());
 159         if (resultX && !resultY) {
 160             return ReassociateMatch.x;
 161         }
 162         if (!resultX && resultY) {
 163             return ReassociateMatch.y;
 164         }
 165         return null;
 166     }
 167 
 168     //@formatter:off
 169     /*
 170      * In reassociate, complexity comes from the handling of IntegerSub (non commutative) which can
 171      * be mixed with IntegerAdd. It first tries to find m1, m2 which match the criterion :
 172      * (a o m2) o m1
 173      * (m2 o a) o m1
 174      * m1 o (a o m2)
 175      * m1 o (m2 o a)
 176      * It then produces 4 boolean for the -/+ cases:
 177      * invertA : should the final expression be like *-a (rather than a+*)
 178      * aSub : should the final expression be like a-* (rather than a+*)
 179      * invertM1 : should the final expression contain -m1
 180      * invertM2 : should the final expression contain -m2
 181      *
 182      */
 183     //@formatter:on
 184     /**
 185      * Tries to re-associate values which satisfy the criterion. For example with a constantness
 186      * criterion: {@code (a + 2) + 1 => a + (1 + 2)}
 187      * <p>
 188      * This method accepts only {@linkplain BinaryOp#isAssociative() associative} operations such as
 189      * +, -, *, &amp;, | and ^
 190      *
 191      * @param forY
 192      * @param forX
 193      */
 194     public static BinaryArithmeticNode<?> reassociate(BinaryArithmeticNode<?> node, NodePredicate criterion, ValueNode forX, ValueNode forY) {
 195         assert node.getOp(forX, forY).isAssociative();
 196         ReassociateMatch match1 = findReassociate(node, criterion);
 197         if (match1 == null) {
 198             return node;
 199         }
 200         ValueNode otherValue = match1.getOtherValue(node);
 201         boolean addSub = false;
 202         boolean subAdd = false;
 203         if (otherValue.getClass() != node.getClass()) {
 204             if (node instanceof AddNode && otherValue instanceof SubNode) {
 205                 addSub = true;
 206             } else if (node instanceof SubNode && otherValue instanceof AddNode) {
 207                 subAdd = true;
 208             } else {
 209                 return node;
 210             }
 211         }
 212         BinaryNode other = (BinaryNode) otherValue;
 213         ReassociateMatch match2 = findReassociate(other, criterion);
 214         if (match2 == null) {
 215             return node;
 216         }
 217         boolean invertA = false;
 218         boolean aSub = false;
 219         boolean invertM1 = false;
 220         boolean invertM2 = false;
 221         if (addSub) {
 222             invertM2 = match2 == ReassociateMatch.y;
 223             invertA = !invertM2;
 224         } else if (subAdd) {
 225             invertA = invertM2 = match1 == ReassociateMatch.x;
 226             invertM1 = !invertM2;
 227         } else if (node instanceof SubNode && other instanceof SubNode) {
 228             invertA = match1 == ReassociateMatch.x ^ match2 == ReassociateMatch.x;
 229             aSub = match1 == ReassociateMatch.y && match2 == ReassociateMatch.y;
 230             invertM1 = match1 == ReassociateMatch.y && match2 == ReassociateMatch.x;
 231             invertM2 = match1 == ReassociateMatch.x && match2 == ReassociateMatch.x;
 232         }
 233         assert !(invertM1 && invertM2) && !(invertA && aSub);
 234         ValueNode m1 = match1.getValue(node);
 235         ValueNode m2 = match2.getValue(other);
 236         ValueNode a = match2.getOtherValue(other);
 237         if (node instanceof AddNode || node instanceof SubNode) {
 238             BinaryNode associated;
 239             if (invertM1) {
 240                 associated = BinaryArithmeticNode.sub(m2, m1);
 241             } else if (invertM2) {
 242                 associated = BinaryArithmeticNode.sub(m1, m2);
 243             } else {
 244                 associated = BinaryArithmeticNode.add(m1, m2);
 245             }
 246             if (invertA) {
 247                 return BinaryArithmeticNode.sub(associated, a);
 248             }
 249             if (aSub) {
 250                 return BinaryArithmeticNode.sub(a, associated);
 251             }
 252             return BinaryArithmeticNode.add(a, associated);
 253         } else if (node instanceof MulNode) {
 254             return BinaryArithmeticNode.mul(a, AddNode.mul(m1, m2));
 255         } else if (node instanceof AndNode) {
 256             return new AndNode(a, new AndNode(m1, m2));
 257         } else if (node instanceof OrNode) {
 258             return new OrNode(a, new OrNode(m1, m2));
 259         } else if (node instanceof XorNode) {
 260             return new XorNode(a, new XorNode(m1, m2));
 261         } else {
 262             throw GraalError.shouldNotReachHere();
 263         }
 264     }
 265 
 266     /**
 267      * Ensure a canonical ordering of inputs for commutative nodes to improve GVN results. Order the
 268      * inputs by increasing {@link Node#id} and call {@link Graph#findDuplicate(Node)} on the node
 269      * if it's currently in a graph. It's assumed that if there was a constant on the left it's been
 270      * moved to the right by other code and that ordering is left alone.
 271      *
 272      * @return the original node or another node with the same input ordering
 273      */
 274     @SuppressWarnings("deprecation")
 275     public BinaryNode maybeCommuteInputs() {
 276         assert this instanceof BinaryCommutative;
 277         if (!y.isConstant() && x.getId() > y.getId()) {
 278             ValueNode tmp = x;
 279             x = y;
 280             y = tmp;
 281             if (graph() != null) {
 282                 // See if this node already exists
 283                 BinaryNode duplicate = graph().findDuplicate(this);
 284                 if (duplicate != null) {
 285                     return duplicate;
 286                 }
 287             }
 288         }
 289         return this;
 290     }
 291 
 292     /**
 293      * Determines if it would be better to swap the inputs in order to produce better assembly code.
 294      * First we try to pick a value which is dead after this use. If both values are dead at this
 295      * use then we try pick an induction variable phi to encourage the phi to live in a single
 296      * register.
 297      *
 298      * @param nodeValueMap
 299      * @return true if inputs should be swapped, false otherwise
 300      */
 301     protected boolean shouldSwapInputs(NodeValueMap nodeValueMap) {
 302         final boolean xHasOtherUsages = getX().hasUsagesOtherThan(this, nodeValueMap);
 303         final boolean yHasOtherUsages = getY().hasUsagesOtherThan(this, nodeValueMap);
 304 
 305         if (!getY().isConstant() && !yHasOtherUsages) {
 306             if (xHasOtherUsages == yHasOtherUsages) {
 307                 return getY() instanceof ValuePhiNode && getY().inputs().contains(this);
 308             } else {
 309                 return true;
 310             }
 311         }
 312         return false;
 313     }
 314 
 315 }