Beispiel #1
1
  protected void computeEdgeAndThreadNo() {
    Iterator it = iterator();
    int numberOfEdge = 0;
    while (it.hasNext()) {
      List succList = (List) getSuccsOf(it.next());

      numberOfEdge = numberOfEdge + succList.size();
    }
    numberOfEdge = numberOfEdge + startToThread.size();

    System.err.println("**number of edges: " + numberOfEdge);

    System.err.println("**number of threads: " + (startToThread.size() + 1));

    /*	Set keySet = startToThread.keySet();
    Iterator keyIt = keySet.iterator();
    while (keyIt.hasNext()){
    List list = (List)startToThread.get(keyIt.next());
    System.out.println("********start thread:");
    Iterator itit = list.iterator();
    while (itit.hasNext()){
    System.out.println(it.next());
    }
    }
    */

  }
Beispiel #2
0
  /**
   * given a DelayabilityAnalysis and the computations of each unit, calculates the latest
   * computation-point for each expression.<br>
   * the <code>equivRhsMap</code> could be calculated on the fly, but it is <b>very</b> likely that
   * it already exists (as similar maps are used for calculating Earliestness, Delayed,...<br>
   * the shared set allows more efficient set-operations, when they the computation is merged with
   * other analyses/computations.
   *
   * @param dg a ExceptionalUnitGraph
   * @param delayed the delayability-analysis of the same graph.
   * @param equivRhsMap all computations of the graph
   * @param set the shared flowSet
   */
  public LatestComputation(
      UnitGraph unitGraph, DelayabilityAnalysis delayed, Map equivRhsMap, BoundedFlowSet set) {
    unitToLatest = new HashMap<Unit, FlowSet>(unitGraph.size() + 1, 0.7f);

    Iterator unitIt = unitGraph.iterator();
    while (unitIt.hasNext()) {
      /* create a new Earliest-list for each unit */
      Unit currentUnit = (Unit) unitIt.next();

      /* basically the latest-set is:
       * (delayed) INTERSECT (comp UNION (UNION_successors ~Delayed)) =
       * (delayed) MINUS ((INTERSECTION_successors Delayed) MINUS comp).
       */

      FlowSet delaySet = (FlowSet) delayed.getFlowBefore(currentUnit);

      /* Calculate (INTERSECTION_successors Delayed) */
      FlowSet succCompSet = (FlowSet) set.topSet();
      List succList = unitGraph.getSuccsOf(currentUnit);
      Iterator succIt = succList.iterator();
      while (succIt.hasNext()) {
        Unit successor = (Unit) succIt.next();
        succCompSet.intersection((FlowSet) delayed.getFlowBefore(successor), succCompSet);
      }
      /* remove the computation of this set: succCompSet is then:
       * ((INTERSECTION_successors Delayed) MINUS comp) */
      if (equivRhsMap.get(currentUnit) != null) succCompSet.remove(equivRhsMap.get(currentUnit));

      /* make the difference: */
      FlowSet latest = (FlowSet) delaySet.emptySet();
      delaySet.difference(succCompSet, latest);

      unitToLatest.put(currentUnit, latest);
    }
  }
Beispiel #3
0
  private void insertAfter(JPegStmt node, JPegStmt after) {
    // System.out.println("node: "+node);
    // System.out.println("after: "+after);
    //		System.out.println("succs of node: "+getSuccsOf(node));

    // this must be done first because the succs of node will be chanaged lately
    List succOfAfter = new ArrayList();
    succOfAfter.addAll(getSuccsOf(node));
    unitToSuccs.put(after, succOfAfter);

    Iterator succsIt = getSuccsOf(node).iterator();
    while (succsIt.hasNext()) {
      Object succ = succsIt.next();
      List pred = getPredsOf(succ);
      pred.remove(node);
      pred.add(after);
    }

    List succOfNode = new ArrayList();
    succOfNode.add(after);
    unitToSuccs.put(node, succOfNode);

    List predOfAfter = new ArrayList();
    predOfAfter.add(node);
    unitToPreds.put(after, predOfAfter);

    //	buildPredecessor(Chain pegChain);
  }
Beispiel #4
0
 protected void buildPreds() {
   buildPredecessor(mainPegChain);
   Set maps = getStartToThread().entrySet();
   for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
     Map.Entry entry = (Map.Entry) iter.next();
     List runMethodChainList = (List) entry.getValue();
     Iterator it = runMethodChainList.iterator();
     while (it.hasNext()) {
       Chain chain = (Chain) it.next();
       //	System.out.println("chain is null: "+(chain == null));
       buildPredecessor(chain);
     }
   }
 }
  private void createWorkList(LinkedList<Object> changedUnits, HashSet<Object> changedUnitsSet) {
    createWorkList(changedUnits, changedUnitsSet, g.getMainPegChain());

    Set maps = g.getStartToThread().entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      List runMethodChainList = (List) entry.getValue();
      Iterator it = runMethodChainList.iterator();
      while (it.hasNext()) {
        PegChain chain = (PegChain) it.next();
        createWorkList(changedUnits, changedUnitsSet, chain);
      }
    }
  }
