/** Find non-locals variables. Algorithm from Briggs, Cooper, Harvey and Simpson */
  public BitSet findNonLocals() {
    BitSet nonLocals = new BitSet(nbVar);
    BitSet killed = new BitSet(nbVar);
    BitSet emptySet = new BitSet(nbVar);
    for (BasicBlock bb = firstBB; bb != null; bb = bb.getNext()) {
      // clear killed set
      killed.and(emptySet);

      Iterator insts = bb.getInstructions();
      while (insts.hasNext()) {
        QInst inst = (QInst) insts.next();
        QOperandBox[] ops = inst.getUses();
        for (int i = 0; i < ops.length; ++i) {
          QOperand op = ops[i].getOperand();
          if (op instanceof QVar) {
            int r = ((QVar) op).getRegister();
            if (!killed.get(r)) {
              nonLocals.set(r);
            }
          }
        }
        if (inst.defVar()) {
          QOperand op = inst.getDefined().getOperand();
          if (op instanceof QVar) {
            int r = ((QVar) op).getRegister();
            killed.set(r);
          }
        }
      }
    }
    return nonLocals;
  }
  public void writeInline(EmitContext emitContext, InstructionAdapter mv) {

    // Last check for assumption violations
    types.verifyFunctionAssumptions(runtimeState);

    Label exitLabel = new Label();

    for (BasicBlock basicBlock : cfg.getBasicBlocks()) {
      if (basicBlock != cfg.getEntry() && basicBlock != cfg.getExit()) {
        for (IRLabel label : basicBlock.getLabels()) {
          mv.visitLabel(emitContext.getAsmLabel(label));
        }
        for (Statement stmt : basicBlock.getStatements()) {
          try {
            if (stmt instanceof ReturnStatement) {
              // Instead of returning, just push the return value on the stack
              // and jump to the exit point for the function.
              stmt.getRHS().load(emitContext, mv);
              mv.goTo(exitLabel);

            } else {
              stmt.emit(emitContext, mv);
            }
          } catch (NotCompilableException e) {
            throw e;
          } catch (Exception e) {
            throw new InternalCompilerException("Exception compiling statement " + stmt, e);
          }
        }
      }
    }
    mv.mark(exitLabel);
  }
Exemple #3
0
 public DebugVMInstruction getStartInstruction() {
   BasicBlock bb = this.get(0);
   while (bb.size() == 0) {
     bb = bb.getSingleSuccessor();
   }
   return bb.get(0);
 }
Exemple #4
0
  @Override
  public int hashCode() {
    int sourceHash = source.hashCode();
    int edgeHash = guard == null ? 0 : guard.hashCode();
    int targetHash = target.hashCode();

    return sourceHash ^ edgeHash ^ targetHash;
  }
Exemple #5
0
 /**
  * Compute a mapping from instruction to basic block. Also, compute the blocks that end with a
  * 'normal' return.
  */
 private void computeI2BMapping() {
   instruction2Block = new int[getInstructions().length];
   for (Iterator it = iterator(); it.hasNext(); ) {
     final BasicBlock b = (BasicBlock) it.next();
     for (int j = b.getFirstInstructionIndex(); j <= b.getLastInstructionIndex(); j++) {
       instruction2Block[j] = getNumber(b);
     }
   }
 }
Exemple #6
0
 /**
  * Look up a BasicBlock by its unique label.
  *
  * @param blockLabel the label of a BasicBlock
  * @return the BasicBlock with the given label, or null if there is no such BasicBlock
  */
 public BasicBlock lookupBlockByLabel(int blockLabel) {
   for (Iterator<BasicBlock> i = blockIterator(); i.hasNext(); ) {
     BasicBlock basicBlock = i.next();
     if (basicBlock.getLabel() == blockLabel) {
       return basicBlock;
     }
   }
   return null;
 }
Exemple #7
0
 public void stringfy(StringBuilder sb) {
   sb.append(this.funcName + ":\n");
   for (int i = 0; i < this.size(); i++) {
     BasicBlock bb = this.get(i);
     sb.append(bb.name + " {\n");
     bb.stringfy(sb);
     sb.append("}\n");
   }
   sb.append("\n");
 }
