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