com.google.javascript.jscomp.graph.DiGraph.DiGraphNode Java Examples

The following examples show how to use com.google.javascript.jscomp.graph.DiGraph.DiGraphNode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ControlFlowAnalysisTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Asserts the priority order of CFG nodes.
 *
 * Checks that the node type of the highest-priority node matches the
 * first element of the list, the type of the second node matches the
 * second element of the list, and so on.
 *
 * @param cfg The control flow graph.
 * @param nodeTypes The expected node types, in order.
 */
private void assertNodeOrder(ControlFlowGraph<Node> cfg,
    List<Integer> nodeTypes) {
  List<DiGraphNode<Node, Branch>> cfgNodes =
      Lists.newArrayList(cfg.getDirectedGraphNodes());
  Collections.sort(cfgNodes, cfg.getOptionalNodeComparator(true));

  // IMPLICIT RETURN must always be last.
  Node implicitReturn = cfgNodes.remove(cfgNodes.size() - 1).getValue();
  assertNull(implicitReturn == null ? "null" : implicitReturn.toStringTree(),
      implicitReturn);

  assertEquals("Wrong number of CFG nodes",
      nodeTypes.size(), cfgNodes.size());
  for (int i = 0; i < cfgNodes.size(); i++) {
    int expectedType = nodeTypes.get(i);
    int actualType = cfgNodes.get(i).getValue().getType();
    assertEquals(
        "node type mismatch at " + i + ".\n" +
        "found   : " + Token.name(actualType) + "\n" +
        "required: " + Token.name(expectedType) + "\n",
        expectedType, actualType);
  }
}
 
Example #2
Source File: Closure_14_ControlFlowAnalysis_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given an entry node, find all the nodes reachable from that node
 * and prioritize them.
 */
private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
  PriorityQueue<DiGraphNode<Node, Branch>> worklist =
      new PriorityQueue<DiGraphNode<Node, Branch>>(10, priorityComparator);
  worklist.add(entry);

  while (!worklist.isEmpty()) {
    DiGraphNode<Node, Branch> current = worklist.remove();
    if (nodePriorities.containsKey(current)) {
      continue;
    }

    nodePriorities.put(current, ++priorityCounter);

    List<DiGraphNode<Node, Branch>> successors =
        cfg.getDirectedSuccNodes(current);
    for (DiGraphNode<Node, Branch> candidate : successors) {
      worklist.add(candidate);
    }
  }
}
 
Example #3
Source File: Closure_14_ControlFlowAnalysis_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given an entry node, find all the nodes reachable from that node
 * and prioritize them.
 */
private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
  PriorityQueue<DiGraphNode<Node, Branch>> worklist =
      new PriorityQueue<DiGraphNode<Node, Branch>>(10, priorityComparator);
  worklist.add(entry);

  while (!worklist.isEmpty()) {
    DiGraphNode<Node, Branch> current = worklist.remove();
    if (nodePriorities.containsKey(current)) {
      continue;
    }

    nodePriorities.put(current, ++priorityCounter);

    List<DiGraphNode<Node, Branch>> successors =
        cfg.getDirectedSuccNodes(current);
    for (DiGraphNode<Node, Branch> candidate : successors) {
      worklist.add(candidate);
    }
  }
}
 
Example #4
Source File: 1_ControlFlowAnalysis.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given an entry node, find all the nodes reachable from that node
 * and prioritize them.
 */
private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
  PriorityQueue<DiGraphNode<Node, Branch>> worklist =
      new PriorityQueue<DiGraphNode<Node, Branch>>(10, priorityComparator);
  worklist.add(entry);

  while (!worklist.isEmpty()) {
    DiGraphNode<Node, Branch> current = worklist.remove();
    if (nodePriorities.containsKey(current)) {
      continue;
    }

    nodePriorities.put(current, ++priorityCounter);

    List<DiGraphNode<Node, Branch>> successors =
        cfg.getDirectedSuccNodes(current);
    for (DiGraphNode<Node, Branch> candidate : successors) {
      worklist.add(candidate);
    }
  }
}
 
Example #5
Source File: 1_ControlFlowAnalysis.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given an entry node, find all the nodes reachable from that node
 * and prioritize them.
 */