Beispiel #6
0
 protected void testList(List list) {
   //		System.out.println("test list");
   Iterator listIt = list.iterator();
   while (listIt.hasNext()) {
     System.out.println(listIt.next());
   }
 }
Beispiel #7
0
  private boolean removeBeginNode() {
    List heads = getHeads();
    if (heads.size() != 1) {
      // System.out.println("heads: "+heads);
      // System.out.println("Error: the size of heads is not equal to 1!");
      return false;
      //	    System.exit(1);
    } else {
      JPegStmt head = (JPegStmt) heads.get(0);
      // System.out.println("test head: "+head);
      if (!head.getName().equals("begin")) {
        System.err.println("Error: the head is not begin node!");
        System.exit(1);
      }
      // remove begin node from heads list
      heads.remove(0);
      // set the preds list of the succs of head to a new list and put succs of head into heads
      Iterator succOfHeadIt = getSuccsOf(head).iterator();
      while (succOfHeadIt.hasNext()) {

        JPegStmt succOfHead = (JPegStmt) succOfHeadIt.next();

        unitToPreds.put(succOfHead, new ArrayList());
        // put succs of head into heads
        heads.add(succOfHead);
      }
      // remove begin node from inlinee Peg
      if (!mainPegChain.remove(head)) {
        System.err.println("fail to remove begin node in from mainPegChain!");
        System.exit(1);
      }
      if (!allNodes.contains(head)) {
        System.err.println("fail to find begin node in FlowSet allNodes!");
        System.exit(1);
      } else {
        allNodes.remove(head);
      }

      // remove begin node from unitToSuccs
      if (unitToSuccs.containsKey(head)) {
        unitToSuccs.remove(head);
      }
    }

    return true;
  }
Beispiel #8
0
  public String toString() {
    Iterator it = iterator();
    StringBuffer buf = new StringBuffer();
    while (it.hasNext()) {
      JPegStmt u = (JPegStmt) it.next();
      buf.append("u is: " + u + "\n");
      List l = new ArrayList();
      l.addAll(getPredsOf(u));
      buf.append("preds: " + l + "\n");
      // buf.append(u.toString() + '\n');
      l = new ArrayList();
      l.addAll(getSuccsOf(u));
      buf.append("succs: " + l + "\n");
    }

    return buf.toString();
  }
Beispiel #9
0
  protected void testUnitToSucc() {
    System.out.println("=====test unitToSucc ");
    Set maps = unitToSuccs.entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      JPegStmt key = (JPegStmt) entry.getKey();
      Tag tag = (Tag) key.getTags().get(0);
      System.out.println("---key=  " + tag + " " + key);
      List list = (List) entry.getValue();
      if (list.size() > 0) {

        System.out.println("**succ set: size: " + list.size());
        Iterator it = list.iterator();
        while (it.hasNext()) {
          JPegStmt stmt = (JPegStmt) it.next();
          Tag tag1 = (Tag) stmt.getTags().get(0);
          System.out.println(tag1 + " " + stmt);
        }
      }
    }
    System.out.println("=========unitToSucc--ends--------");
  }
Beispiel #10
0
  private void buildHeadsAndTails() {

    List tailList = new ArrayList();
    List headList = new ArrayList();

    // Build the sets
    {
      Iterator unitIt = mainPegChain.iterator();

      while (unitIt.hasNext()) {
        JPegStmt s = (JPegStmt) unitIt.next();

        List succs = unitToSuccs.get(s);
        if (succs.size() == 0) tailList.add(s);
        if (!unitToPreds.containsKey(s)) {
          System.err.println("unitToPreds does not contain key: " + s);
          System.exit(1);
        }
        List preds = unitToPreds.get(s);
        if (preds.size() == 0) headList.add(s);
        // System.out.println("head is:");
      }
    }
    tails = (List) tailList;
    heads = (List) headList;
    //	tails = Collections.unmodifiableList(tailList);
    // heads = Collections.unmodifiableList(headList);

    Iterator tmpIt = heads.iterator();

    while (tmpIt.hasNext()) {
      Object temp = tmpIt.next();
      // System.out.println(temp);
    }

    buildPredecessor(mainPegChain);
  }
