示例#1
0
 /** 删除选中的元素 */
 public void deleteSelectedCells() {
   if (!graph.isSelectionEmpty()) {
     Object[] cells = graph.getSelectionCells();
     cells = graph.getDescendants(cells);
     graph.getModel().remove(cells);
   }
 }
  /**
   * Creates a new instance.
   *
   * @param flowGraph the flow-graph which represents this flow-part structure
   * @param parameters the parameters for this flow-part
   * @throws IllegalArgumentException if some parameters were {@code null}
   * @since 0.5.0
   */
  public FlowPartDescription(FlowGraph flowGraph, List<? extends Parameter> parameters) {
    if (flowGraph == null) {
      throw new IllegalArgumentException("flowGraph must not be null"); // $NON-NLS-1$
    }
    if (parameters == null) {
      throw new IllegalArgumentException("parameters must not be null"); // $NON-NLS-1$
    }
    this.flowGraph = flowGraph;
    List<FlowElementPortDescription> inputs = new ArrayList<FlowElementPortDescription>();
    List<FlowElementPortDescription> outputs = new ArrayList<FlowElementPortDescription>();
    this.inputPorts = Collections.unmodifiableList(inputs);
    this.outputPorts = Collections.unmodifiableList(outputs);
    this.parameters = Collections.unmodifiableList(new ArrayList<Parameter>(parameters));

    for (FlowIn<?> in : flowGraph.getFlowInputs()) {
      inputs.add(
          new FlowElementPortDescription(
              in.getDescription().getName(),
              in.getDescription().getDataType(),
              PortDirection.INPUT));
    }
    for (FlowOut<?> out : flowGraph.getFlowOutputs()) {
      outputs.add(
          new FlowElementPortDescription(
              out.getDescription().getName(),
              out.getDescription().getDataType(),
              PortDirection.OUTPUT));
    }
  }
示例#3
0
 // Update Undo/Redo Button State based on Undo Manager
 protected void updateHistoryButtons() {
   // The View Argument Defines the Context
   editor.mainToolBar.setActionEnabled(
       MainActions.ACTION_UNDO, undoManager.canUndo(graph.getGraphLayoutCache()));
   editor.mainToolBar.setActionEnabled(
       MainActions.ACTION_REDO, undoManager.canRedo(graph.getGraphLayoutCache()));
 }
示例#4
0
  protected Node checkReachability(Term n) throws SemanticException {
    FlowGraph g = currentFlowGraph();
    if (g != null) {
      Collection peers = g.peers(n);
      if (peers != null && !peers.isEmpty()) {
        boolean isInitializer = (n instanceof Initializer);

        for (Iterator iter = peers.iterator(); iter.hasNext(); ) {
          FlowGraph.Peer p = (FlowGraph.Peer) iter.next();

          // the peer is reachable if at least one of its out items
          // is reachable. This would cover all cases, except that some
          // peers may have no successors (e.g. peers that throw an
          // an exception that is not caught by the method). So we need
          // to also check the inItem.
          if (p.inItem() != null) {
            DataFlowItem dfi = (DataFlowItem) p.inItem();
            // there will only be one peer for an initializer,
            // as it cannot occur in a finally block.
            if (isInitializer && !dfi.normalReachable) {
              throw new SemanticException(
                  "Initializers must be able to complete normally.", n.position());
            }

            if (dfi.reachable) {
              return n.reachable(true);
            }
          }

          if (p.outItems != null) {
            for (Iterator k = p.outItems.values().iterator(); k.hasNext(); ) {
              DataFlowItem item = (DataFlowItem) k.next();

              if (item != null && item.reachable) {
                // n is reachable.
                return n.reachable(true);
              }
            }
          }
        }

        // if we fall through to here, then no peer for n was reachable.
        n = n.reachable(false);

        // Compound statements are allowed to be unreachable
        // (e.g., "{ // return; }" or "while (true) S").  If a compound
        // statement is truly unreachable, one of its sub-statements will
        // be also and we will report an error there.

        if ((n instanceof Block && ((Block) n).statements().isEmpty())
            || (n instanceof Stmt && !(n instanceof CompoundStmt))) {
          throw new SemanticException("Unreachable statement.", n.position());
        }
      }
    }
    return n;
  }
