Ejemplo n.º 1
0
  /**
   * Inserts mark-locals if necessary when changing a register. If the definition of {@code origReg}
   * is associated with a local variable, then insert a mark-local for {@code newReg} just below it.
   * We expect the definition of {@code origReg} to ultimately be removed by the dead code
   * eliminator
   *
   * @param origReg {@code non-null;} original register
   * @param newReg {@code non-null;} new register that will replace {@code origReg}
   */
  private void fixLocalAssignment(RegisterSpec origReg, RegisterSpec newReg) {
    for (SsaInsn use : ssaMeth.getUseListForRegister(origReg.getReg())) {
      RegisterSpec localAssignment = use.getLocalAssignment();
      if (localAssignment == null) {
        continue;
      }

      if (use.getResult() == null) {
        /*
         * This is a mark-local. it will be updated when all uses are
         * updated.
         */
        continue;
      }

      LocalItem local = localAssignment.getLocalItem();

      // Un-associate original use.
      use.setResultLocal(null);

      // Now add a mark-local to the new reg immediately after.
      newReg = newReg.withLocalItem(local);

      SsaInsn newInsn =
          SsaInsn.makeFromRop(
              new PlainInsn(
                  Rops.opMarkLocal(newReg),
                  SourcePosition.NO_INFO,
                  null,
                  RegisterSpecList.make(newReg)),
              use.getBlock());

      ArrayList<SsaInsn> insns = use.getBlock().getInsns();

      insns.add(insns.indexOf(use) + 1, newInsn);
    }
  }
Ejemplo n.º 2
0
  /**
   * Processes a single block.
   *
   * @param blockIndex {@code >= 0;} block index of the block to process
   */
  private void processBlock(int blockIndex) {
    RegisterSpecSet primaryState = resultInfo.mutableCopyOfStarts(blockIndex);
    SsaBasicBlock block = blocks.get(blockIndex);
    List<SsaInsn> insns = block.getInsns();
    int insnSz = insns.size();

    // The exit block has no insns and no successors
    if (blockIndex == method.getExitBlockIndex()) {
      return;
    }

    /*
     * We may have to treat the last instruction specially: If it
     * can (but doesn't always) throw, and the exception can be
     * caught within the same method, then we need to use the
     * state *before* executing it to be what is merged into
     * exception targets.
     */
    SsaInsn lastInsn = insns.get(insnSz - 1);
    boolean hasExceptionHandlers = lastInsn.getOriginalRopInsn().getCatches().size() != 0;
    boolean canThrowDuringLastInsn = hasExceptionHandlers && (lastInsn.getResult() != null);
    int freezeSecondaryStateAt = insnSz - 1;
    RegisterSpecSet secondaryState = primaryState;

    /*
     * Iterate over the instructions, adding information for each place
     * that the active variable set changes.
     */

    for (int i = 0; i < insnSz; i++) {
      if (canThrowDuringLastInsn && (i == freezeSecondaryStateAt)) {
        // Until this point, primaryState == secondaryState.
        primaryState.setImmutable();
        primaryState = primaryState.mutableCopy();
      }

      SsaInsn insn = insns.get(i);
      RegisterSpec result;

      result = insn.getLocalAssignment();

      if (result == null) {
        // We may be nuking an existing local

        result = insn.getResult();

        if (result != null && primaryState.get(result.getReg()) != null) {
          primaryState.remove(primaryState.get(result.getReg()));
        }
        continue;
      }

      result = result.withSimpleType();

      RegisterSpec already = primaryState.get(result);
      /*
       * The equals() check ensures we only add new info if
       * the instruction causes a change to the set of
       * active variables.
       */
      if (!result.equals(already)) {
        /*
         * If this insn represents a local moving from one register
         * to another, remove the association between the old register
         * and the local.
         */
        RegisterSpec previous = primaryState.localItemToSpec(result.getLocalItem());

        if (previous != null && (previous.getReg() != result.getReg())) {

          primaryState.remove(previous);
        }

        resultInfo.addAssignment(insn, result);
        primaryState.put(result);
      }
    }

    primaryState.setImmutable();

    /*
     * Merge this state into the start state for each successor,
     * and update the work set where required (that is, in cases
     * where the start state for a block changes).
     */

    IntList successors = block.getSuccessorList();
    int succSz = successors.size();
    int primarySuccessor = block.getPrimarySuccessorIndex();

    for (int i = 0; i < succSz; i++) {
      int succ = successors.get(i);
      RegisterSpecSet state = (succ == primarySuccessor) ? primaryState : secondaryState;

      if (resultInfo.mergeStarts(succ, state)) {
        workSet.set(succ);
      }
    }
  }