private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
  PriorityQueue<DiGraphNode<Node, Branch>> worklist =
      new PriorityQueue<DiGraphNode<Node, Branch>>(10, priorityComparator);
  worklist.add(entry);

  while (!worklist.isEmpty()) {
    DiGraphNode<Node, Branch> current = worklist.remove();
    if (nodePriorities.containsKey(current)) {
      continue;
    }

    nodePriorities.put(current, ++priorityCounter);

    List<DiGraphNode<Node, Branch>> successors =
        cfg.getDirectedSuccNodes(current);
    for (DiGraphNode<Node, Branch> candidate : successors) {
      worklist.add(candidate);
    }
  }
}
 
Example #6
Source File: Closure_127_UnreachableCodeElimination_t.java    From coming with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (parent == null || n.isFunction() || n.isScript()) {
    return;
  }
  DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
  if (gNode == null) { // Not in CFG.
    return;
  }
  if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
      (removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n, compiler))) {
    removeDeadExprStatementSafely(n);
    return;
  }
  tryRemoveUnconditionalBranching(n);
}
 
Example #7
Source File: Closure_127_UnreachableCodeElimination_s.java    From coming with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (parent == null || n.isFunction() || n.isScript()) {
    return;
  }
  DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
  if (gNode == null) { // Not in CFG.
    return;
  }
  if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
      (removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n, compiler))) {
    removeDeadExprStatementSafely(n);
    return;
  }
  tryRemoveUnconditionalBranching(n);
}
 
Example #8
Source File: Closure_85_UnreachableCodeElimination_t.java    From coming with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (parent == null) {
    return;
  }
  if (n.getType() == Token.FUNCTION || n.getType() == Token.SCRIPT) {
    return;
  }

  DiGraphNode<Node, Branch> gNode = curCfg.getDirectedGraphNode(n);
  if (gNode == null) { // Not in CFG.
    return;
  }
  if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
      (removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n))) {
    removeDeadExprStatementSafely(n);
    return;
  }

  tryRemoveUnconditionalBranching(n);
}
 
Example #9
Source File: Closure_85_UnreachableCodeElimination_s.java    From coming with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (parent == null) {
    return;
  }
  if (n.getType() == Token.FUNCTION || n.getType() == Token.SCRIPT) {
    return;
  }

  DiGraphNode<Node, Branch> gNode = curCfg.getDirectedGraphNode(n);
  if (gNode == null) { // Not in CFG.
    return;
  }
  if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
      (removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n))) {
    removeDeadExprStatementSafely(n);
    return;
  }

  tryRemoveUnconditionalBranching(n);
}
 
Example #10
Source File: Closure_103_ControlFlowAnalysis_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given an entry node, find all the nodes reachable from that node
 * and prioritize them.
 */
private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
  PriorityQueue<DiGraphNode<Node, Branch>> worklist =
      new PriorityQueue<DiGraphNode<Node, Branch>>(10, priorityComparator);
  worklist.add(entry);

  while (!worklist.isEmpty()) {
    DiGraphNode<Node, Branch> current = worklist.remove();
    if (nodePriorities.containsKey(current)) {
      continue;
    }

    nodePriorities.put(current, ++priorityCounter);

    List<DiGraphNode<Node, Branch>> successors =
        cfg.getDirectedSuccNodes(current);
    for (DiGraphNode<Node, Branch> candidate : successors) {
      worklist.add(candidate);
    }
  }
}
 
Example #11
Source File: Closure_103_ControlFlowAnalysis_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given an entry node, find all the nodes reachable from that node
 * and prioritize them.
 */
private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
  PriorityQueue<DiGraphNode<Node, Branch>> worklist =
      new PriorityQueue<DiGraphNode<Node, Branch>>(10, priorityComparator);
  worklist.add(entry);

  while (!worklist.isEmpty()) {
    DiGraphNode<Node, Branch> current = worklist.remove();
    if (nodePriorities.containsKey(current)) {
      continue;
    }

    nodePriorities.put(current, ++priorityCounter);

    List<DiGraphNode<Node, Branch>> successors =
        cfg.getDirectedSuccNodes(current);
    for (DiGraphNode<Node, Branch> candidate : successors) {
      worklist.add(candidate);
    }
  }
}
 
Example #12
Source File: UnreachableCodeElimination.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (parent == null) {
    return;
  }
  if (n.isFunction() || n.isScript()) {
    return;
  }

  DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
  if (gNode == null) { // Not in CFG.
    return;
  }
  if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
      (removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n, compiler))) {
    removeDeadExprStatementSafely(n);
    return;
  }

  tryRemoveUnconditionalBranching(n);
}
 