Beispiel #11
0
  private void insertBefore(JPegStmt node, JPegStmt enter) {

    // build preds of before

    List predOfBefore = new ArrayList();
    predOfBefore.addAll(getPredsOf(node));
    unitToPreds.put(enter, predOfBefore);

    //	System.out.println("put into unitToPreds enter: "+enter);
    //	System.out.println("put into unitToPreds value: "+predOfBefore);
    Iterator predsIt = getPredsOf(node).iterator();

    // build succs of former preds of node
    while (predsIt.hasNext()) {
      Object pred = predsIt.next();

      List succ = getSuccsOf(pred);
      succ.remove(node);
      succ.add(enter);
      //	    System.out.println("in unitToPred pred: "+pred);
      //	    System.out.println("in unitToPred value is: "+succ);
    }

    List succOfBefore = new ArrayList();
    succOfBefore.add(node);
    unitToSuccs.put(enter, succOfBefore);
    //	System.out.println("put into unitToSuccs enter: "+enter);
    // System.out.println("put into unitToSuccs value: "+succOfBefore);

    List predOfNode = new ArrayList();
    predOfNode.add(enter);
    unitToPreds.put(node, predOfNode);
    // System.out.println("put into unitToPreds enter: "+node);
    // System.out.println("put into unitToPreds value: "+predOfNode);
    // buildPreds();

  }
  /**
   * This method pushes all newExpr down to be the stmt directly before every invoke of the init
   * only if they are in the types list
   */
  public void internalTransform(Body b, String phaseName, Map options) {
    JimpleBody body = (JimpleBody) b;

    if (Options.v().verbose())
      G.v().out.println("[" + body.getMethod().getName() + "] Folding Jimple constructors...");

    Chain units = body.getUnits();
    List<Unit> stmtList = new ArrayList<Unit>();
    stmtList.addAll(units);

    Iterator<Unit> it = stmtList.iterator();
    Iterator<Unit> nextStmtIt = stmtList.iterator();
    // start ahead one
    nextStmtIt.next();

    SmartLocalDefs localDefs = SmartLocalDefsPool.v().getSmartLocalDefsFor(body);
    UnitGraph graph = localDefs.getGraph();
    LocalUses localUses = new SimpleLocalUses(graph, localDefs);

    /* fold in NewExpr's with specialinvoke's */
    while (it.hasNext()) {
      Stmt s = (Stmt) it.next();

      if (!(s instanceof AssignStmt)) continue;

      /* this should be generalized to ArrayRefs */
      // only deal with stmts that are an local = newExpr
      Value lhs = ((AssignStmt) s).getLeftOp();
      if (!(lhs instanceof Local)) continue;

      Value rhs = ((AssignStmt) s).getRightOp();
      if (!(rhs instanceof NewExpr)) continue;

      // check if very next statement is invoke -->
      // this indicates there is no control flow between
      // new and invoke and should do nothing
      if (nextStmtIt.hasNext()) {
        Stmt next = (Stmt) nextStmtIt.next();
        if (next instanceof InvokeStmt) {
          InvokeStmt invoke = (InvokeStmt) next;

          if (invoke.getInvokeExpr() instanceof SpecialInvokeExpr) {
            SpecialInvokeExpr invokeExpr = (SpecialInvokeExpr) invoke.getInvokeExpr();
            if (invokeExpr.getBase() == lhs) {
              break;
            }
          }
        }
      }

      // check if new is in the types list - only process these
      if (!types.contains(((NewExpr) rhs).getType())) continue;

      List lu = localUses.getUsesOf(s);
      Iterator luIter = lu.iterator();
      boolean MadeNewInvokeExpr = false;

      while (luIter.hasNext()) {
        Unit use = ((UnitValueBoxPair) (luIter.next())).unit;
        if (!(use instanceof InvokeStmt)) continue;
        InvokeStmt is = (InvokeStmt) use;
        if (!(is.getInvokeExpr() instanceof SpecialInvokeExpr)
            || lhs != ((SpecialInvokeExpr) is.getInvokeExpr()).getBase()) continue;

        // make a new one here
        AssignStmt constructStmt =
            Jimple.v()
                .newAssignStmt(((DefinitionStmt) s).getLeftOp(), ((DefinitionStmt) s).getRightOp());
        constructStmt.setRightOp(Jimple.v().newNewExpr(((NewExpr) rhs).getBaseType()));
        MadeNewInvokeExpr = true;

        // redirect jumps
        use.redirectJumpsToThisTo(constructStmt);
        // insert new one here
        units.insertBefore(constructStmt, use);

        constructStmt.addTag(s.getTag("SourceLnPosTag"));
      }
      if (MadeNewInvokeExpr) {
        units.remove(s);
      }
    }
  }