Ejemplo n.º 3
0
  /**
   * Sorts move instructions added via {@code addMoveToEnd} during phi removal so that results don't
   * overwrite sources that are used. For use after all phis have been removed and all calls to
   * addMoveToEnd() have been made.
   *
   * <p>This is necessary because copy-propogation may have left us in a state where the same basic
   * block has the same register as a phi operand and a result. In this case, the register in the
   * phi operand always refers value before any other phis have executed.
   */
  public void scheduleMovesFromPhis() {
    if (movesFromPhisAtBeginning > 1) {
      List<SsaInsn> toSchedule;

      toSchedule = insns.subList(0, movesFromPhisAtBeginning);

      scheduleUseBeforeAssigned(toSchedule);

      SsaInsn firstNonPhiMoveInsn = insns.get(movesFromPhisAtBeginning);

      /*
       * TODO: It's actually possible that this case never happens,
       * because a move-exception block, having only one predecessor in
       * SSA form, perhaps is never on a dominance frontier.
       */
      if (firstNonPhiMoveInsn.isMoveException()) {
        if (true) {
          /*
           * We've yet to observe this case, and if it can occur the
           * code written to handle it probably does not work.
           */
          throw new RuntimeException("Unexpected: moves from " + "phis before move-exception");
        } else {
          /*
           * A move-exception insn must be placed first in this block
           * We need to move it there, and deal with possible
           * interference.
           */
          boolean moveExceptionInterferes = false;

          int moveExceptionResult = firstNonPhiMoveInsn.getResult().getReg();

          /*
           * Does the move-exception result reg interfere with the phi
           * moves?
           */
          for (SsaInsn insn : toSchedule) {
            if (insn.isResultReg(moveExceptionResult) || insn.isRegASource(moveExceptionResult)) {
              moveExceptionInterferes = true;
              break;
            }
          }

          if (!moveExceptionInterferes) {
            // This is the easy case.
            insns.remove(movesFromPhisAtBeginning);
            insns.add(0, firstNonPhiMoveInsn);
          } else {
            /*
             * We need to move the result to a spare reg and move it
             * back.
             */
            RegisterSpec originalResultSpec = firstNonPhiMoveInsn.getResult();
            int spareRegister = parent.borrowSpareRegister(originalResultSpec.getCategory());

            // We now move it to a spare register.
            firstNonPhiMoveInsn.changeResultReg(spareRegister);
            RegisterSpec tempSpec = firstNonPhiMoveInsn.getResult();

            insns.add(0, firstNonPhiMoveInsn);

            // And here we move it back.

            NormalSsaInsn toAdd =
                new NormalSsaInsn(
                    new PlainInsn(
                        Rops.opMove(tempSpec.getType()),
                        SourcePosition.NO_INFO,
                        originalResultSpec,
                        RegisterSpecList.make(tempSpec)),
                    this);

            /*
             * Place it immediately after the phi-moves, overwriting
             * the move-exception that was there.
             */
            insns.set(movesFromPhisAtBeginning + 1, toAdd);
          }
        }
      }
    }

    if (movesFromPhisAtEnd > 1) {
      scheduleUseBeforeAssigned(
          insns.subList(insns.size() - movesFromPhisAtEnd - 1, insns.size() - 1));
    }

    // Return registers borrowed here and in scheduleUseBeforeAssigned().
    parent.returnSpareRegisters();
  }