Example #13
Source File: NameReferenceGraphReport.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public int compare(DiGraphNode<Name, Reference> node1,
    DiGraphNode<Name, Reference> node2) {
  Preconditions.checkNotNull(node1.getValue());
  Preconditions.checkNotNull(node2.getValue());

  if ((node1.getValue().getQualifiedName() == null) &&
      (node2.getValue().getQualifiedName() == null)) {
    return 0;
  }

  // Node 1, if null, comes before node 2.
  if (node1.getValue().getQualifiedName() == null) {
    return -1;
  }

  // Node 2, if null, comes before node 1.
  if (node2.getValue().getQualifiedName() == null) {
    return 1;
  }

  return node1.getValue().getQualifiedName().compareTo(
      node2.getValue().getQualifiedName());
}
 
Example #14
Source File: DataFlowAnalysis.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void initialize() {
  orderedWorkSet.clear();
  for (DiGraphNode<N, Branch> node : getCfg().getDirectedGraphNodes()) {
    int outEdgeCount = getCfg().getOutEdges(node.getValue()).size();
    List<L> outLattices = Lists.newArrayList();
    for (int i = 0; i < outEdgeCount; i++) {
      outLattices.add(createInitialEstimateLattice());
    }
    node.setAnnotation(new BranchedFlowState<L>(
        createInitialEstimateLattice(), outLattices));
    if (node != getCfg().getImplicitReturn()) {
      orderedWorkSet.add(node);
    }
  }
}
 
Example #15
Source File: DataFlowAnalysis.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void joinInputs(DiGraphNode<N, Branch> node) {
  BranchedFlowState<L> state = node.getAnnotation();
  List<DiGraphNode<N, Branch>> predNodes =
      getCfg().getDirectedPredNodes(node);
  List<L> values = new ArrayList<L>(predNodes.size());

  for (DiGraphNode<N, Branch> predNode : predNodes) {
    BranchedFlowState<L> predNodeState = predNode.getAnnotation();

    L in = predNodeState.out.get(
        getCfg().getDirectedSuccNodes(predNode).indexOf(node));

    values.add(in);
  }
  if (getCfg().getEntry() == node) {
    state.setIn(createEntryLattice());
  } else if (!values.isEmpty()) {
    state.setIn(joinOp.apply(values));
  }
}
 
Example #16
Source File: InstrumentFunctions.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @returns true if all paths from block must exit with an explicit return.
 */
private boolean allPathsReturn(Node block) {
  // Computes the control flow graph.
  ControlFlowAnalysis cfa = new ControlFlowAnalysis(
      compiler, false, false);
  cfa.process(null, block);
  ControlFlowGraph<Node> cfg = cfa.getCfg();

  Node returnPathsParent = cfg.getImplicitReturn().getValue();
  for (DiGraphNode<Node, Branch> pred :
    cfg.getDirectedPredNodes(returnPathsParent)) {
    Node n = pred.getValue();
    if (!n.isReturn()) {
      return false;
    }
  }
  return true;
}
 
Example #17
Source File: ControlFlowAnalysis.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given an entry node, find all the nodes reachable from that node
 * and prioritize them.
 */
private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
  PriorityQueue<DiGraphNode<Node, Branch>> worklist =
      new PriorityQueue<DiGraphNode<Node, Branch>>(10, priorityComparator);
  worklist.add(entry);

  while (!worklist.isEmpty()) {
    DiGraphNode<Node, Branch> current = worklist.remove();
    if (nodePriorities.containsKey(current)) {
      continue;
    }

    nodePriorities.put(current, ++priorityCounter);

    List<DiGraphNode<Node, Branch>> successors =
        cfg.getDirectedSuccNodes(current);
    for (DiGraphNode<Node, Branch> candidate : successors) {
      worklist.add(candidate);
    }
  }
}
 
Example #18
Source File: CheckPathsBetweenNodesTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Tests a graph with many valid paths. */
public void testManyValidPaths() {
  DiGraph<String, String> g = LinkedDirectedGraph.create();
  g.createDirectedGraphNode("a");
  g.createDirectedGraphNode("b");
  g.createDirectedGraphNode("c1");
  g.createDirectedGraphNode("c2");
  g.createDirectedGraphNode("c3");
  DiGraphNode<String, String> d = g.createDirectedGraphNode("d");

  g.connect("a",  "-", "b");
  g.connect("b",  "-", "c1");
  g.connect("b",  "-", "c2");
  g.connect("c2", "-", "d");
  g.connect("c1", "-", "d");
  g.connect("a",  "-", "c3");
  g.connect("c3", "-", "d");

  assertGood(createTest(g, "a", "d", new PrefixPredicate("c"), ALL_EDGE));
}
 