Exemple #8
0
 /**
  * Get Collection of basic blocks whose IDs are specified by given BitSet.
  *
  * @param labelSet BitSet of block labels
  * @return a Collection containing the blocks whose IDs are given
  */
 public Collection<BasicBlock> getBlocks(BitSet labelSet) {
   LinkedList<BasicBlock> result = new LinkedList<BasicBlock>();
   for (Iterator<BasicBlock> i = blockIterator(); i.hasNext(); ) {
     BasicBlock block = i.next();
     if (labelSet.get(block.getLabel())) {
       result.add(block);
     }
   }
   return result;
 }
Exemple #9
0
 /**
  * Get a Collection of basic blocks which contain the bytecode instruction with given offset.
  *
  * @param offset the bytecode offset of an instruction
  * @return Collection of BasicBlock objects which contain the instruction with that offset
  */
 public Collection<BasicBlock> getBlocksContainingInstructionWithOffset(int offset) {
   LinkedList<BasicBlock> result = new LinkedList<BasicBlock>();
   for (Iterator<BasicBlock> i = blockIterator(); i.hasNext(); ) {
     BasicBlock block = i.next();
     if (block.containsInstructionWithOffset(offset)) {
       result.add(block);
     }
   }
   return result;
 }
Exemple #10
0
 private void printAllRegions() {
   for (BasicBlock bb1 : cfg.getBasicBlocks()) {
     for (BasicBlock bb2 : cfg.getBasicBlocks()) {
       if (!bb1.equals(bb2) && getDomInfo().dominates(bb1, bb2)) {
         if (isRegion(bb1, bb2)) {
           LOGGER.debug("REGION {},{}", bb1, bb2);
         }
       }
     }
   }
 }
Exemple #11
0
 @Override
 public boolean equals(Object o) {
   if (!(o instanceof Edge)) {
     return false;
   }
   Edge edge = (Edge) o;
   return (edge != null
       && source.equals(edge.source)
       && target.equals(edge.target)
       && Objects.equal(guard, edge.guard));
 }
Exemple #12
0
 public List<DebugVMInstruction> serchInst(Expression e) {
   List<DebugVMInstruction> ilist = new ArrayList<DebugVMInstruction>();
   for (int i = 0; i < this.size(); i++) {
     BasicBlock bb = this.get(i);
     for (int j = 0; j < bb.size(); j++) {
       DebugVMInstruction inst = bb.get(j);
       if (inst.expr.equals(e)) {
         ilist.add(inst);
       }
     }
   }
   return ilist;
 }
Exemple #13
0
 public int getLastInstructionIndex() {
   if (this == entry() || this == exit()) {
     // these are the special end blocks
     return -2;
   }
   if (getNumber() == (getMaxNumber() - 1)) {
     // this is the last non-exit block
     return getInstructions().length - 1;
   } else {
     BasicBlock next = getNode(getNumber() + 1);
     return next.getFirstInstructionIndex() - 1;
   }
 }
Exemple #14
0
 /**
  * Get number of non-exception control successors of given basic block.
  *
  * @param block a BasicBlock
  * @return number of non-exception control successors of the basic block
  */
 public int getNumNonExceptionSucessors(BasicBlock block) {
   int numNonExceptionSuccessors = block.getNumNonExceptionSuccessors();
   if (numNonExceptionSuccessors < 0) {
     numNonExceptionSuccessors = 0;
     for (Iterator<Edge> i = outgoingEdgeIterator(block); i.hasNext(); ) {
       Edge edge = i.next();
       if (!edge.isExceptionEdge()) {
         numNonExceptionSuccessors++;
       }
     }
     block.setNumNonExceptionSuccessors(numNonExceptionSuccessors);
   }
   return numNonExceptionSuccessors;
 }
