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 */ 23 package org.graalvm.compiler.lir.alloc.trace.lsra; 24 25 import static jdk.vm.ci.code.ValueUtil.isRegister; 26 import static org.graalvm.compiler.core.common.GraalOptions.DetailedAsserts; 27 import static org.graalvm.compiler.lir.LIRValueUtil.isStackSlotValue; 28 import static org.graalvm.compiler.lir.LIRValueUtil.isVariable; 29 30 import java.util.ArrayList; 31 32 import org.graalvm.compiler.core.common.alloc.Trace; 33 import org.graalvm.compiler.core.common.alloc.TraceBuilderResult; 34 import org.graalvm.compiler.core.common.cfg.AbstractBlockBase; 35 import org.graalvm.compiler.debug.Debug; 36 import org.graalvm.compiler.debug.Indent; 37 import org.graalvm.compiler.lir.LIRInsertionBuffer; 38 import org.graalvm.compiler.lir.LIRInstruction; 39 import org.graalvm.compiler.lir.LIRInstruction.OperandMode; 40 import org.graalvm.compiler.lir.StandardOp.LoadConstantOp; 41 import org.graalvm.compiler.lir.StandardOp.MoveOp; 42 import org.graalvm.compiler.lir.StandardOp.ValueMoveOp; 43 import org.graalvm.compiler.lir.alloc.trace.lsra.TraceInterval.SpillState; 44 import org.graalvm.compiler.lir.alloc.trace.lsra.TraceLinearScanPhase.IntervalPredicate; 45 import org.graalvm.compiler.lir.alloc.trace.lsra.TraceLinearScanPhase.TraceLinearScan; 46 import org.graalvm.compiler.lir.gen.LIRGenerationResult; 47 48 import jdk.vm.ci.code.TargetDescription; 49 import jdk.vm.ci.meta.AllocatableValue; 50 51 final class TraceLinearScanEliminateSpillMovePhase extends TraceLinearScanAllocationPhase { 52 53 private static final IntervalPredicate spilledIntervals = new TraceLinearScanPhase.IntervalPredicate() { 54 55 @Override 56 public boolean apply(TraceInterval i) { 57 return i.isSplitParent() && SpillState.IN_MEMORY.contains(i.spillState()); 58 } 59 }; 60 61 @Override 62 protected void run(TargetDescription target, LIRGenerationResult lirGenRes, Trace trace, TraceLinearScanAllocationContext context) { 63 TraceBuilderResult traceBuilderResult = context.resultTraces; 64 TraceLinearScan allocator = context.allocator; 65 boolean shouldEliminateSpillMoves = shouldEliminateSpillMoves(traceBuilderResult, allocator); 66 eliminateSpillMoves(allocator, shouldEliminateSpillMoves, traceBuilderResult); 67 } 68 69 private static boolean shouldEliminateSpillMoves(TraceBuilderResult traceBuilderResult, TraceLinearScan allocator) { 70 return !traceBuilderResult.incomingSideEdges(traceBuilderResult.getTraceForBlock(allocator.blockAt(0))); 71 } 72 73 // called once before assignment of register numbers 74 @SuppressWarnings("try") 75 private static void eliminateSpillMoves(TraceLinearScan allocator, boolean shouldEliminateSpillMoves, TraceBuilderResult traceBuilderResult) { 76 try (Indent indent = Debug.logAndIndent("Eliminating unnecessary spill moves: Trace%d", traceBuilderResult.getTraceForBlock(allocator.blockAt(0)).getId())) { 77 allocator.sortIntervalsBySpillPos(); 78 79 /* 80 * collect all intervals that must be stored after their definition. The list is sorted 81 * by Interval.spillDefinitionPos. 82 */ 83 TraceInterval interval = allocator.createUnhandledListBySpillPos(spilledIntervals); 84 if (DetailedAsserts.getValue(allocator.getOptions())) { 85 checkIntervals(interval); 86 } 87 if (Debug.isLogEnabled()) { 88 try (Indent indent2 = Debug.logAndIndent("Sorted intervals")) { 89 for (TraceInterval i = interval; i != null; i = i.next) { 90 Debug.log("%5d: %s", i.spillDefinitionPos(), i); 91 } 92 } 93 } 94 95 LIRInsertionBuffer insertionBuffer = new LIRInsertionBuffer(); 96 for (AbstractBlockBase<?> block : allocator.sortedBlocks()) { 97 try (Indent indent1 = Debug.logAndIndent("Handle %s", block)) { 98 ArrayList<LIRInstruction> instructions = allocator.getLIR().getLIRforBlock(block); 99 int numInst = instructions.size(); 100 101 int lastOpId = -1; 102 // iterate all instructions of the block. 103 for (int j = 0; j < numInst; j++) { 104 LIRInstruction op = instructions.get(j); 105 int opId = op.id(); 106 try (Indent indent2 = Debug.logAndIndent("%5d %s", opId, op)) { 107 108 if (opId == -1) { 109 MoveOp move = (MoveOp) op; 110 /* 111 * Remove move from register to stack if the stack slot is 112 * guaranteed to be correct. Only moves that have been inserted by 113 * LinearScan can be removed. 114 */ 115 if (shouldEliminateSpillMoves && canEliminateSpillMove(allocator, block, move, lastOpId)) { 116 /* 117 * Move target is a stack slot that is always correct, so 118 * eliminate instruction. 119 */ 120 if (Debug.isLogEnabled()) { 121 if (move instanceof ValueMoveOp) { 122 ValueMoveOp vmove = (ValueMoveOp) move; 123 Debug.log("eliminating move from interval %d (%s) to %d (%s) in block %s", allocator.operandNumber(vmove.getInput()), vmove.getInput(), 124 allocator.operandNumber(vmove.getResult()), vmove.getResult(), block); 125 } else { 126 LoadConstantOp load = (LoadConstantOp) move; 127 Debug.log("eliminating constant load from %s to %d (%s) in block %s", load.getConstant(), allocator.operandNumber(load.getResult()), load.getResult(), 128 block); 129 } 130 } 131 132 // null-instructions are deleted by assignRegNum 133 instructions.set(j, null); 134 } 135 136 } else { 137 lastOpId = opId; 138 /* 139 * Insert move from register to stack just after the beginning of 140 * the interval. 141 */ 142 // assert interval == TraceInterval.EndMarker || 143 // interval.spillDefinitionPos() >= opId : "invalid order"; 144 assert interval == TraceInterval.EndMarker || (interval.isSplitParent() && SpillState.IN_MEMORY.contains(interval.spillState())) : "invalid interval"; 145 146 while (interval != TraceInterval.EndMarker && interval.spillDefinitionPos() == opId) { 147 Debug.log("handle %s", interval); 148 if (!interval.canMaterialize() && interval.spillState() != SpillState.StartInMemory) { 149 150 AllocatableValue fromLocation = interval.getSplitChildAtOpId(opId, OperandMode.DEF).location(); 151 AllocatableValue toLocation = allocator.canonicalSpillOpr(interval); 152 if (!fromLocation.equals(toLocation)) { 153 154 if (!insertionBuffer.initialized()) { 155 /* 156 * prepare insertion buffer (appended when all 157 * instructions in the block are processed) 158 */ 159 insertionBuffer.init(instructions); 160 } 161 162 assert isRegister(fromLocation) : "from operand must be a register but is: " + fromLocation + " toLocation=" + toLocation + " spillState=" + 163 interval.spillState(); 164 assert isStackSlotValue(toLocation) : "to operand must be a stack slot"; 165 166 LIRInstruction move = allocator.getSpillMoveFactory().createMove(toLocation, fromLocation); 167 insertionBuffer.append(j + 1, move); 168 169 if (Debug.isLogEnabled()) { 170 Debug.log("inserting move after definition of interval %d to stack slot %s at opId %d", interval.operandNumber, interval.spillSlot(), opId); 171 } 172 } 173 } 174 interval = interval.next; 175 } 176 } 177 } 178 } // end of instruction iteration 179 180 if (insertionBuffer.initialized()) { 181 insertionBuffer.finish(); 182 } 183 } 184 } // end of block iteration 185 186 assert interval == TraceInterval.EndMarker : "missed an interval"; 187 } 188 } 189 190 /** 191 * @param allocator 192 * @param block The block {@code move} is located in. 193 * @param move Spill move. 194 * @param lastOpId The id of last "normal" instruction before the spill move. (Spill moves have 195 * no valid opId but -1.) 196 */ 197 private static boolean canEliminateSpillMove(TraceLinearScan allocator, AbstractBlockBase<?> block, MoveOp move, int lastOpId) { 198 assert ((LIRInstruction) move).id() == -1 : "Not a spill move: " + move; 199 assert isVariable(move.getResult()) : "LinearScan inserts only moves to variables: " + move; 200 assert lastOpId >= 0 : "Invalid lastOpId: " + lastOpId; 201 202 TraceInterval curInterval = allocator.intervalFor(move.getResult()); 203 204 if (!isRegister(curInterval.location()) && curInterval.inMemoryAt(lastOpId) && !isPhiResolutionMove(allocator, move)) { 205 /* Phi resolution moves cannot be removed because they define the value. */ 206 // TODO (je) check if the comment is still valid! 207 assert isStackSlotValue(curInterval.location()) : "Not a stack slot: " + curInterval.location(); 208 return true; 209 } 210 return false; 211 } 212 213 /** 214 * Checks if a (spill or split) move is a Phi resolution move. 215 * 216 * A spill or split move connects a split parent or a split child with another split child. 217 * Therefore the destination of the move is always a split child. Phi resolution moves look like 218 * spill moves (i.e. {@link LIRInstruction#id() id} is {@code 0}, but they define a new 219 * variable. As a result the destination interval is a split parent. 220 */ 221 private static boolean isPhiResolutionMove(TraceLinearScan allocator, MoveOp move) { 222 assert ((LIRInstruction) move).id() == -1 : "Not a spill move: " + move; 223 TraceInterval curInterval = allocator.intervalFor(move.getResult()); 224 return curInterval.isSplitParent(); 225 } 226 227 private static void checkIntervals(TraceInterval interval) { 228 TraceInterval prev = null; 229 TraceInterval temp = interval; 230 while (temp != TraceInterval.EndMarker) { 231 assert temp.spillDefinitionPos() >= 0 : "invalid spill definition pos " + temp; 232 if (prev != null) { 233 // assert temp.from() >= prev.from() : "intervals not sorted"; 234 assert temp.spillDefinitionPos() >= prev.spillDefinitionPos() : "when intervals are sorted by from : then they must also be sorted by spillDefinitionPos"; 235 } 236 237 assert temp.spillSlot() != null || temp.canMaterialize() : "interval has no spill slot assigned"; 238 assert temp.spillDefinitionPos() >= temp.from() : "invalid order"; 239 // assert temp.spillDefinitionPos() <= temp.from() + 2 : 240 // "only intervals defined once at their start-pos can be optimized"; 241 242 if (Debug.isLogEnabled()) { 243 Debug.log("interval %d (from %d to %d) must be stored at %d", temp.operandNumber, temp.from(), temp.to(), temp.spillDefinitionPos()); 244 } 245 246 prev = temp; 247 temp = temp.next; 248 } 249 } 250 251 }