示例#5
0
 /** 组合选中的元素 */
 public void groupSelectedCells() {
   Object[] cells = graph.getSelectionCells();
   // Order Cells by Model Layering
   cells = graph.order(cells);
   // If Any Cells in View
   if (cells != null && cells.length > 0) {
     DefaultGraphCell group = new DefaultGraphCell();
     // Insert into model
     graph.getGraphLayoutCache().insertGroup(group, cells);
   }
 }
 /**
  * この要素からの出力ポートに対する、フロー部品内部の出力ポートを返す。
  *
  * @param externalOutput この要素からの出力ポート
  * @return 対応するフロー部品内部の出力ポート
  * @throws IllegalArgumentException 引数に{@code null}が指定された場合
  */
 public FlowOut<?> getInternalOutputPort(FlowElementPortDescription externalOutput) {
   if (externalOutput == null) {
     throw new IllegalArgumentException("externalOutput must not be null"); // $NON-NLS-1$
   }
   assert outputPorts.size() == flowGraph.getFlowOutputs().size();
   int index = outputPorts.indexOf(externalOutput);
   if (index < 0) {
     throw new IllegalArgumentException();
   }
   return flowGraph.getFlowOutputs().get(index);
 }
示例#7
0
  /**
   * 重新设置流程图
   *
   * @param newGraph
   */
  public void setFlowGraph(FlowGraph newGraph) {
    if (newGraph == null) {
      if (graph != null) graph.getParent().remove(graph);
      this.graph = null;
      this.undoManager = null;

      this.updateUI();
      return;
    }
    if (this.graph != null) {
      scroller.remove(graph);
      // uninstallListeners(graph);
    }

    graph = newGraph;

    // 设置UnDoManager
    if (graph.getUndoManager() == null) {
      undoManager =
          new GraphUndoManager() {
            // Override Superclass
            public void undoableEditHappened(UndoableEditEvent e) {
              // First Invoke Superclass
              super.undoableEditHappened(e);
              // Then Update Undo/Redo Buttons
              updateHistoryButtons();
            }
          };
      graph.getModel().addUndoableEditListener(undoManager);
      graph.setUndoManager(undoManager);
    } else {
      undoManager = graph.getUndoManager();
    }

    graph.setMarqueeHandler(this.marqueeHandler);

    this.uninstallListeners(graph);
    this.installListeners(graph);

    scroller.setViewportView(graph);

    if (editor.mainToolBar != null) {
      // 更新工具条的状态,主要更新重做、撤销
      editor.mainToolBar.setActionEnabled(MainActions.ACTION_REDO, false);
      editor.mainToolBar.setActionEnabled(MainActions.ACTION_UNDO, false);
      // editor.mainToolBar.setActionEnabled(MainActions.ACTION_SAVE,
      // !graph.getGraphInfo().isDeployed());
      editor.mainToolBar.setActionEnabled(
          MainActions.ACTION_SAVE, graph.getGraphInfo().getValidStatus() == 0);
    }

    // 更新属性视图
    if (graph.getSelectionCount() == 0) {
      editor.propertiesView.resetProperties(graph.getGraphInfo().getProperties());
    }

    updateHistoryButtons();
  }
  /* (non-Javadoc)
   * @see edu.kit.ipd.wala.ExceptionPrunedCFG#getPruned(com.ibm.wala.ipa.callgraph.CGNode)
   */
  @Override
  public ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> getPruned(
      CGNode method, IProgressMonitor progress) throws UnsoundGraphException {
    FlowGraph graph = cg2graph.get(method);
    ExplodedControlFlowGraph origCfg = cg2origcfg.get(method);

    if (graph == null) {
      if (DEBUG) {
        String fileName = method.getMethod().getSignature();
        fileName = fileName.replace('/', '.');
        System.out.println("--- Starting " + fileName + " ---");

        MethodCFG mCFG = new MethodCFG(method, ignoreExceptions);
        if (mCFG.init(cache)) {
          mCFG.write(mCFG.getOriginalGraph(), "out/" + fileName + ".dot");
          System.out.println(
              "Exceptions in original graph: " + mCFG.getOriginalGraph().countExceptions());

          mCFG.purgeExceptions();

          graph = mCFG.getGraph();
          mCFG.write(graph, "out/" + fileName + ".filter.dot");
          System.out.println("Exceptions in final graph: " + graph.countExceptions());

          cg2graph.put(method, graph);
          origCfg = mCFG.getECFG();
          cg2origcfg.put(method, origCfg);
        }
      } else {
        MethodCFG mCFG = new MethodCFG(method, ignoreExceptions);
        if (mCFG.init(cache)) {
          mCFG.purgeExceptions();
          graph = mCFG.getGraph();
          cg2graph.put(method, graph);
          origCfg = mCFG.getECFG();
          cg2origcfg.put(method, origCfg);
        }
      }

      printDetails(method, origCfg, graph);
    }

    if (graph != null) {
      IgnoreEdgeListFilter filter = new IgnoreEdgeListFilter(origCfg, graph);
      PrunedCFG<SSAInstruction, IExplodedBasicBlock> pCFG = PrunedCFG.make(origCfg, filter);

      return pCFG;
    } else {
      return null;
    }
  }