Example #19
Source File: DataFlowAnalysis.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the lattice element at the exit point. Needs to be overridden
 * because we use a BranchedFlowState instead of a FlowState; ugh.
 */
@Override
L getExitLatticeElement() {
  DiGraphNode<N, Branch> node = getCfg().getImplicitReturn();
  BranchedFlowState<L> state = node.getAnnotation();
  return state.getIn();
}
 
Example #20
Source File: DataFlowAnalysis.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Finds a fixed-point solution. The function has the side effect of replacing
 * the existing node annotations with the computed solutions using {@link
 * com.google.javascript.jscomp.graph.GraphNode#setAnnotation(Annotation)}.
 *
 * <p>Initially, each node's input and output flow state contains the value
 * given by {@link #createInitialEstimateLattice()} (with the exception of the
 * entry node of the graph which takes on the {@link #createEntryLattice()}
 * value. Each node will use the output state of its predecessor and compute a
 * output state according to the instruction. At that time, any nodes that
 * depends on the node's newly modified output value will need to recompute
 * their output state again. Each step will perform a computation at one node
 * until no extra computation will modify any existing output state anymore.
 *
 * @param maxSteps Max number of iterations before the method stops and throw
 *        a {@link MaxIterationsExceededException}. This will prevent the
 *        analysis from going into a infinite loop.
 */
final void analyze(int maxSteps) {
  initialize();
  int step = 0;
  while (!orderedWorkSet.isEmpty()) {
    if (step > maxSteps) {
      throw new MaxIterationsExceededException(
        "Analysis did not terminate after " + maxSteps + " iterations");
    }
    DiGraphNode<N, Branch> curNode = orderedWorkSet.iterator().next();
    orderedWorkSet.remove(curNode);
    joinInputs(curNode);
    if (flow(curNode)) {
      // If there is a change in the current node, we want to grab the list
      // of nodes that this node affects.
      List<DiGraphNode<N, Branch>> nextNodes = isForward() ?
          cfg.getDirectedSuccNodes(curNode) :
          cfg.getDirectedPredNodes(curNode);
      for (DiGraphNode<N, Branch> nextNode : nextNodes) {
        if (nextNode != cfg.getImplicitReturn()) {
          orderedWorkSet.add(nextNode);
        }
      }
    }
    step++;
  }
  if (isForward()) {
    joinInputs(getCfg().getImplicitReturn());
  }
}
 
Example #21
Source File: DataFlowAnalysis.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected final boolean flow(DiGraphNode<N, Branch> node) {
  BranchedFlowState<L> state = node.getAnnotation();
  List<L> outBefore = state.out;
  state.out = branchedFlowThrough(node.getValue(), state.in);
  Preconditions.checkState(outBefore.size() == state.out.size());
  for (int i = 0; i < outBefore.size(); i++) {
    if (!outBefore.get(i).equals(state.out.get(i))) {
      return true;
    }
  }
  return false;
}
 
Example #22
Source File: DeadAssignmentsElimination.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Try to remove useless assignments from a control flow graph that has been
 * annotated with liveness information.
 *
 * @param t The node traversal.
 * @param cfg The control flow graph of the program annotated with liveness
 *        information.
 */
private void tryRemoveDeadAssignments(NodeTraversal t,
    ControlFlowGraph<Node> cfg) {
  Iterable<DiGraphNode<Node, Branch>> nodes = cfg.getDirectedGraphNodes();

  for (DiGraphNode<Node, Branch> cfgNode : nodes) {
    FlowState<LiveVariableLattice> state =
        cfgNode.getAnnotation();
    Node n = cfgNode.getValue();
    if (n == null) {
      continue;
    }
    switch (n.getType()) {
      case Token.IF:
      case Token.WHILE:
      case Token.DO:
        tryRemoveAssignment(t, NodeUtil.getConditionExpression(n), state);
        continue;
      case Token.FOR:
        if (!NodeUtil.isForIn(n)) {
          tryRemoveAssignment(
              t, NodeUtil.getConditionExpression(n), state);
        }
        continue;
      case Token.SWITCH:
      case Token.CASE:
      case Token.RETURN:
        if (n.hasChildren()) {
          tryRemoveAssignment(t, n.getFirstChild(), state);
        }
        continue;
      // TODO(user): case Token.VAR: Remove var a=1;a=2;.....
    }

    tryRemoveAssignment(t, n, state);
  }
}
 
Example #23
Source File: 1_ControlFlowAnalysis.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param entry The entry node.
 * @param priorities The map from nodes to position in the AST (to be
 *    filled by the {@link ControlFlowAnalysis#shouldTraverse}).
 */
private AstControlFlowGraph(Node entry,
    Map<DiGraphNode<Node, Branch>, Integer> priorities,
    boolean edgeAnnotations) {
  super(entry,
      true /* node annotations */, edgeAnnotations);
  this.priorities = priorities;
}
 
Example #24
Source File: CheckPathsBetweenNodes.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void discoverBackEdges(DiGraphNode<N, E> u) {
  u.setAnnotation(GRAY);
  for (DiGraphEdge<N, E> e : u.getOutEdges()) {
    if (ignoreEdge(e)) {
      continue;
    }
    DiGraphNode<N, E> v = e.getDestination();
    if (v.getAnnotation() == WHITE) {
      discoverBackEdges(v);
    } else if (v.getAnnotation() == GRAY) {
      e.setAnnotation(BACK_EDGE);
    }
  }
  u.setAnnotation(BLACK);
}
 
Example #25
Source File: CheckPathsBetweenNodes.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verify that all non-looping paths from {@code a} to {@code b} pass
 * through at least one node where {@code nodePredicate} is true.
 */
private boolean checkAllPathsWithoutBackEdges(DiGraphNode<N, E> a,
    DiGraphNode<N, E> b) {
  if (nodePredicate.apply(a.getValue()) &&
      (inclusive || (a != start && a != end))) {
    return true;
  }
  if (a == b) {
    return false;
  }
  for (DiGraphEdge<N, E> e : a.getOutEdges()) {
    // Once we visited that edge once, we no longer need to
    // re-visit it again.
    if (e.getAnnotation() == VISITED_EDGE) {
      continue;
    }
    e.setAnnotation(VISITED_EDGE);

    if (ignoreEdge(e)) {
      continue;
    }
    if (e.getAnnotation() == BACK_EDGE) {
      continue;
    }

    DiGraphNode<N, E> next = e.getDestination();
    if (!checkAllPathsWithoutBackEdges(next, b)) {
      return false;
    }
  }
  return true;
}
 
Example #26
Source File: NameReferenceGraphReport.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate the HTML for describing a specific declaration.
 * @param builder  contents of report to be generated
 * @param declarationNode declaration to describe
 */
private void generateDeclarationReport(StringBuilder builder,
    DiGraphNode<Name, Reference> declarationNode) {
  // Provide the name and location of declaration,
  // with an anchor to allow navigation to this declaration.
  String declName = declarationNode.getValue().getQualifiedName();
  JSType declType = declarationNode.getValue().getType();

  builder.append("<LI> ");
  builder.append("<A NAME=\"" + declName + "\">");
  builder.append(declName);
  builder.append("\n");

  // Provide the type of the declaration.
  // This is helpful for debugging.
  generateType(builder, declType);

  // List all the definitions of this name that were found in the code.
  // For each, list
  List<DefinitionsRemover.Definition> defs =
      declarationNode.getValue().getDeclarations();

  if (defs.size() == 0) {
     builder.append("<br>No definitions found<br>");
  } else {
    // Otherwise, provide a list of definitions in a dotted list.
    // For each definition, print the location where that definition is
    // found.
    builder.append("<ul>");
    for (DefinitionsRemover.Definition def : defs) {
      Node fnDef = def.getRValue();
      String sourceFileName = getSourceFile(fnDef);
      builder.append("<li> Defined: ");
      generateSourceReferenceLink(builder,
          sourceFileName, fnDef.getLineno(), fnDef.getCharno());
    }
    builder.append("</ul>");
  }
}
 
Example #27
Source File: CheckPathsBetweenNodes.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verify that some non-looping paths from {@code a} to {@code b} pass
 * through at least one node where {@code nodePredicate} is true.
 */
private boolean checkSomePathsWithoutBackEdges(DiGraphNode<N, E> a,
    DiGraphNode<N, E> b) {
  if (nodePredicate.apply(a.getValue()) &&
      (inclusive || (a != start && a != end))) {
    return true;
  }
  if (a == b) {
    return false;
  }
  for (DiGraphEdge<N, E> e : a.getOutEdges()) {
    // Once we visited that edge once, we no longer need to
    // re-visit it again.
    if (e.getAnnotation() == VISITED_EDGE) {
      continue;
    }
    e.setAnnotation(VISITED_EDGE);

    if (ignoreEdge(e)) {
      continue;
    }
    if (e.getAnnotation() == BACK_EDGE) {
      continue;
    }

    DiGraphNode<N, E> next = e.getDestination();
    if (checkSomePathsWithoutBackEdges(next, b)) {
      return true;
    }
  }
  return false;
}
 
Example #28
Source File: Closure_76_DeadAssignmentsElimination_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to remove useless assignments from a control flow graph that has been
 * annotated with liveness information.
 *
 * @param t The node traversal.
 * @param cfg The control flow graph of the program annotated with liveness
 *        information.
 */
private void tryRemoveDeadAssignments(NodeTraversal t,
    ControlFlowGraph<Node> cfg) {
  Iterable<DiGraphNode<Node, Branch>> nodes = cfg.getDirectedGraphNodes();

  for (DiGraphNode<Node, Branch> cfgNode : nodes) {
    FlowState<LiveVariableLattice> state =
        cfgNode.getAnnotation();
    Node n = cfgNode.getValue();
    if (n == null) {
      continue;
    }
    switch (n.getType()) {
      case Token.IF:
      case Token.WHILE:
      case Token.DO:
        tryRemoveAssignment(t, NodeUtil.getConditionExpression(n), state);
        continue;
      case Token.FOR:
        if (!NodeUtil.isForIn(n)) {
          tryRemoveAssignment(
              t, NodeUtil.getConditionExpression(n), state);
        }
        continue;
      case Token.SWITCH:
      case Token.CASE:
      case Token.RETURN:
        if (n.hasChildren()) {
          tryRemoveAssignment(t, n.getFirstChild(), state);
        }
        continue;
      // TODO(user): case Token.VAR: Remove var a=1;a=2;.....
    }

    tryRemoveAssignment(t, n, state);
  }
}
 
Example #29
Source File: Closure_76_DeadAssignmentsElimination_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to remove useless assignments from a control flow graph that has been
 * annotated with liveness information.
 *
 * @param t The node traversal.
 * @param cfg The control flow graph of the program annotated with liveness
 *        information.
 */
private void tryRemoveDeadAssignments(NodeTraversal t,
    ControlFlowGraph<Node> cfg) {
  Iterable<DiGraphNode<Node, Branch>> nodes = cfg.getDirectedGraphNodes();

  for (DiGraphNode<Node, Branch> cfgNode : nodes) {
    FlowState<LiveVariableLattice> state =
        cfgNode.getAnnotation();
    Node n = cfgNode.getValue();
    if (n == null) {
      continue;
    }
    switch (n.getType()) {
      case Token.IF:
      case Token.WHILE:
      case Token.DO:
        tryRemoveAssignment(t, NodeUtil.getConditionExpression(n), state);
        continue;
      case Token.FOR:
        if (!NodeUtil.isForIn(n)) {
          tryRemoveAssignment(
              t, NodeUtil.getConditionExpression(n), state);
        }
        continue;
      case Token.SWITCH:
      case Token.CASE:
      case Token.RETURN:
        if (n.hasChildren()) {
          tryRemoveAssignment(t, n.getFirstChild(), state);
        }
        continue;
      // TODO(user): case Token.VAR: Remove var a=1;a=2;.....
    }

    tryRemoveAssignment(t, n, state);
  }
}
 
Example #30
Source File: DataFlowAnalysis.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the work list and the control flow graph.
 */
protected void initialize() {
  // TODO(user): Calling clear doesn't deallocate the memory in a
  // LinkedHashSet. Consider creating a new work set if we plan to repeatedly
  // call analyze.
  orderedWorkSet.clear();
  for (DiGraphNode<N, Branch> node : cfg.getDirectedGraphNodes()) {
    node.setAnnotation(new FlowState<L>(createInitialEstimateLattice(),
        createInitialEstimateLattice()));
    if (node != cfg.getImplicitReturn()) {
      orderedWorkSet.add(node);
    }
  }
}