Exemple #15
0
 /** Compute outgoing edges in the control flow graph. */
 private void computeEdges() {
   for (Iterator it = iterator(); it.hasNext(); ) {
     BasicBlock b = (BasicBlock) it.next();
     if (b.equals(exit())) {
       continue;
     } else if (b.equals(entry())) {
       BasicBlock bb0 = getBlockForInstruction(0);
       assert bb0 != null;
       addNormalEdge(b, bb0);
     } else {
       b.computeOutgoingEdges();
     }
   }
 }
Exemple #16
0
  /** @param args */
  public static void main(String[] args) {
    ArrayList<BasicBlock> blocks = new ArrayList<BasicBlock>();
    BlockFactory factory = new BlockFactory();

    BasicBlock blockA = factory.GetBlock("A");
    blocks.add(blockA);

    BasicBlock blockB = factory.GetBlock("B");
    blocks.add(blockB);

    BasicBlock blockC = factory.GetBlock("C");
    blocks.add(blockC);

    BasicBlock blockD = factory.GetBlock("D");
    blocks.add(blockD);

    BasicBlock blockE = factory.GetBlock("E");
    blocks.add(blockE);

    BasicBlock blockF = factory.GetBlock("F", true);
    blocks.add(blockF);

    Edge edgeAB = new Edge(blockA, blockB);
    Edge edgeAC = new Edge(blockA, blockC);
    Edge edgeBC = new Edge(blockB, blockC);
    Edge edgeBD = new Edge(blockB, blockD);
    Edge edgeCD = new Edge(blockC, blockD);
    Edge edgeDE = new Edge(blockD, blockE);
    Edge edgeDF = new Edge(blockD, blockF);
    Edge edgeEF = new Edge(blockE, blockF);

    blockA.getOutgoingEdges().add(edgeAB);
    blockA.getOutgoingEdges().add(edgeAC);

    blockB.getOutgoingEdges().add(edgeBC);
    blockB.getOutgoingEdges().add(edgeBD);

    blockC.getOutgoingEdges().add(edgeCD);

    blockD.getOutgoingEdges().add(edgeDE);
    blockD.getOutgoingEdges().add(edgeDF);

    blockE.getOutgoingEdges().add(edgeEF);

    BallLarus larus = new BallLarus();
    larus.CalculateValues(blocks);

    System.out.println(larus.GetDOT(blocks));
  }
  /** add the start and the end blocks in the CFG */
  private void addStartEndBlocks() {
    // this blocks have no code to generate and to
    start = new BasicBlock(graph);
    end = new BasicBlock(graph);

    start.addDefaultNextBlock(firstBB);
    start.addCFGNextBlock(end);
    int i = 0;
    // all blocks with no succesor are linked to the end block
    for (BasicBlock bb = firstBB; bb != null; bb = bb.getNext()) {
      if (!bb.hasSuccessor()) {
        ++i;
        bb.addCFGNextBlock(end);
      }
    }
  }
Exemple #18
0
  /** Initialize the block with the default values */
  @Override
  protected void setDefaultValues() {
    super.setDefaultValues();
    setInterfaceFunctionName(INTERFUNCTION_NAME);
    setStyle(INTERFUNCTION_NAME);

    setValue(XcosMessages.DOTS);
  }
Exemple #19
0
  @Override
  public String toString() {
    StringBuffer s = new StringBuffer("");
    for (Iterator it = iterator(); it.hasNext(); ) {
      BasicBlock bb = (BasicBlock) it.next();
      s.append("BB").append(getNumber(bb)).append("\n");
      for (int j = bb.getFirstInstructionIndex(); j <= bb.getLastInstructionIndex(); j++) {
        s.append("  ").append(j).append("  ").append(getInstructions()[j]).append("\n");
      }

      Iterator<BasicBlock> succNodes = getSuccNodes(bb);
      while (succNodes.hasNext()) {
        s.append("    -> BB").append(getNumber(succNodes.next())).append("\n");
      }
    }
    return s.toString();
  }