示例#9
0
 public Item createInitialItem(FlowGraph graph, Term node) {
   if (node == graph.entryNode()) {
     return DataFlowItem.REACHABLE;
   } else {
     return DataFlowItem.NOT_REACHABLE;
   }
 }
 @Override
 public String getName() {
   if (name == null) {
     return flowGraph.getDescription().getSimpleName();
   }
   return name;
 }
  private static void printDetails(CGNode method, ExplodedControlFlowGraph cfg, FlowGraph pruned) {
    int deletedEdges = 0;
    int originalEdges = 0;
    for (IExplodedBasicBlock node : cfg) {
      originalEdges += cfg.getSuccNodeCount(node);

      Iterator<IExplodedBasicBlock> it = cfg.getSuccNodes(node);

      int srcNum = node.getNumber();
      while (it.hasNext()) {
        IExplodedBasicBlock dst = it.next();
        int dstNum = dst.getNumber();
        if (pruned.hasEdge(srcNum, dstNum)) {
          deletedEdges++;
        }
      }
    }

    DecimalFormat df = new DecimalFormat("00.00");

    double percent = ((double) deletedEdges / (double) originalEdges) * 100.0;
    Log.info(
        "EXC: "
            + df.format(percent)
            + "% - edges: "
            + originalEdges
            + " deleted: "
            + deletedEdges
            + " - "
            + edu.kit.joana.deprecated.jsdg.util.Util.methodName(method.getMethod()));
  }
示例#12
0
 public Item createInitialItem(FlowGraph graph, Term node, boolean entry) {
   if (node == graph.root() && entry) {
     return DataFlowItem.REACHABLE;
   } else {
     return DataFlowItem.NOT_REACHABLE;
   }
 }
示例#13
0
  public void graphChanged(GraphModelEvent e) {
    GraphModelChange change = e.getChange();
    // 检查是否增加了元素
    Object[] inserted = change.getInserted();
    if (inserted != null && inserted.length > 0) {
      // 更新结构树
      for (int i = 0; i < inserted.length; i++) {
        if (inserted[i] instanceof Port) {
          continue;
        } else if (inserted[i] instanceof Edge) {
          editor.strutcView.addFlowRoute(graph, (Edge) inserted[i]);
        } else if (inserted[i] instanceof GraphCell) {
          editor.strutcView.addFlowCell(graph, (GraphCell) inserted[i]);
        }
      }
    }
    // 检查是否删除了元素
    Object[] removed = change.getRemoved();
    if (removed != null && removed.length > 0) {
      // 更新结构树
      for (int i = 0; i < removed.length; i++) {
        if (removed[i] instanceof Edge) {
          editor.strutcView.removeFlowRoute(graph, (Edge) removed[i]);
        } else if (removed[i] instanceof GraphCell) {
          editor.strutcView.removeFlowCell(graph, (GraphCell) removed[i]);
        }
      }
    }
    // System.out.println("Model Event");

    // 记录该图形已经更改
    graph.setChanged(true);

    // 更新保存按钮
    editor.mainToolBar.setActionEnabled(
        MainActions.ACTION_SAVE, graph.getGraphInfo().getValidStatus() == 0);

    /*
     * if (!graph.getGraphInfo().isDeployed()) {
     * editor.mainToolBar.setActionEnabled(MainActions.ACTION_SAVE, true); }
     */
    // editor.mainToolBar.setActionEnabled(MainActions.ACTION_SAVEALL,
    // true);
  }