Beispiel #13
0
  protected void buildSuccsForInlining(JPegStmt stmt, Chain chain, PegGraph inlinee) {
    // System.out.println("entering buildSuccsForInlining...");
    Tag tag = (Tag) stmt.getTags().get(0);
    // System.out.println("stmt is: "+tag+" "+stmt);
    /*connect heads of inlinee with the preds of invokeStmt and
     * delete stmt from the succs list from the preds
     */

    Iterator predIt = getPredsOf(stmt).iterator();
    // System.out.println("preds list: "+getPredsOf(stmt));
    // System.out.println("preds size: "+getPredsOf(stmt).size());
    Iterator headsIt = inlinee.getHeads().iterator();
    {
      // System.out.println("heads: "+inlinee.getHeads());
      while (predIt.hasNext()) {
        JPegStmt pred = (JPegStmt) predIt.next();
        // System.out.println("pred: "+pred);
        List succList = (List) getSuccsOf(pred);
        // System.out.println("succList of pred: "+succList);
        int pos = succList.indexOf(stmt);
        // System.out.println("remove : "+stmt + " from succList: \n"+succList+ "\n of pred" );
        // remove invokeStmt
        succList.remove(pos);

        while (headsIt.hasNext()) {
          succList.add(headsIt.next());
        }
        unitToSuccs.put(pred, succList);
      }

      {
        while (headsIt.hasNext()) {
          Object head = headsIt.next();
          List predsOfHeads = new ArrayList();
          predsOfHeads.addAll(getPredsOf(head));
          unitToPreds.put(head, predsOfHeads);
        }
      }
      /*
      {
      predIt = getPredsOf(stmt).iterator();
      while (predIt.hasNext()){
      JPegStmt s = (JPegStmt)predIt.next();
      if (unitToSuccs.containsKey(s)){
      Iterator succIt = ((List) unitToSuccs.get(s)).iterator();
      while(succIt.hasNext()){

      //Object successor =  succIt.next();
       JPegStmt successor = (JPegStmt)succIt.next();
       List predList = (List) unitToPreds.get(successor);
       if (predList != null) {
       try {
       predList.add(s);

       } catch(NullPointerException e) {
       System.out.println(s + "successor: " + successor);
       throw e;
       }
       }
       }
       }
       }




       }*/

    }

    /*connect tails of inlinee with the succ of invokeStmt and
     * delete stmt from the
     */

    Iterator tailsIt = inlinee.getTails().iterator();
    {
      // System.out.println("tails: "+inlinee.getTails());
      while (tailsIt.hasNext()) {
        Iterator succIt = getSuccsOf(stmt).iterator();
        JPegStmt tail = (JPegStmt) tailsIt.next();
        List succList = null;
        if (unitToSuccs.containsKey(tail)) {
          // System.out.println("error: unitToSucc containsKey: "+tail);
          succList = (List) getSuccsOf(tail);
          // System.out.println("succList: "+succList);
        } else {

          succList = new ArrayList();
        }
        while (succIt.hasNext()) {
          JPegStmt succ = (JPegStmt) succIt.next();
          succList.add(succ);
          // System.out.println("succ: "+succ);
          // remove stmt from the preds list of the succs of itself.
          List predListOfSucc = getPredsOf(succ);
          if (predListOfSucc == null) {
            System.err.println("Error: predListOfSucc is null!");
            System.exit(1);
          } else {
            if (predListOfSucc.size() != 0) {

              int pos = predListOfSucc.indexOf(stmt);
              if (pos > 0 || pos == 0) {

                //	System.out.println("remove stmt: "+stmt+" from the preds list"+predListOfSucc+"
                // of the succ");
                predListOfSucc.remove(pos);
              }

              //		System.out.println("remove(from PRED): ");
            }
          }
          unitToPreds.put(succ, predListOfSucc);
        }
        unitToSuccs.put(tail, succList);
        // System.out.println("put: "+tail);
        // System.out.println("succList: "+succList+ "into unitToSucc");

      }
    }

    // add Nov 1
    {
      tailsIt = inlinee.getTails().iterator();
      while (tailsIt.hasNext()) {
        JPegStmt s = (JPegStmt) tailsIt.next();
        if (unitToSuccs.containsKey(s)) {
          Iterator succIt = unitToSuccs.get(s).iterator();
          while (succIt.hasNext()) {

            // Object successor =  succIt.next();
            JPegStmt successor = (JPegStmt) succIt.next();
            List<JPegStmt> predList = unitToPreds.get(successor);
            if (predList != null && !predList.contains(s)) {
              try {
                predList.add(s);
                /*
                Tag tag = (Tag)successor.getTags().get(0);
                System.out.println("add "+s+" to predlist of "+tag+" "+successor);
                */
              } catch (NullPointerException e) {
                System.out.println(s + "successor: " + successor);
                throw e;
              }
            }
          }
        }
      }
    }
    // end add Nov 1

    // System.out.println("stmt: "+stmt);
    // remove stmt from allNodes and mainPegChain
    // System.out.println("mainPegChain contains stmt: "+mainPegChain.contains(stmt));
    //		testPegChain();

    if (!allNodes.contains(stmt)) {
      System.err.println("fail to find begin node in  allNodes!");
      System.exit(1);
    } else {
      allNodes.remove(stmt);
      // System.out.println("remove from allNode: "+stmt);
    }

    if (!chain.contains(stmt)) {
      System.err.println("Error! Chain does not contains stmt (extending point)!");
      System.exit(1);

    } else {
      if (!chain.remove(stmt)) {
        System.err.println("fail to remove invoke stmt in from Chain!");
        System.exit(1);
      }
    }
    /*
    if (!mainPegChain.contains(stmt)){
    boolean find = false;
    //System.out.println("main chain does not contain AFTER");
     Set maps = startToThread.entrySet();
     for(Iterator iter=maps.iterator(); iter.hasNext();){
     Map.Entry entry = (Map.Entry)iter.next();
     Object startNode = entry.getKey();
     Iterator runIt  = ((List)entry.getValue()).iterator();
     while (runIt.hasNext()){
     Chain chain=(Chain)runIt.next();
     if (chain.contains(stmt)) {
     find = true;
     if (!chain.remove(stmt)){
     System.err.println("fail to remove begin node in from mainPegChain!");
     System.exit(1);
     }
     break;
     }
     }
     if (find == false){
     System.err.println("fail to find stmt: "+stmt+" in chains!");
     System.exit(1);
     }
     }
     //this.toString();
      }
      else{
      if (!mainPegChain.remove(stmt)) {
      System.err.println("fail to remove begin node in from mainPegChain!");
      System.exit(1);
      }
      else{
      // System.out.println("remove(from mainchain): "+stmt);
       }
       }
       */
    // remove stmt from unitToSuccs and unitToPreds
    if (unitToSuccs.containsKey(stmt)) {
      unitToSuccs.remove(stmt);
    }
    if (unitToPreds.containsKey(stmt)) {
      unitToPreds.remove(stmt);
    }
  }
