1/* 2 * Copyright (c) 2015, 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 */ 23package org.graalvm.compiler.api.directives.test; 24 25import org.graalvm.compiler.api.directives.GraalDirectives; 26import org.graalvm.compiler.core.test.GraalCompilerTest; 27import org.graalvm.compiler.graph.iterators.NodeIterable; 28import org.graalvm.compiler.nodes.AbstractBeginNode; 29import org.graalvm.compiler.nodes.IfNode; 30import org.graalvm.compiler.nodes.ReturnNode; 31import org.graalvm.compiler.nodes.StructuredGraph; 32import org.graalvm.compiler.nodes.debug.ControlFlowAnchorNode; 33import org.junit.Assert; 34import org.junit.Test; 35 36public class ProbabilityDirectiveTest extends GraalCompilerTest { 37 38 public static int branchProbabilitySnippet(int arg) { 39 if (GraalDirectives.injectBranchProbability(0.125, arg > 0)) { 40 GraalDirectives.controlFlowAnchor(); // prevent removal of the if 41 return 1; 42 } else { 43 GraalDirectives.controlFlowAnchor(); // prevent removal of the if 44 return 2; 45 } 46 } 47 48 @Test 49 public void testBranchProbability() { 50 test("branchProbabilitySnippet", 5); 51 } 52 53 @Override 54 protected boolean checkLowTierGraph(StructuredGraph graph) { 55 NodeIterable<IfNode> ifNodes = graph.getNodes(IfNode.TYPE); 56 Assert.assertEquals("IfNode count", 1, ifNodes.count()); 57 58 IfNode ifNode = ifNodes.first(); 59 AbstractBeginNode oneSuccessor; 60 if (returnValue(ifNode.trueSuccessor()) == 1) { 61 oneSuccessor = ifNode.trueSuccessor(); 62 } else { 63 assert returnValue(ifNode.falseSuccessor()) == 1; 64 oneSuccessor = ifNode.falseSuccessor(); 65 } 66 Assert.assertEquals("branch probability of " + ifNode, 0.125, ifNode.probability(oneSuccessor), 0); 67 68 return true; 69 } 70 71 private static int returnValue(AbstractBeginNode b) { 72 ControlFlowAnchorNode anchor = (ControlFlowAnchorNode) b.next(); 73 ReturnNode returnNode = (ReturnNode) anchor.next(); 74 return returnNode.result().asJavaConstant().asInt(); 75 } 76} 77