示例#14
0
  // From GraphSelectionListener Interface
  public void valueChanged(GraphSelectionEvent e) {

    // 设置工具条相关按钮的可用性
    editor.mainToolBar.setActionEnabled(MainActions.ACTION_GROUP, graph.getSelectionCount() > 1);
    // Update Button States based on Current Selection
    boolean enabled = !graph.isSelectionEmpty();
    editor.mainToolBar.setActionEnabled(MainActions.ACTION_DELETE, enabled);
    editor.mainToolBar.setActionEnabled(MainActions.ACTION_UNGROUP, enabled);
    editor.mainToolBar.setActionEnabled(MainActions.ACTION_TOFRONT, enabled);
    editor.mainToolBar.setActionEnabled(MainActions.ACTION_TOBACK, enabled);
    editor.mainToolBar.setActionEnabled(MainActions.ACTION_COPY, enabled);
    editor.mainToolBar.setActionEnabled(MainActions.ACTION_CUT, enabled);
    if (graph.getSelectionCount() > 0) {

      Object c = graph.getSelectionCell();
      if (c instanceof DefaultGraphCell) {
        DefaultGraphCell cell = (DefaultGraphCell) c;
        Object uo = cell.getUserObject();
        Rectangle2D rect = GraphConstants.getBounds(cell.getAttributes());
        if (rect != null) {
          editor.messageView.warn(
              "rect=" + rect.getX() + ":" + rect.getY() + rect.getWidth() + ":" + rect.getHeight());
        }

        if (uo instanceof FlowElementObject) {
          editor.propertiesView.resetProperties(((FlowElementObject) uo).getProperties());
        } else {
          // System.out.println("uo="+uo);
          undo();
          editor.messageView.warn("不能这样操作,请在操作左加的属性值");
          // System.out.println("不能这样操作");
          // editor.propertiesView.resetProperties(null);
        }
      } else {
        undo();
        // editor.propertiesView.resetProperties(null);
        editor.messageView.warn("不能这样操作,操作对像,不能识别" + c.getClass().getName());
      }

    } else {
      editor.propertiesView.resetProperties(graph.getGraphInfo().getProperties());
    }
    // System.out.println("Change");
  }
示例#15
0
  protected Node checkReachability(Term n) {
    FlowGraph g = currentFlowGraph();
    if (g != null) {
      Collection<FlowGraph.Peer> peers = g.peers(n, Term.EXIT);
      if (peers != null && !peers.isEmpty()) {
        boolean isInitializer = (n instanceof Initializer);

        for (FlowGraph.Peer p : peers) {
          // the peer is reachable if at least one of its out items
          // is reachable. This would cover all cases, except that some
          // peers may have no successors (e.g. peers that throw an
          // an exception that is not caught by the method). So we need
          // to also check the inItem.
          if (p.inItem() != null) {
            DataFlowItem dfi = (DataFlowItem) p.inItem();
            // there will only be one peer for an initializer,
            // as it cannot occur in a finally block.
            if (isInitializer && !dfi.normalReachable) {
              reportError(new Errors.InitializersMustCompleteNormally(n.position()));
            }

            if (dfi.reachable) {
              return n.reachable(true);
            }
          }

          if (p.outItems != null) {
            for (Item v : p.outItems.values()) {
              DataFlowItem item = (DataFlowItem) v;

              if (item != null && item.reachable) {
                // n is reachable.
                return n.reachable(true);
              }
            }
          }
        }

        // if we fall through to here, then no peer for n was reachable.
        n = n.reachable(false);
      }
    }
    return n;
  }
示例#16
0
 /** 重做上一步 */
 public void redo() {
   if (undoManager == null) return;
   try {
     undoManager.redo(graph.getGraphLayoutCache());
   } catch (Exception ex) {
     System.err.println(ex);
   } finally {
     updateHistoryButtons();
   }
 }