Beispiel #14
0
  /*
  private void deleteExitToException(){
  Iterator it = iterator();
  while (it.hasNext()){
  JPegStmt stmt = (JPegStmt)it.next();
  Unit unit = stmt.getUnit();
  UnitGraph unitGraph = stmt.getUnitGraph();
  if (unit instanceof ExitMonitorStmt){
  Iterator succIt = unitGraph.getSuccsOf(unit).iterator();
  while(succIt.next
  && exceHandlers.contains(un) ){
  System.out.println("====find it! unit: "+unit+"\n un: "+un);
  continue;
  }
  }
  }
  */
  private void buildPredecessor(Chain pegChain) {
    // System.out.println("==building predcessor===");

    // initialize the pred sets to empty
    {
      JPegStmt s = null;
      Iterator unitIt = pegChain.iterator();
      while (unitIt.hasNext()) {

        s = (JPegStmt) unitIt.next();

        unitToPreds.put(s, new ArrayList());
      }
    }
    //	System.out.println("==finish init of unitToPred===");
    {
      Iterator unitIt = pegChain.iterator();

      while (unitIt.hasNext()) {

        Object s = unitIt.next();
        //		System.out.println("s is: "+s);

        // Modify preds set for each successor for this statement
        if (unitToSuccs.containsKey(s)) {
          List succList = unitToSuccs.get(s);
          Iterator succIt = succList.iterator();
          //		    System.out.println("unitToSuccs contains "+s);
          //		    System.out.println("succList is: "+succList);
          while (succIt.hasNext()) {

            // Object successor =  succIt.next();
            JPegStmt successor = (JPegStmt) succIt.next();
            //			System.out.println("successor is: "+successor);
            List<Object> predList = unitToPreds.get(successor);
            //			System.out.println("predList is: "+predList);
            if (predList != null && !predList.contains(s)) {
              try {
                predList.add(s);
                /*
                Tag tag1 = (Tag)((JPegStmt)s).getTags().get(0);
                System.out.println("add "+tag1+" "+s+" to predListof");
                Tag tag2 = (Tag)((JPegStmt)successor).getTags().get(0);
                System.out.println(tag2+" "+successor);
                */
              } catch (NullPointerException e) {
                System.out.println(s + "successor: " + successor);
                throw e;
              }
              // if (((JPegStmt)successor).getName().equals("start")){
              if (successor instanceof StartStmt) {
                List runMethodChainList = startToThread.get(successor);
                if (runMethodChainList == null) {
                  throw new RuntimeException("null runmehtodchain: \n" + successor.getUnit());
                }
                Iterator possibleMethodIt = runMethodChainList.iterator();
                while (possibleMethodIt.hasNext()) {

                  Chain subChain = (Chain) possibleMethodIt.next();

                  buildPredecessor(subChain);
                }
              }
            } else {
              System.err.println("predlist of " + s + " is null");
              //							System.exit(1);
            }
            //			unitToPreds.put(successor, predList);

          }

        } else {
          System.err.println("unitToSuccs does not contains key" + s);
          System.exit(1);
        }
      }
    }
  }
