1 /* 2 * Copyright (c) 2015, 2016, 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.loop; 24 25 import org.graalvm.compiler.core.common.type.IntegerStamp; 26 import org.graalvm.compiler.nodes.FixedNode; 27 import org.graalvm.compiler.nodes.StructuredGraph; 28 import org.graalvm.compiler.nodes.ValueNode; 29 import org.graalvm.compiler.nodes.calc.BinaryArithmeticNode; 30 import org.graalvm.compiler.nodes.calc.SignedDivNode; 31 32 /** 33 * Utility methods to perform integer math with some obvious constant folding first. 34 */ 35 public class MathUtil { 36 private static boolean isConstantOne(ValueNode v1) { 37 return v1.isConstant() && v1.stamp() instanceof IntegerStamp && v1.asJavaConstant().asLong() == 1; 38 } 39 40 private static boolean isConstantZero(ValueNode v1) { 41 return v1.isConstant() && v1.stamp() instanceof IntegerStamp && v1.asJavaConstant().asLong() == 0; 42 } 43 44 public static ValueNode add(StructuredGraph graph, ValueNode v1, ValueNode v2) { 45 if (isConstantZero(v1)) { 46 return v2; 47 } 48 if (isConstantZero(v2)) { 49 return v1; 50 } 51 return BinaryArithmeticNode.add(graph, v1, v2); 52 } 53 54 public static ValueNode mul(StructuredGraph graph, ValueNode v1, ValueNode v2) { 55 if (isConstantOne(v1)) { 56 return v2; 57 } 58 if (isConstantOne(v2)) { 59 return v1; 60 } 61 return BinaryArithmeticNode.mul(graph, v1, v2); 62 } 63 64 public static ValueNode sub(StructuredGraph graph, ValueNode v1, ValueNode v2) { 65 if (isConstantZero(v2)) { 66 return v1; 67 } 68 return BinaryArithmeticNode.sub(graph, v1, v2); 69 } 70 71 public static ValueNode divBefore(StructuredGraph graph, FixedNode before, ValueNode dividend, ValueNode divisor) { 72 if (isConstantOne(divisor)) { 73 return dividend; 74 } 75 SignedDivNode div = graph.add(new SignedDivNode(dividend, divisor)); 76 graph.addBeforeFixed(before, div); 77 return div; 78 } 79 }