示例#17
0
  /**
   * 连接两个Port
   *
   * @param source
   * @param target
   */
  public void connect(Port source, Port target) {
    for (Iterator it = source.edges(); it.hasNext(); ) {
      Edge e = (Edge) it.next();
      if (e.getTarget() == target) {
        this.repaint();
        return;
      }
    }
    // Construct Edge with no label
    DefaultEdge edge = new DefaultEdge();
    if (graph.getModel().acceptsSource(edge, source)
        && graph.getModel().acceptsTarget(edge, target)) {

      edge.setUserObject(new FlowEdgeObject(edge));
      // Create a Map thath holds the attributes for the edge
      edge.getAttributes().applyMap(createEdgeAttributes());
      // Insert the Edge and its Attributes
      graph.getGraphLayoutCache().insertEdge(edge, source, target);

      // 添加到树结构
      // editor.strutcView.addFlowRoute(graph, edge);
    }
  }
示例#18
0
  /**
   * Check that the conditions of initialization are not broken.
   *
   * <p>To summarize the conditions: - Local variables must be initialized before use, (i.e. min
   * count > 0) - Final local variables (including Formals) cannot be assigned to more than once
   * (i.e. max count <= 1) - Final non-static fields whose target is this cannot be assigned to more
   * than once - Final static fields whose target is the current class cannot be assigned to more
   * than once
   *
   * <p>This method is also responsible for maintaining state between the dataflows over
   * Initializers, by copying back the appropriate MinMaxInitCounts to the map
   * currClassFinalFieldInitCounts.
   */
  public void check(FlowGraph graph, Term n, Item inItem, Map outItems) throws SemanticException {
    DataFlowItem dfIn = (DataFlowItem) inItem;
    if (dfIn == null) {
      // There is no input data flow item. This can happen if we are
      // checking an unreachable term, and so no Items have flowed
      // through the term. For example, in the code fragment:
      //     a: do { break a; } while (++i < 10);
      // the expression "++i < 10" is unreachable, but the as there is
      // no unreachable statement, the Java Language Spec permits it.

      // Set inItem to a default Item
      dfIn = createInitDFI();
    }

    DataFlowItem dfOut = null;
    if (outItems != null && !outItems.isEmpty()) {
      // due to the flow equations, all DataFlowItems in the outItems map
      // are the same, so just take the first one.
      dfOut = (DataFlowItem) outItems.values().iterator().next();
    }

    if (n instanceof Local) {
      checkLocal(graph, (Local) n, dfIn, dfOut);
    } else if (n instanceof LocalAssign) {
      checkLocalAssign(graph, (LocalAssign) n, dfIn, dfOut);
    } else if (n instanceof FieldAssign) {
      checkFieldAssign(graph, (FieldAssign) n, dfIn, dfOut);
    } else if (n instanceof ClassBody) {
      // we need to check that the locals used inside this class body
      // have all been defined at this point.
      Set localsUsed = (Set) currCBI.localsUsedInClassBodies.get(n);

      if (localsUsed != null) {
        checkLocalsUsedByInnerClass(graph, (ClassBody) n, localsUsed, dfIn, dfOut);
      }
    }

    if (n == graph.finishNode()) {
      if (currCBI.currCodeDecl instanceof Initializer) {
        finishInitializer(graph, (Initializer) currCBI.currCodeDecl, dfIn, dfOut);
      }
      if (currCBI.currCodeDecl instanceof ConstructorDecl) {
        finishConstructorDecl(graph, (ConstructorDecl) currCBI.currCodeDecl, dfIn, dfOut);
      }
    }
  }
 public boolean hasNormalEdge(IExplodedBasicBlock src, IExplodedBasicBlock dst) {
   return finalGraph.hasEdge(src.getNumber(), dst.getNumber());
 }
示例#20
0
 /** 缩小 */
 public void zoomOut() {
   graph.setScale(graph.getScale() / 1.5);
 }
示例#21
0
 /** 将选中的元素往上一层 */
 public void toFront() {
   graph.getGraphLayoutCache().toFront(graph.getSelectionCells());
 }
