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