Ejemplo n.º 4
0
  /**
   * Ensures that all move operations in this block occur such that reads of any register happen
   * before writes to that register. NOTE: caller is expected to returnSpareRegisters()! TODO: See
   * Briggs, et al "Practical Improvements to the Construction and Destruction of Static Single
   * Assignment Form" section 5. a) This can be done in three passes.
   *
   * @param toSchedule List of instructions. Must consist only of moves.
   */
  private void scheduleUseBeforeAssigned(List<SsaInsn> toSchedule) {
    BitSet regsUsedAsSources = new BitSet(parent.getRegCount());

    // TODO: Get rid of this.
    BitSet regsUsedAsResults = new BitSet(parent.getRegCount());

    int sz = toSchedule.size();

    int insertPlace = 0;

    while (insertPlace < sz) {
      int oldInsertPlace = insertPlace;

      // Record all registers used as sources in this block.
      for (int i = insertPlace; i < sz; i++) {
        setRegsUsed(regsUsedAsSources, toSchedule.get(i).getSources().get(0));

        setRegsUsed(regsUsedAsResults, toSchedule.get(i).getResult());
      }

      /*
       * If there are no circular dependencies, then there exists n
       * instructions where n > 1 whose result is not used as a source.
       */
      for (int i = insertPlace; i < sz; i++) {
        SsaInsn insn = toSchedule.get(i);

        /*
         * Move these n registers to the front, since they overwrite
         * nothing.
         */
        if (!checkRegUsed(regsUsedAsSources, insn.getResult())) {
          Collections.swap(toSchedule, i, insertPlace++);
        }
      }

      /*
       * If we've made no progress in this iteration, there's a circular
       * dependency. Split it using the temp reg.
       */
      if (oldInsertPlace == insertPlace) {

        SsaInsn insnToSplit = null;

        // Find an insn whose result is used as a source.
        for (int i = insertPlace; i < sz; i++) {
          SsaInsn insn = toSchedule.get(i);
          if (checkRegUsed(regsUsedAsSources, insn.getResult())
              && checkRegUsed(regsUsedAsResults, insn.getSources().get(0))) {

            insnToSplit = insn;
            /*
             * We're going to split this insn; move it to the front.
             */
            Collections.swap(toSchedule, insertPlace, i);
            break;
          }
        }

        // At least one insn will be set above.

        RegisterSpec result = insnToSplit.getResult();
        RegisterSpec tempSpec = result.withReg(parent.borrowSpareRegister(result.getCategory()));

        NormalSsaInsn toAdd =
            new NormalSsaInsn(
                new PlainInsn(
                    Rops.opMove(result.getType()),
                    SourcePosition.NO_INFO,
                    tempSpec,
                    insnToSplit.getSources()),
                this);

        toSchedule.add(insertPlace++, toAdd);

        RegisterSpecList newSources = RegisterSpecList.make(tempSpec);

        NormalSsaInsn toReplace =
            new NormalSsaInsn(
                new PlainInsn(
                    Rops.opMove(result.getType()), SourcePosition.NO_INFO, result, newSources),
                this);

        toSchedule.set(insertPlace, toReplace);

        // The size changed.
        sz = toSchedule.size();
      }

      regsUsedAsSources.clear();
      regsUsedAsResults.clear();
    }
  }
Ejemplo n.º 5
0
  /**
   * Updates all uses of various consts to use the values in the newly assigned registers.
   *
   * @param newRegs {@code non-null;} mapping between constant and new reg
   * @param origRegCount {@code >=0;} original SSA reg count, not including newly added constant
   *     regs
   */
  private void updateConstUses(HashMap<TypedConstant, RegisterSpec> newRegs, int origRegCount) {

    /*
     * set of constants associated with a local variable; used only if
     * COLLECT_ONE_LOCAL is true.
     */
    final HashSet<TypedConstant> usedByLocal = new HashSet<TypedConstant>();

    final ArrayList<SsaInsn>[] useList = ssaMeth.getUseListCopy();

    for (int i = 0; i < origRegCount; i++) {
      SsaInsn insn = ssaMeth.getDefinitionForRegister(i);

      if (insn == null) {
        continue;
      }

      final RegisterSpec origReg = insn.getResult();
      TypeBearer typeBearer = insn.getResult().getTypeBearer();

      if (!typeBearer.isConstant()) continue;

      TypedConstant cst = (TypedConstant) typeBearer;
      final RegisterSpec newReg = newRegs.get(cst);

      if (newReg == null) {
        continue;
      }

      if (ssaMeth.isRegALocal(origReg)) {
        if (!COLLECT_ONE_LOCAL) {
          continue;
        } else {
          /*
           * TODO: If the same local gets the same cst multiple times,
           * it would be nice to reuse the register.
           */
          if (usedByLocal.contains(cst)) {
            continue;
          } else {
            usedByLocal.add(cst);
            fixLocalAssignment(origReg, newRegs.get(cst));
          }
        }
      }

      // maps an original const register to the new collected register
      RegisterMapper mapper =
          new RegisterMapper() {

            @Override
            public int getNewRegisterCount() {
              return ssaMeth.getRegCount();
            }

            @Override
            public RegisterSpec map(RegisterSpec registerSpec) {
              if (registerSpec.getReg() == origReg.getReg()) {
                return newReg.withLocalItem(registerSpec.getLocalItem());
              }

              return registerSpec;
            }
          };

      for (SsaInsn use : useList[origReg.getReg()]) {
        if (use.canThrow() && use.getBlock().getSuccessors().cardinality() > 1) {
          continue;
        }
        use.mapSourceRegisters(mapper);
      }
    }
  }