Exemple #20
0
 public BasicPlane writeLP(int lp, int dummy) {
   List<BasicBlock> updatedBlocks = getNewBlocksList();
   int active = getActiveBlockIndex();
   if (active == -1) {
     active = getLowestEraseCleanBlockIndex();
     updatedBlocks.set(
         active, (BasicBlock) updatedBlocks.get(active).setStatus(BlockStatusGeneral.ACTIVE));
   }
   BasicBlock activeBlock = updatedBlocks.get(active);
   activeBlock = activeBlock.writeLP(lp);
   if (!activeBlock.hasRoomForWrite()) {
     activeBlock = (BasicBlock) activeBlock.setStatus(BlockStatusGeneral.USED);
   }
   updatedBlocks.set(active, activeBlock);
   Builder builder = getSelfBuilder();
   builder.setBlocks(updatedBlocks);
   return builder.build();
 }
Exemple #21
0
 public Completion executeWith(JSObject withObj, BasicBlock block) {
   LexicalEnvironment oldEnv = this.lexicalEnvironment;
   LexicalEnvironment withEnv = LexicalEnvironment.newObjectEnvironment(withObj, true, oldEnv);
   try {
     this.lexicalEnvironment = withEnv;
     return block.call(this);
   } finally {
     this.lexicalEnvironment = oldEnv;
   }
 }
Exemple #22
0
 Statement generateJumpStatement(BasicBlock target) {
   if (nextBlock == target && blockMap[target.getIndex()] == null) {
     return null;
   }
   Decompiler.Block block = blockMap[target.getIndex()];
   if (block == null) {
     throw new IllegalStateException("Could not find block for basic block $" + target.getIndex());
   }
   if (target.getIndex() == indexer.nodeAt(block.end)) {
     BreakStatement breakStmt = new BreakStatement();
     breakStmt.setLocation(currentLocation);
     breakStmt.setTarget(block.statement);
     return breakStmt;
   } else {
     ContinueStatement contStmt = new ContinueStatement();
     contStmt.setLocation(currentLocation);
     contStmt.setTarget(block.statement);
     return contStmt;
   }
 }
Exemple #23
0
  /**
   * Apply style on setExprs
   *
   * @param exprs the expression to be parsed
   */
  @Override
  public void setExprs(ScilabType exprs) {
    super.setExprs(exprs);

    final StyleMap map = new StyleMap(getStyle());
    map.put(mxConstants.STYLE_FONTFAMILY, getFont().getName());
    map.put(mxConstants.STYLE_FONTSIZE, Integer.toString(getFontSize()));
    setStyle(map.toString());

    setValue(getLocalExprs().getData()[0][0]);
  }
Exemple #24
0
 /** Initialize the block with the default values */
 @Override
 protected void setDefaultValues() {
   super.setDefaultValues();
   setInterfaceFunctionName("SPLIT_f");
   setStyle(getInterfaceFunctionName());
   setSimulationFunctionName("lsplit");
   setRealParameters(new ScilabDouble());
   setIntegerParameters(new ScilabDouble());
   setObjectsParameters(new ScilabList());
   setExprs(new ScilabDouble());
 }
Exemple #25
0
 public void checkIntegrity() {
   // Ensure that basic blocks have only consecutive instructions
   for (Iterator<BasicBlock> i = blockIterator(); i.hasNext(); ) {
     BasicBlock basicBlock = i.next();
     InstructionHandle prev = null;
     for (Iterator<InstructionHandle> j = basicBlock.instructionIterator(); j.hasNext(); ) {
       InstructionHandle handle = j.next();
       if (prev != null && prev.getNext() != handle) {
         throw new IllegalStateException(
             "Non-consecutive instructions in block "
                 + basicBlock.getLabel()
                 + ": prev="
                 + prev
                 + ", handle="
                 + handle);
       }
       prev = handle;
     }
   }
 }
 @Override
 public int genLLCode(BasicBlock block) {
   Function func = block.getFunc();
   HashMap funcSymbolTable = func.getTable();
   HashMap globalSymbolTable = func.getGlobalHash();
   if (funcSymbolTable.containsKey(id)) {
     return (int) funcSymbolTable.get(id);
   } else if (globalSymbolTable.containsKey(id)) {
     return (int) globalSymbolTable.get(id);
   } else {
     throw new lowlevel.LowLevelException("Var " + id + " is not defined");
   }
 }
