Search in sources :

Example 36 with ValueBox

use of soot.ValueBox in project soot by Sable.

the class CopyPropagator method internalTransform.

/**
 * Cascaded copy propagator.
 *
 * If it encounters situations of the form: A: a = ...; B: ... x = a; C:...
 * use (x); where a has only one definition, and x has only one definition
 * (B), then it can propagate immediately without checking between B and C
 * for redefinitions of a (namely) A because they cannot occur. In this case
 * the propagator is global.
 *
 * Otherwise, if a has multiple definitions then it only checks for
 * redefinitions of Propagates constants and copies in extended basic
 * blocks.
 *
 * Does not propagate stack locals when the "only-regular-locals" option is
 * true.
 */
protected void internalTransform(Body b, String phaseName, Map<String, String> opts) {
    CPOptions options = new CPOptions(opts);
    StmtBody stmtBody = (StmtBody) b;
    int fastCopyPropagationCount = 0;
    int slowCopyPropagationCount = 0;
    if (Options.v().verbose())
        logger.debug("[" + stmtBody.getMethod().getName() + "] Propagating copies...");
    if (Options.v().time())
        Timers.v().propagatorTimer.start();
    Chain<Unit> units = stmtBody.getUnits();
    Map<Local, Integer> localToDefCount = new HashMap<Local, Integer>();
    // Count number of definitions for each local.
    for (Unit u : units) {
        Stmt s = (Stmt) u;
        if (s instanceof DefinitionStmt && ((DefinitionStmt) s).getLeftOp() instanceof Local) {
            Local l = (Local) ((DefinitionStmt) s).getLeftOp();
            if (!localToDefCount.containsKey(l))
                localToDefCount.put(l, new Integer(1));
            else
                localToDefCount.put(l, new Integer(localToDefCount.get(l).intValue() + 1));
        }
    }
    if (throwAnalysis == null)
        throwAnalysis = Scene.v().getDefaultThrowAnalysis();
    if (forceOmitExceptingUnitEdges == false)
        forceOmitExceptingUnitEdges = Options.v().omit_excepting_unit_edges();
    // Go through the definitions, building the webs
    UnitGraph graph = new ExceptionalUnitGraph(stmtBody, throwAnalysis, forceOmitExceptingUnitEdges);
    LocalDefs localDefs = LocalDefs.Factory.newLocalDefs(graph);
    // Perform a local propagation pass.
    {
        Iterator<Unit> stmtIt = (new PseudoTopologicalOrderer<Unit>()).newList(graph, false).iterator();
        while (stmtIt.hasNext()) {
            Stmt stmt = (Stmt) stmtIt.next();
            for (ValueBox useBox : stmt.getUseBoxes()) {
                if (useBox.getValue() instanceof Local) {
                    Local l = (Local) useBox.getValue();
                    // null due to typing, we always inline that constant.
                    if (!(l.getType() instanceof NullType)) {
                        if (options.only_regular_locals() && l.getName().startsWith("$"))
                            continue;
                        if (options.only_stack_locals() && !l.getName().startsWith("$"))
                            continue;
                    }
                    List<Unit> defsOfUse = localDefs.getDefsOfAt(l, stmt);
                    // We can propagate the definition if we either only
                    // have
                    // one definition or all definitions are side-effect
                    // free
                    // and equal. For starters, we only support constants in
                    // the case of multiple definitions.
                    boolean propagateDef = defsOfUse.size() == 1;
                    if (!propagateDef && defsOfUse.size() > 0) {
                        boolean agrees = true;
                        Constant constVal = null;
                        for (Unit defUnit : defsOfUse) {
                            boolean defAgrees = false;
                            if (defUnit instanceof AssignStmt) {
                                AssignStmt assign = (AssignStmt) defUnit;
                                if (assign.getRightOp() instanceof Constant) {
                                    if (constVal == null) {
                                        constVal = (Constant) assign.getRightOp();
                                        defAgrees = true;
                                    } else if (constVal.equals(assign.getRightOp()))
                                        defAgrees = true;
                                }
                            }
                            agrees &= defAgrees;
                        }
                        propagateDef = agrees;
                    }
                    if (propagateDef) {
                        DefinitionStmt def = (DefinitionStmt) defsOfUse.get(0);
                        if (def.getRightOp() instanceof Constant) {
                            if (useBox.canContainValue(def.getRightOp())) {
                                useBox.setValue(def.getRightOp());
                            }
                        } else if (def.getRightOp() instanceof CastExpr) {
                            CastExpr ce = (CastExpr) def.getRightOp();
                            if (ce.getCastType() instanceof RefLikeType) {
                                boolean isConstNull = ce.getOp() instanceof IntConstant && ((IntConstant) ce.getOp()).value == 0;
                                isConstNull |= ce.getOp() instanceof LongConstant && ((LongConstant) ce.getOp()).value == 0;
                                if (isConstNull) {
                                    if (useBox.canContainValue(NullConstant.v())) {
                                        useBox.setValue(NullConstant.v());
                                    }
                                }
                            }
                        } else if (def.getRightOp() instanceof Local) {
                            Local m = (Local) def.getRightOp();
                            if (l != m) {
                                Integer defCount = localToDefCount.get(m);
                                if (defCount == null || defCount == 0)
                                    throw new RuntimeException("Variable " + m + " used without definition!");
                                if (defCount == 1) {
                                    useBox.setValue(m);
                                    fastCopyPropagationCount++;
                                    continue;
                                }
                                List<Unit> path = graph.getExtendedBasicBlockPathBetween(def, stmt);
                                if (path == null) {
                                    // no path in the extended basic block
                                    continue;
                                }
                                Iterator<Unit> pathIt = path.iterator();
                                // Skip first node
                                pathIt.next();
                                // Make sure that m is not redefined along
                                // path
                                {
                                    boolean isRedefined = false;
                                    while (pathIt.hasNext()) {
                                        Stmt s = (Stmt) pathIt.next();
                                        if (stmt == s) {
                                            break;
                                        }
                                        if (s instanceof DefinitionStmt) {
                                            if (((DefinitionStmt) s).getLeftOp() == m) {
                                                isRedefined = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (isRedefined)
                                        continue;
                                }
                                useBox.setValue(m);
                                slowCopyPropagationCount++;
                            }
                        }
                    }
                }
            }
        }
    }
    if (Options.v().verbose())
        logger.debug("[" + stmtBody.getMethod().getName() + "]     Propagated: " + fastCopyPropagationCount + " fast copies  " + slowCopyPropagationCount + " slow copies");
    if (Options.v().time())
        Timers.v().propagatorTimer.end();
}
Also used : HashMap(java.util.HashMap) NullConstant(soot.jimple.NullConstant) Constant(soot.jimple.Constant) LongConstant(soot.jimple.LongConstant) IntConstant(soot.jimple.IntConstant) AssignStmt(soot.jimple.AssignStmt) Unit(soot.Unit) Stmt(soot.jimple.Stmt) AssignStmt(soot.jimple.AssignStmt) DefinitionStmt(soot.jimple.DefinitionStmt) RefLikeType(soot.RefLikeType) ExceptionalUnitGraph(soot.toolkits.graph.ExceptionalUnitGraph) Iterator(java.util.Iterator) CastExpr(soot.jimple.CastExpr) IntConstant(soot.jimple.IntConstant) List(java.util.List) LongConstant(soot.jimple.LongConstant) PseudoTopologicalOrderer(soot.toolkits.graph.PseudoTopologicalOrderer) Local(soot.Local) LocalDefs(soot.toolkits.scalar.LocalDefs) ExceptionalUnitGraph(soot.toolkits.graph.ExceptionalUnitGraph) UnitGraph(soot.toolkits.graph.UnitGraph) ValueBox(soot.ValueBox) CPOptions(soot.options.CPOptions) NullType(soot.NullType) StmtBody(soot.jimple.StmtBody) DefinitionStmt(soot.jimple.DefinitionStmt)

Example 37 with ValueBox

use of soot.ValueBox in project soot by Sable.

the class LocalNameStandardizer method internalTransform.

@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
    boolean onlyStackName = PhaseOptions.getBoolean(options, "only-stack-locals");
    boolean sortLocals = PhaseOptions.getBoolean(options, "sort-locals");
    final BooleanType booleanType = BooleanType.v();
    final ByteType byteType = ByteType.v();
    final ShortType shortType = ShortType.v();
    final CharType charType = CharType.v();
    final IntType intType = IntType.v();
    final LongType longType = LongType.v();
    final DoubleType doubleType = DoubleType.v();
    final FloatType floatType = FloatType.v();
    final ErroneousType erroneousType = ErroneousType.v();
    final UnknownType unknownType = UnknownType.v();
    final StmtAddressType stmtAddressType = StmtAddressType.v();
    final NullType nullType = NullType.v();
    // Change the names to the standard forms now.
    {
        int objectCount = 0;
        int intCount = 0;
        int longCount = 0;
        int floatCount = 0;
        int doubleCount = 0;
        int addressCount = 0;
        int errorCount = 0;
        int nullCount = 0;
        /* The goal of this option is to ensure that local ordering remains
             * consistent between different iterations of soot. This helps to ensure
             * things like stable string representations of instructions and stable
             * jimple representations of a methods body when soot is used to load
             * the same code in different iterations.
             * 
             * First sorts the locals alphabetically by the string representation of
             * their type. Then if there are two locals with the same type, it uses
             * the only other source of structurally stable information (i.e. the 
             * instructions themselves) to produce an ordering for the locals
             * that remains consistent between different soot instances. It achieves
             * this by determining the position of a local's first occurrence in the 
             * instruction's list of definition statements. This position is then used
             * to sort the locals with the same type in an ascending order. 
             * 
             * The only times that this may not produce a consistent ordering for the 
             * locals between different soot instances is if a local is never defined in
             * the instructions or if the instructions themselves are changed in some way
             * that effects the ordering of the locals. In the first case, if a local is 
             * never defined, the other jimple body phases will remove this local as it is 
             * unused. As such, all we have to do is rerun this LocalNameStandardizer after
             * all other jimple body phases to eliminate any ambiguity introduced by these
             * phases and by the removed unused locals. In the second case, if the instructions
             * themselves changed then the user would have had to intentionally told soot to
             * modify the instructions of the code. Otherwise, the instructions would not have
             * changed because we assume the instructions to always be structurally stable
             * between different instances of soot. As such, in this instance, the user should
             * not be expecting soot to produce the same output as the input and thus the
             * ordering of the locals does not matter.
             */
        if (sortLocals) {
            Chain<Local> locals = body.getLocals();
            final List<ValueBox> defs = body.getDefBoxes();
            ArrayList<Local> sortedLocals = new ArrayList<Local>(locals);
            Collections.sort(sortedLocals, new Comparator<Local>() {

                private Map<Local, Integer> firstOccuranceCache = new HashMap<Local, Integer>();

                @Override
                public int compare(Local arg0, Local arg1) {
                    int ret = arg0.getType().toString().compareTo(arg1.getType().toString());
                    if (ret == 0) {
                        ret = Integer.compare(getFirstOccurance(arg0), getFirstOccurance(arg1));
                    }
                    return ret;
                }

                private int getFirstOccurance(Local l) {
                    Integer cur = firstOccuranceCache.get(l);
                    if (cur != null) {
                        return cur;
                    } else {
                        int count = 0;
                        int first = -1;
                        for (ValueBox vb : defs) {
                            Value v = vb.getValue();
                            if (v instanceof Local && v.equals(l)) {
                                first = count;
                                break;
                            }
                            count++;
                        }
                        firstOccuranceCache.put(l, first);
                        return first;
                    }
                }
            });
            locals.clear();
            locals.addAll(sortedLocals);
        }
        for (Local l : body.getLocals()) {
            String prefix = "";
            if (l.getName().startsWith("$"))
                prefix = "$";
            else {
                if (onlyStackName)
                    continue;
            }
            final Type type = l.getType();
            if (type.equals(booleanType))
                l.setName(prefix + "z" + intCount++);
            else if (type.equals(byteType))
                l.setName(prefix + "b" + longCount++);
            else if (type.equals(shortType))
                l.setName(prefix + "s" + longCount++);
            else if (type.equals(charType))
                l.setName(prefix + "c" + longCount++);
            else if (type.equals(intType))
                l.setName(prefix + "i" + longCount++);
            else if (type.equals(longType))
                l.setName(prefix + "l" + longCount++);
            else if (type.equals(doubleType))
                l.setName(prefix + "d" + doubleCount++);
            else if (type.equals(floatType))
                l.setName(prefix + "f" + floatCount++);
            else if (type.equals(stmtAddressType))
                l.setName(prefix + "a" + addressCount++);
            else if (type.equals(erroneousType) || type.equals(unknownType)) {
                l.setName(prefix + "e" + errorCount++);
            } else if (type.equals(nullType))
                l.setName(prefix + "n" + nullCount++);
            else
                l.setName(prefix + "r" + objectCount++);
        }
    }
}
Also used : Chain(soot.util.Chain) LongType(soot.LongType) ArrayList(java.util.ArrayList) ByteType(soot.ByteType) IntType(soot.IntType) FloatType(soot.FloatType) Comparator(java.util.Comparator) ErroneousType(soot.ErroneousType) ArrayList(java.util.ArrayList) List(java.util.List) ShortType(soot.ShortType) BooleanType(soot.BooleanType) Local(soot.Local) UnknownType(soot.UnknownType) UnknownType(soot.UnknownType) DoubleType(soot.DoubleType) FloatType(soot.FloatType) IntType(soot.IntType) ShortType(soot.ShortType) CharType(soot.CharType) LongType(soot.LongType) NullType(soot.NullType) StmtAddressType(soot.StmtAddressType) BooleanType(soot.BooleanType) ErroneousType(soot.ErroneousType) ByteType(soot.ByteType) Type(soot.Type) DoubleType(soot.DoubleType) ValueBox(soot.ValueBox) Value(soot.Value) CharType(soot.CharType) StmtAddressType(soot.StmtAddressType) NullType(soot.NullType) HashMap(java.util.HashMap) Map(java.util.Map)

Example 38 with ValueBox

use of soot.ValueBox in project soot by Sable.

the class UnusedLocalEliminator method internalTransform.

@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
    if (Options.v().verbose())
        logger.debug("[" + body.getMethod().getName() + "] Eliminating unused locals...");
    int i = 0;
    int n = body.getLocals().size();
    int[] oldNumbers = new int[n];
    Chain<Local> locals = body.getLocals();
    for (Local local : locals) {
        oldNumbers[i] = local.getNumber();
        local.setNumber(i);
        i++;
    }
    boolean[] usedLocals = new boolean[n];
    // Traverse statements noting all the uses and defs
    for (Unit s : body.getUnits()) {
        for (ValueBox vb : s.getUseBoxes()) {
            Value v = vb.getValue();
            if (v instanceof Local) {
                Local l = (Local) v;
                assert locals.contains(l);
                usedLocals[l.getNumber()] = true;
            }
        }
        for (ValueBox vb : s.getDefBoxes()) {
            Value v = vb.getValue();
            if (v instanceof Local) {
                Local l = (Local) v;
                assert locals.contains(l);
                usedLocals[l.getNumber()] = true;
            }
        }
    }
    // Remove all locals that are unused.
    List<Local> keep = new ArrayList<Local>(body.getLocalCount());
    for (Local local : locals) {
        int lno = local.getNumber();
        local.setNumber(oldNumbers[lno]);
        if (usedLocals[lno]) {
            keep.add(local);
        }
    }
    body.getLocals().clear();
    body.getLocals().addAll(keep);
}
Also used : ValueBox(soot.ValueBox) Value(soot.Value) ArrayList(java.util.ArrayList) Local(soot.Local) Unit(soot.Unit)

Example 39 with ValueBox

use of soot.ValueBox in project soot by Sable.

the class CombinedDUAnalysis method flowThrough.

// STEP 5: Define flow equations.
// in(s) = ( out(s) minus boxes(def(s)) ) union useboxes(s)
protected void flowThrough(FlowSet<ValueBox> out, Unit u, FlowSet<ValueBox> in) {
    Local def = localDefed(u);
    out.copy(in);
    if (def != null) {
        Collection<ValueBox> boxesDefed = localToUseBoxes.get(def);
        for (ValueBox vb : in) {
            if (boxesDefed.contains(vb))
                in.remove(vb);
        }
    }
    in.union(unitToLocalUseBoxes.get(u));
}
Also used : ValueBox(soot.ValueBox) Local(soot.Local)

Example 40 with ValueBox

use of soot.ValueBox in project soot by Sable.

the class CombinedDUAnalysis method getLiveLocalsBefore.

public List<Local> getLiveLocalsBefore(Unit u) {
    List<Local> ret = liveLocalsBefore.get(u);
    if (ret == null) {
        HashSet<Local> hs = new HashSet<Local>();
        for (ValueBox vb : getFlowBefore(u)) {
            hs.add((Local) vb.getValue());
        }
        liveLocalsBefore.put(u, ret = new ArrayList<Local>(hs));
    }
    return ret;
}
Also used : ValueBox(soot.ValueBox) ArrayList(java.util.ArrayList) Local(soot.Local) HashSet(java.util.HashSet)

Aggregations

ValueBox (soot.ValueBox)58 Value (soot.Value)43 Local (soot.Local)36 Unit (soot.Unit)33 ArrayList (java.util.ArrayList)26 Type (soot.Type)20 Stmt (soot.jimple.Stmt)20 DefinitionStmt (soot.jimple.DefinitionStmt)17 InvokeExpr (soot.jimple.InvokeExpr)15 SootMethod (soot.SootMethod)13 RefType (soot.RefType)12 AssignStmt (soot.jimple.AssignStmt)11 IntConstant (soot.jimple.IntConstant)11 HashSet (java.util.HashSet)10 IntType (soot.IntType)10 SootClass (soot.SootClass)10 FieldRef (soot.jimple.FieldRef)10 HashMap (java.util.HashMap)9 LongType (soot.LongType)9 VoidType (soot.VoidType)9