Ejemplo n.º 6
0
  /**
   * Gets all of the collectable constant values used in this method, sorted by most used first.
   * Skips non-collectable consts, such as non-string object constants
   *
   * @return {@code non-null;} list of constants in most-to-least used order
   */
  private ArrayList<TypedConstant> getConstsSortedByCountUse() {
    int regSz = ssaMeth.getRegCount();

    final HashMap<TypedConstant, Integer> countUses = new HashMap<TypedConstant, Integer>();

    /*
     * Each collected constant can be used by just one local (used only if
     * COLLECT_ONE_LOCAL is true).
     */
    final HashSet<TypedConstant> usedByLocal = new HashSet<TypedConstant>();

    // Count how many times each const value is used.
    for (int i = 0; i < regSz; i++) {
      SsaInsn insn = ssaMeth.getDefinitionForRegister(i);

      if (insn == null || insn.getOpcode() == null) continue;

      RegisterSpec result = insn.getResult();
      TypeBearer typeBearer = result.getTypeBearer();

      if (!typeBearer.isConstant()) continue;

      TypedConstant cst = (TypedConstant) typeBearer;

      // Find defining instruction for move-result-pseudo instructions
      if (insn.getOpcode().getOpcode() == RegOps.MOVE_RESULT_PSEUDO) {
        int pred = insn.getBlock().getPredecessors().nextSetBit(0);
        ArrayList<SsaInsn> predInsns;
        predInsns = ssaMeth.getBlocks().get(pred).getInsns();
        insn = predInsns.get(predInsns.size() - 1);
      }

      if (insn.canThrow()) {
        /*
         * Don't move anything other than strings -- the risk of
         * changing where an exception is thrown is too high.
         */
        if (!(cst instanceof CstString) || !COLLECT_STRINGS) {
          continue;
        }
        /*
         * We can't move any throwable const whose throw will be caught,
         * so don't count them.
         */
        if (insn.getBlock().getSuccessors().cardinality() > 1) {
          continue;
        }
      }

      /*
       * TODO: Might be nice to try and figure out which local wins most
       * when collected.
       */
      if (ssaMeth.isRegALocal(result)) {
        if (!COLLECT_ONE_LOCAL) {
          continue;
        } else {
          if (usedByLocal.contains(cst)) {
            // Count one local usage only.
            continue;
          } else {
            usedByLocal.add(cst);
          }
        }
      }

      Integer has = countUses.get(cst);
      if (has == null) {
        countUses.put(cst, 1);
      } else {
        countUses.put(cst, has + 1);
      }
    }

    // Collect constants that have been reused.
    ArrayList<TypedConstant> constantList = new ArrayList<TypedConstant>();
    for (Map.Entry<TypedConstant, Integer> entry : countUses.entrySet()) {
      if (entry.getValue() > 1) {
        constantList.add(entry.getKey());
      }
    }

    // Sort by use, with most used at the beginning of the list.
    Collections.sort(
        constantList,
        new Comparator<Constant>() {

          public int compare(Constant a, Constant b) {
            int ret;
            ret = countUses.get(b) - countUses.get(a);

            if (ret == 0) {
              /*
               * Provide sorting determinisim for constants with same
               * usage count.
               */
              ret = a.compareTo(b);
            }

            return ret;
          }

          @Override
          public boolean equals(Object obj) {
            return obj == this;
          }
        });

    return constantList;
  }