Beispiel #15
0
  // This method adds the monitorenter/exit statements into whichever pegChain contains the
  // corresponding node statement
  protected void addMonitorStmt() {
    // System.out.println("====entering addMonitorStmt");
    if (synch.size() > 0) {
      // System.out.println("synch: "+synch);
      Iterator<List> it = synch.iterator();
      while (it.hasNext()) {
        List list = it.next();

        JPegStmt node = (JPegStmt) list.get(0);
        JPegStmt enter = (JPegStmt) list.get(1);
        JPegStmt exit = (JPegStmt) list.get(2);
        //		System.out.println("monitor node: "+node);
        // System.out.println("monitor enter: "+enter);
        // System.out.println("monitor exit: "+exit);
        // add for test
        // System.out.println("allNodes contains node: "+allNodes.contains(node));
        // end add for test

        {
          if (!mainPegChain.contains(node)) {

            boolean find = false;
            // System.out.println("main chain does not contain node");
            Set maps = startToThread.entrySet();
            // System.out.println("size of startToThread: "+startToThread.size());
            for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
              Map.Entry entry = (Map.Entry) iter.next();
              Object startNode = entry.getKey();
              Iterator runIt = ((List) entry.getValue()).iterator();
              while (runIt.hasNext()) {
                Chain chain = (Chain) runIt.next();
                //	testPegChain(chain);
                if (chain.contains(node)) {
                  find = true;
                  // System.out.println("---find it---");
                  chain.add(enter);
                  chain.add(exit);
                  break;
                }
              }
            }
            if (find == false) {
              System.err.println("fail to find stmt: " + node + " in chains!");
              System.exit(1);
            }

            // this.toString();
          } else {
            mainPegChain.add(enter);
            mainPegChain.add(exit);
          }
        }

        allNodes.add(enter);
        allNodes.add(exit);

        insertBefore(node, enter);
        insertAfter(node, exit);
      }
    }
    // add for test
    /*
    {
    // System.out.println("===main peg chain===");
     //testPegChain(mainPegChain);
      //System.out.println("===end main peg chain===");
       Set maps = startToThread.entrySet();
       for(Iterator iter=maps.iterator(); iter.hasNext();){
       Map.Entry entry = (Map.Entry)iter.next();
       Object startNode = entry.getKey();
       Iterator runIt  = ((List)entry.getValue()).iterator();
       while (runIt.hasNext()){
       Chain chain=(Chain)runIt.next();
       testPegChain(chain);
       }
       }
       }
       */
    //	System.out.println(this.toString());
    // end add for test
  }