示例#22
0
 /** 取消元素的组合 */
 public void ungroupSelectedCells() {
   graph.getGraphLayoutCache().ungroup(graph.getSelectionCells());
 }
示例#23
0
 /** 将选中的元素往下一层 */
 public void toBack() {
   graph.getGraphLayoutCache().toBack(graph.getSelectionCells());
 }
示例#24
0
 /**
  * The initial item to be given to the entry point of the dataflow contains the init counts for
  * the final fields.
  */
 public Item createInitialItem(FlowGraph graph, Term node) {
   if (node == graph.startNode()) {
     return createInitDFI();
   }
   return BOTTOM;
 }
示例#25
0
 /** 放大 */
 public void zoomIn() {
   graph.setScale(graph.getScale() * 1.5);
 }
示例#26
0
  /** Runs BLOAT on a method. */
  public static void bloatMethod(final MethodEditor m, final BloatContext context) {
    try {
      if (Main.COMPACT_ARRAY_INIT) {
        // Compact the initialization of arrays of the basic types by
        // putting the values of the array into a string in the constant
        // pool. The initialization code is replaced with a loop that
        // loads the array from the string in the constant pool.

        if (Main.TRACE) {
          System.out.println("  Compacting Arrays: " + Main.dateFormat.format(new Date()));
        }

        CompactArrayInitializer.transform(m);

        if (Main.DEBUG) {
          System.out.println("---------- After compaction:");
          m.print(System.out);
          System.out.println("---------- end print");
        }
      }

      FlowGraph cfg; // The control flow graph for a method

      if (Main.TRACE) {
        System.out.println("  Constructing CFG: " + Main.dateFormat.format(new Date()));
      }

      try {
        // Construct the control flow graph for method m
        cfg = new FlowGraph(m);
      } catch (final ClassFormatException ex) {
        System.err.println(ex.getMessage());
        context.release(m.methodInfo());
        return;
      }

      // We separate out initialization since before this the FlowGraph
      // more exactly represents the input program.
      cfg.initialize();

      if (Main.TRACE) {
        System.out.println("  Transforming to SSA: " + Main.dateFormat.format(new Date()));
      }

      SSA.transform(cfg);

      if (FlowGraph.DEBUG) {
        System.out.println("---------- After SSA:");
        cfg.print(System.out);
        System.out.println("---------- end print");
      }

      if (Main.DEBUG) {
        cfg.visit(new VerifyCFG(false));
      }

      if (!Tree.USE_STACK) {
        // Do copy propagation and value numbering first to get rid of
        // all the extra copies inserted for dups. If they're left in,
        // it really slows down value numbering.
        if (Main.PROP) {
          if (Main.DEBUG) {
            System.out.println("-----Before Copy Propagation-----");
          }

          if (Main.TRACE) {
            System.out.println("  Copy propagation: " + Main.dateFormat.format(new Date()));
          }

          final ExprPropagation copy = new ExprPropagation(cfg);
          copy.transform();

          if (Main.DEBUG) {
            cfg.visit(new VerifyCFG(false));
          }

          if (Main.DEBUG) {
            System.out.println("------After Copy Propagation-----");
            cfg.print(System.out);
          }
        }
      }

      DeadCodeElimination dce = null;

      if (Main.DCE) {

        if (Main.TRACE) {
          System.out.println("  Dead Code Elimination: " + Main.dateFormat.format(new Date()));
        }

        if (Main.DEBUG) {
          System.out.println("---Before Dead Code Elimination--");
        }

        dce = new DeadCodeElimination(cfg);
        dce.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG(false));
        }

        if (Main.DEBUG) {
          System.out.println("---After Dead Code Elimination---");
          cfg.print(System.out);
        }
      }

      if (Main.INFER) {

        if (Main.DEBUG) {
          System.out.println("---------Doing type inference--------");
        }

        if (Main.TRACE) {
          System.out.println("  Type Inferencing: " + Main.dateFormat.format(new Date()));
        }

        TypeInference.transform(cfg, context.getHierarchy());
      }

      if (Main.NUMBER) {

        if (Main.TRACE) {
          System.out.println("  Value Numbering: " + Main.dateFormat.format(new Date()));
        }

        if (Main.DEBUG) {
          System.out.println("--------Doing value numbering--------");
        }

        (new ValueNumbering()).transform(cfg);
      }

      if (Main.FOLD) {
        if (Main.DEBUG) {
          System.out.println("--------Before Value Folding---------");
        }

        if (Main.TRACE) {
          System.out.println("  Value Folding: " + Main.dateFormat.format(new Date()));
        }

        (new ValueFolding()).transform(cfg);

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("---------After Value Folding---------");
          cfg.print(System.out);
        }
      }

      if (Main.PRE) {
        if (Main.DEBUG) {
          System.out.println("-------------Before SSAPRE-----------");
        }

        if (Main.TRACE) {
          System.out.println("  SSAPRE: " + Main.dateFormat.format(new Date()));
        }

        final SSAPRE pre = new SSAPRE(cfg, context);
        pre.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("-------------After SSAPRE------------");
          cfg.print(System.out);
        }
      }

      if (Main.FOLD) {
        if (Main.DEBUG) {
          System.out.println("--------Before Value Folding---------");
        }

        if (Main.TRACE) {
          System.out.println("  Value Folding: " + Main.dateFormat.format(new Date()));
        }

        (new ValueFolding()).transform(cfg);

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("---------After Value Folding---------");
          cfg.print(System.out);
        }
      }

      if (Main.PROP) {
        if (Main.DEBUG) {
          System.out.println("-------Before Copy Propagation-------");
        }

        if (Main.TRACE) {
          System.out.println("  Copy Propagation " + Main.dateFormat.format(new Date()));
        }

        final ExprPropagation copy = new ExprPropagation(cfg);
        copy.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("--------After Copy Propagation-------");
          cfg.print(System.out);
        }
      }

      // make sure we've done at least one thing since the last DCE
      if (Main.DCE && (Main.INFER || Main.NUMBER || Main.FOLD || Main.PRE || Main.PROP)) {
        if (Main.DEBUG) {
          System.out.println("-----Before Dead Code Elimination----");
        }

        if (Main.TRACE) {
          System.out.println("  Dead Code Elimination: " + Main.dateFormat.format(new Date()));
        }

        dce = new DeadCodeElimination(cfg);
        dce.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("-----After Dead Code Elimination-----");
          cfg.print(System.out);
        }
      }

      if (Main.PERSIST) {
        (new PersistentCheckElimination()).transform(cfg);
      }

      if (Main.DIVA) {
        if (Main.DEBUG) {
          System.out.println("-----Before DIVA------");
        }

        if (Main.TRACE) {
          System.out.println("  DIVA: " + Main.dateFormat.format(new Date()));
        }

        (new InductionVarAnalyzer()).transform(cfg);

        if (Main.DEBUG) {
          System.out.println("-----After DIVA-----");
          cfg.print(System.out);
        }
      }

      /*
       * if (STACK_ALLOC) { if (DEBUG) {
       * System.out.println("------------Before StackPRE----------"); }
       *
       * StackPRE pre = new StackPRE(cfg); pre.transform();
       *
       * if (DEBUG) { cfg.visit(new VerifyCFG()); }
       *
       * if (DEBUG) { System.out.println("------------After
       * StackPRE-----------"); cfg.print(System.out); } }
       */

      // Do the new stack optimization
      if (Main.OPT_STACK_2) {

        if (Main.TRACE) {
          System.out.println("  New stack optimization: " + Main.dateFormat.format(new Date()));
        }

        // generate code without doing liveness or register allocation
        final CodeGenerator codegen = new CodeGenerator(m);
        codegen.replacePhis(cfg);
        m.clearCode2();
        cfg.visit(codegen);
        // do stack optimization on the bytecode

        final StackOpt so = new StackOpt();
        so.transform(m);

        // convert it back to a cfg
        cfg = new FlowGraph(m);
        cfg.initialize();

        // convert it back to SSA
        SSA.transform(cfg);

        // do more dead code elimination (eliminate stores)
        dce = new DeadCodeElimination(cfg);
        dce.transform();
      }

      if (Main.TRACE) {
        System.out.println("  Register allocation: " + Main.dateFormat.format(new Date()));
      }

      if (Main.VERIFY) {
        try {
          cfg.visit(new VerifyCFG());
        } catch (final IllegalArgumentException ee) {
          System.out.println(
              " NOTE: CFG did not verify while "
                  + "bloating "
                  + m.name()
                  + " after all optimizations. Exception: "
                  + ee);
        }
      }

      // We're all done performing optimizations. Let's generate some code
      // and go home.

      // Perform liveness analysis of variables in the method.
      // Assign local variables ("registers") to expression values.
      final Liveness liveness = new Liveness(cfg);
      final RegisterAllocator alloc = new RegisterAllocator(cfg, liveness);

      // Gather information which can be used to optimize use of the stack
      if (CodeGenerator.OPT_STACK) {
        if (Main.TRACE) {
          System.out.println("  Old stack optimization: " + Main.dateFormat.format(new Date()));
        }
        StackOptimizer.optimizeCFG(cfg);
      }

      if (Main.TRACE) {
        System.out.println("  Code Generation: " + Main.dateFormat.format(new Date()));
      }

      // Start the code generation process.
      final CodeGenerator codegen = new CodeGenerator(m);
      codegen.replacePhis(cfg);

      if (Main.DEBUG) {
        System.out.println("After fixing Phis------------------------");
        cfg.print(System.out);
        System.out.println("End print--------------------------------");
      }

      codegen.simplifyControlFlow(cfg);
      codegen.allocReturnAddresses(cfg, alloc);

      if (Main.DEBUG) {
        System.out.println("After removing empty blocks--------------");
        cfg.print(System.out);
        System.out.println("End print--------------------------------");
      }

      // Clear the old contents of the bytecode store and generate new
      // code.
      // Code is generated using a visitor pattern on the CFG.
      m.clearCode();
      cfg.visit(codegen);

      Peephole.transform(m);

      // Commit any changes that have been made to the method
      context.commit(m.methodInfo());

    } catch (final Exception ex99) {
      final String msg =
          "** Exception while optimizing "
              + m.name()
              + m.type()
              + " of class "
              + m.declaringClass().name();
      System.err.println(msg);
      System.err.println(ex99.getMessage());
      ex99.printStackTrace(System.err);
      System.exit(1);
    }
  }