Exemple #27
0
  @Override
  protected Pair<BasicPlane, Integer> cleanPlane() {
    List<BasicBlock> cleanBlocks = getNewBlocksList();
    Pair<Integer, BasicBlock> pickedToClean = pickBlockToClean();
    int toMove = pickedToClean.getValue1().getValidCounter();
    int active = getActiveBlockIndex();
    BasicBlock activeBlock = cleanBlocks.get(active);

    for (BasicPage page : pickedToClean.getValue1().getPages()) {
      if (page.isValid()) {
        activeBlock = activeBlock.move(page.getLp());
      }
    }
    if (!activeBlock.hasRoomForWrite()) {
      activeBlock = (BasicBlock) activeBlock.setStatus(BlockStatusGeneral.USED);
    }
    cleanBlocks.set(active, activeBlock);
    cleanBlocks.set(pickedToClean.getValue0(), (BasicBlock) pickedToClean.getValue1().eraseBlock());
    Builder builder = getSelfBuilder();
    builder.setBlocks(cleanBlocks);
    return new Pair<>(builder.build(), toMove);
  }
  protected String processSimpleEdge(CFAEdge pCFAEdge, BasicBlock currentBlock) {

    switch (pCFAEdge.getEdgeType()) {
      case BlankEdge:
      case StatementEdge:
      case ReturnStatementEdge:
        return pCFAEdge.getCode();

      case AssumeEdge:
        {
          CAssumeEdge lAssumeEdge = (CAssumeEdge) pCFAEdge;
          return ("__CPROVER_assume(" + lAssumeEdge.getCode() + ");");
          //    return ("if(! (" + lAssumptionString + ")) { return (0); }");
        }

      case DeclarationEdge:
        {
          CDeclarationEdge lDeclarationEdge = (CDeclarationEdge) pCFAEdge;

          if (lDeclarationEdge.getDeclaration().isGlobal()) {
            mGlobalDefinitionsList.add(lDeclarationEdge.getCode());
            return "";
          }

          // avoid having the same declaration edge twice in one basic block
          if (currentBlock.hasDeclaration(lDeclarationEdge)) {
            return "";
          } else {
            currentBlock.addDeclaration(lDeclarationEdge);
            return lDeclarationEdge.getCode();
          }
        }

      default:
        throw new AssertionError(
            "Unexpected edge " + pCFAEdge + " of type " + pCFAEdge.getEdgeType());
    }
  }
Exemple #29
0
  public Location getPreviousLocation(Location loc) {
    InstructionHandle handle = loc.getHandle();

    BasicBlock basicBlock = loc.getBasicBlock();
    if (basicBlock.getFirstInstruction().equals(handle)) {
      BasicBlock prevBlock = basicBlock;

      while (true) {
        prevBlock = getPredecessorWithEdgeType(prevBlock, EdgeTypes.FALL_THROUGH_EDGE);
        if (prevBlock == null) {
          return loc;
        }

        handle = prevBlock.getLastInstruction();
        if (handle != null) {
          return new Location(handle, prevBlock);
        }
      }

    } else {
      handle = handle.getPrev();
      return new Location(handle, basicBlock);
    }
  }
  /**
   * Construct the control flow graph with the information code of a method.
   *
   * @param methodInfo informations on the method
   * @param info informations on the method code
   */
  public ControlFlowGraph(MethodInfo methodInfo, CodeInfo info) {
    this.info = info;
    graph = new Graph();
    subroutines = new HashMap();

    findBasicBlocks();

    generateQInsts(info.getInstructions(), methodInfo);

    constructSSAForm();

    optimize();

    if (DEBUG) {
      for (BasicBlock bb = firstBB; bb != null; bb = bb.getNext()) {
        System.out.println("\n" + bb);
        Iterator insts = bb.getAllSSAInstructions();
        while (insts.hasNext()) {
          QInst inst = (QInst) insts.next();
          System.out.println(inst);
        }
      }
    }
  }