Beispiel #16
0
  private void buildSuccessor(Chain pegChain) {

    // Add regular successors
    {
      HashMap unitToPeg = (HashMap) unitToPegMap.get(pegChain);
      Iterator pegIt = pegChain.iterator();
      JPegStmt currentNode, nextNode;
      currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
      // June 19 add for begin node
      if (currentNode != null) {
        // System.out.println("currentNode: "+currentNode);
        // if the unit is "begin" node
        nextNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;

        if (currentNode.getName().equals("begin")) {
          List<JPegStmt> successors = new ArrayList<JPegStmt>();
          successors.add(nextNode);
          unitToSuccs.put(currentNode, successors);

          currentNode = nextNode;
        }
        // end June 19 add for begin node

        while (currentNode != null) {
          //		    System.out.println("currentNode: "+currentNode);
          /* If unitToSuccs contains currentNode, it is the point to inline methods,
           * we need not compute its successors again
           */

          if (unitToSuccs.containsKey(currentNode) && !currentNode.getName().equals("wait")) {
            currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
            continue;
          }
          List<JPegStmt> successors = new ArrayList<JPegStmt>();
          Unit unit = currentNode.getUnit();

          UnitGraph unitGraph = currentNode.getUnitGraph();
          List unitSucc = unitGraph.getSuccsOf(unit);
          Iterator succIt = unitSucc.iterator();
          while (succIt.hasNext()) {
            Unit un = (Unit) succIt.next();

            // Don't build the edge from "monitor exit" to exception handler

            if (unit instanceof ExitMonitorStmt && exceHandlers.contains(un)) {
              // System.out.println("====find it! unit: "+unit+"\n un: "+un);
              continue;
            } else if (unitToPeg.containsKey(un)) {
              JPegStmt pp = (JPegStmt) (unitToPeg.get(un));
              if (pp != null && !successors.contains(pp)) successors.add(pp);
            }
          } // end while

          if (currentNode.getName().equals("wait")) {
            while (!(currentNode.getName().equals("notified-entry"))) {
              currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
            }
            unitToSuccs.put(currentNode, successors);
            // System.out.println("put key: "+currentNode+" into unitToSucc");
          } else {
            unitToSuccs.put(currentNode, successors);
          }
          if (currentNode.getName().equals("start")) {

            //						System.out.println("-----build succ for start----");

            if (startToThread.containsKey(currentNode)) {
              List runMethodChainList = startToThread.get(currentNode);
              Iterator possibleMethodIt = runMethodChainList.iterator();
              while (possibleMethodIt.hasNext()) {

                Chain subChain = (Chain) possibleMethodIt.next();
                if (subChain != null) {
                  // System.out.println("build succ for subChain");
                  // buildSuccessor(subGraph, subChain, addExceptionEdges);
                  buildSuccessor(subChain);
                } else System.out.println("*********subgraph is null!!!");
              }
            }
          }

          currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
        } // while

        // June 19 add for begin node
      }
      // end June 19 add for begin node
    }
  }
  protected void doAnalysis() {
    LinkedList<Object> changedUnits = new LinkedList<Object>();
    HashSet<Object> changedUnitsSet = new HashSet<Object>();

    int numNodes = graph.size();
    int numComputations = 0;

    // Set initial values and nodes to visit.

    createWorkList(changedUnits, changedUnitsSet);

    // testWorkList(changedUnits);

    // Set initial values for entry points
    {
      Iterator it = graph.getHeads().iterator();

      while (it.hasNext()) {
        Object s = it.next();

        // unitToBeforeFlow.put(s, entryInitialFlow());
        nodes.add(s);
        valueBefore.add(entryInitialFlow());
      }
    }

    // Perform fixed point flow analysis
    {
      Object previousAfterFlow = newInitialFlow();

      while (!changedUnits.isEmpty()) {
        Object beforeFlow;
        Object afterFlow;

        Object s = changedUnits.removeFirst();
        Tag tag = (Tag) ((JPegStmt) s).getTags().get(0);
        // System.out.println("===unit is: "+tag+" "+s);
        changedUnitsSet.remove(s);

        // copy(unitToAfterFlow.get(s), previousAfterFlow);
        // add for debug april 6
        int pos = nodes.indexOf(s);
        copy(valueAfter.elementAt(pos), previousAfterFlow);
        // end add for debug april
        // Compute and store beforeFlow
        {
          List preds = graph.getPredsOf(s);

          // beforeFlow = unitToBeforeFlow.get(s);

          beforeFlow = valueBefore.elementAt(pos);

          if (preds.size() == 1) {
            // copy(unitToAfterFlow.get(preds.get(0)), beforeFlow);
            copy(valueAfter.elementAt(nodes.indexOf(preds.get(0))), beforeFlow);
          } else if (preds.size() != 0) {
            Iterator predIt = preds.iterator();
            Object obj = predIt.next();

            // copy(unitToAfterFlow.get(obj), beforeFlow);
            copy(valueAfter.elementAt(nodes.indexOf(obj)), beforeFlow);

            while (predIt.hasNext()) {
              JPegStmt stmt = (JPegStmt) predIt.next();
              if (stmt.equals(obj)) {
                // System.out.println("!!!same object!!!");
                continue;
              }
              Tag tag1 = (Tag) stmt.getTags().get(0);
              // System.out.println("pred: "+tag1+" "+stmt);

              // Object otherBranchFlow = unitToAfterFlow.get(stmt);
              if (nodes.indexOf(stmt) >= 0) // RLH
              {
                Object otherBranchFlow = valueAfter.elementAt(nodes.indexOf(stmt));

                merge(beforeFlow, otherBranchFlow, beforeFlow);
              }
            }
          }
        }

        // Compute afterFlow and store it.
        {
          // afterFlow = unitToAfterFlow.get(s);
          afterFlow = valueAfter.elementAt(nodes.indexOf(s));
          flowThrough(beforeFlow, s, afterFlow);

          // unitToAfterFlow.put(s, afterFlow);
          valueAfter.set(nodes.indexOf(s), afterFlow);
          // System.out.println("update afterFlow nodes: "+s);
          // System.out.println("afterFlow: "+afterFlow);
          // ((MonitorSet)unitToAfterFlow.get(s)).test();

          numComputations++;
        }

        // Update queue appropriately

        if (!afterFlow.equals(previousAfterFlow)) {

          Iterator succIt = graph.getSuccsOf(s).iterator();

          while (succIt.hasNext()) {
            Object succ = succIt.next();

            if (!changedUnitsSet.contains(succ)) {
              changedUnits.addLast(succ);
              changedUnitsSet.add(succ);
              /*if (succ instanceof JPegStmt){
              Tag tag1 = (Tag)((JPegStmt)succ).getTags().get(0);

              System.out.println("add to worklist: "+tag1+" "+succ);
              }
              else
              System.out.println("add to worklist: "+succ);
              */
            }
          }
        }
      }
    }

    // G.v().out.println(graph.getBody().getMethod().getSignature() + " numNodes: " + numNodes +
    //    " numComputations: " + numComputations + " avg: " + Main.truncatedOf((double)
    // numComputations / numNodes, 2));

    Timers.v().totalFlowNodes += numNodes;
    Timers.v().totalFlowComputations += numComputations;
  }
  private static boolean internalAggregate(
      StmtBody body, Map<ValueBox, Zone> boxToZone, boolean onlyStackVars) {
    LocalUses localUses;
    LocalDefs localDefs;
    ExceptionalUnitGraph graph;
    boolean hadAggregation = false;
    Chain<Unit> units = body.getUnits();

    graph = new ExceptionalUnitGraph(body);
    localDefs = new SmartLocalDefs(graph, new SimpleLiveLocals(graph));
    localUses = new SimpleLocalUses(graph, localDefs);

    List<Unit> unitList = new PseudoTopologicalOrderer<Unit>().newList(graph, false);
    for (Unit u : unitList) {
      if (!(u instanceof AssignStmt)) continue;
      AssignStmt s = (AssignStmt) u;

      Value lhs = s.getLeftOp();
      if (!(lhs instanceof Local)) continue;
      Local lhsLocal = (Local) lhs;

      if (onlyStackVars && !lhsLocal.getName().startsWith("$")) continue;

      List<UnitValueBoxPair> lu = localUses.getUsesOf(s);
      if (lu.size() != 1) continue;

      UnitValueBoxPair usepair = lu.get(0);
      Unit use = usepair.unit;
      ValueBox useBox = usepair.valueBox;

      List<Unit> ld = localDefs.getDefsOfAt(lhsLocal, use);
      if (ld.size() != 1) continue;

      // Check to make sure aggregation pair in the same zone
      if (boxToZone.get(s.getRightOpBox()) != boxToZone.get(usepair.valueBox)) {
        continue;
      }

      /* we need to check the path between def and use */
      /* to see if there are any intervening re-defs of RHS */
      /* in fact, we should check that this path is unique. */
      /* if the RHS uses only locals, then we know what
      to do; if RHS has a method invocation f(a, b,
      c) or field access, we must ban field writes, other method
      calls and (as usual) writes to a, b, c. */

      boolean cantAggr = false;
      boolean propagatingInvokeExpr = false;
      boolean propagatingFieldRef = false;
      boolean propagatingArrayRef = false;
      ArrayList<FieldRef> fieldRefList = new ArrayList<FieldRef>();

      LinkedList<Value> localsUsed = new LinkedList<Value>();
      for (ValueBox vb : s.getUseBoxes()) {
        Value v = vb.getValue();
        if (v instanceof Local) localsUsed.add(v);
        else if (v instanceof InvokeExpr) propagatingInvokeExpr = true;
        else if (v instanceof ArrayRef) propagatingArrayRef = true;
        else if (v instanceof FieldRef) {
          propagatingFieldRef = true;
          fieldRefList.add((FieldRef) v);
        }
      }

      // look for a path from s to use in graph.
      // only look in an extended basic block, though.

      List<Unit> path = graph.getExtendedBasicBlockPathBetween(s, use);

      if (path == null) continue;

      Iterator<Unit> pathIt = path.iterator();

      // skip s.
      if (pathIt.hasNext()) pathIt.next();

      while (pathIt.hasNext() && !cantAggr) {
        Stmt between = (Stmt) (pathIt.next());

        if (between != use) {
          // Check for killing definitions

          for (ValueBox vb : between.getDefBoxes()) {
            Value v = vb.getValue();
            if (localsUsed.contains(v)) {
              cantAggr = true;
              break;
            }

            if (propagatingInvokeExpr || propagatingFieldRef || propagatingArrayRef) {
              if (v instanceof FieldRef) {
                if (propagatingInvokeExpr) {
                  cantAggr = true;
                  break;
                } else if (propagatingFieldRef) {
                  // Can't aggregate a field access if passing a definition of a field
                  // with the same name, because they might be aliased
                  for (FieldRef fieldRef : fieldRefList) {
                    if (((FieldRef) v).getField() == fieldRef.getField()) {
                      cantAggr = true;
                      break;
                    }
                  }
                }
              } else if (v instanceof ArrayRef) {
                if (propagatingInvokeExpr) {
                  // Cannot aggregate an invoke expr past an array write
                  cantAggr = true;
                  break;
                } else if (propagatingArrayRef) {
                  // cannot aggregate an array read past a write
                  // this is somewhat conservative
                  // (if types differ they may not be aliased)

                  cantAggr = true;
                  break;
                }
              }
            }
          }

          // Make sure not propagating past a {enter,exit}Monitor
          if (propagatingInvokeExpr && between instanceof MonitorStmt) cantAggr = true;
        }

        // Check for intervening side effects due to method calls
        if (propagatingInvokeExpr || propagatingFieldRef || propagatingArrayRef) {
          for (final ValueBox box : between.getUseBoxes()) {
            if (between == use && box == useBox) {
              // Reached use point, stop looking for
              // side effects
              break;
            }

            Value v = box.getValue();

            if (v instanceof InvokeExpr
                || (propagatingInvokeExpr && (v instanceof FieldRef || v instanceof ArrayRef))) {
              cantAggr = true;
              break;
            }
          }
        }
      }

      // we give up: can't aggregate.
      if (cantAggr) {
        continue;
      }
      /* assuming that the d-u chains are correct, */
      /* we need not check the actual contents of ld */

      Value aggregatee = s.getRightOp();

      if (usepair.valueBox.canContainValue(aggregatee)) {
        boolean wasSimpleCopy = isSimpleCopy(usepair.unit);
        usepair.valueBox.setValue(aggregatee);
        units.remove(s);
        hadAggregation = true;
        // clean up the tags. If s was not a simple copy, the new statement should get
        // the tags of s.
        // OK, this fix was wrong. The condition should not be
        // "If s was not a simple copy", but rather "If usepair.unit
        // was a simple copy". This way, when there's a load of a constant
        // followed by an invoke, the invoke gets the tags.
        if (wasSimpleCopy) {
          // usepair.unit.removeAllTags();
          usepair.unit.addAllTagsOf(s);
        }
      } else {
        /*
        if(Options.v().verbose())
        {
            G.v().out.println("[debug] failed aggregation");
              G.v().out.println("[debug] tried to put "+aggregatee+
                             " into "+usepair.stmt +
                             ": in particular, "+usepair.valueBox);
              G.v().out.println("[debug] aggregatee instanceof Expr: "
                             +(aggregatee instanceof Expr));
        }*/
      }
    }
    return hadAggregation;
  }