示例#27
0
  public static void main(String[] args) {
    FlowGraph f = new FlowGraph();

    // Create oscil unit

    Unit oscil = new Unit();

    oscil.setCode("$aout oscil3 $amp, $kpch, $itable");

    PortList ins = oscil.getInputs();
    PortList outs = oscil.getOutputs();

    Port iamp = new Port();
    iamp.name = "amp";
    iamp.rate = Port.K_RATE;

    Port kpch = new Port();
    kpch.name = "kpch";
    kpch.rate = Port.K_RATE;

    Port itable = new Port();
    itable.name = "itable";
    itable.rate = Port.I_RATE;

    ins.addPort(iamp);
    ins.addPort(kpch);
    ins.addPort(itable);

    Port aout = new Port();
    aout.name = "aout";
    aout.rate = Port.A_RATE;

    outs.addPort(aout);

    // Create Out Unit
    Unit out = new Unit();
    out.setCode("outs $aleft, $aright");

    ins = out.getInputs();

    Port aleft = new Port();
    aleft.name = "aleft";
    aleft.rate = Port.A_RATE;

    Port aright = new Port();
    aright.name = "aright";
    aright.rate = Port.A_RATE;

    ins.addPort(aleft);
    ins.addPort(aright);

    // add to FlowGraph

    GraphUnit gOscil = new GraphUnit();
    gOscil.coordinate = new Point2D.Double(0, 0);
    gOscil.unit = oscil;

    GraphUnit gOut = new GraphUnit();
    gOut.coordinate = new Point2D.Double(1, 1);
    gOut.unit = out;

    f.addGraphUnit(gOscil);
    f.addGraphUnit(gOut);

    Cable cLeft = new Cable(gOscil, 0, gOut, 0, 0);
    Cable cRight = new Cable(gOscil, 0, gOut, 1, 0);

    f.addCable(cLeft);
    f.addCable(cRight);

    System.out.println(f.generateInstrument());
  }
示例#28
0
 /** 缩放为实际大小 */
 public void zoom() {
   graph.setScale(1.0);
 }