simplify icon indicating copy to clipboard operation
simplify copied to clipboard

Propagate constants in useless array assignment and reference

Open CalebFenton opened this issue 7 years ago • 2 comments

Here's a short example:

Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = "hello";
arrayOfObject[1] = world";
someMethod(arrayOfObject[0], arrayOfObject[1])

I think this could work by replacing aget on a known array with a constant-izable value with the constant op equivalent. Dead code analysis would then notice arrayOfObject isn't used. For an easy example of this, see https://github.com/CalebFenton/simplify/issues/94.

CalebFenton avatar Oct 05 '18 00:10 CalebFenton

#94 actually contains a harder version of this where the array elements are unknown. But it can still be optimized assuming the register isn't reused between aput and aget, which will probably typically be the case with code that's been unreflected.

CalebFenton avatar Oct 05 '18 03:10 CalebFenton

Here's how it might look in Smali:

.method protected findClass(Ljava/lang/String;)Ljava/lang/Class;
    .registers 8
    iget-object v0, p0, Lo/We;->c:Ljava/lang/Object;

    const/4 v1, 0x2
    new-array v1, v1, [Ljava/lang/Object;

    const/4 v2, 0x0
    aput-object p1, v1, v2

    const/4 v2, 0x1
    aput-object p0, v1, v2

    const/4 v2, 0x0
    aget-object v2, v1, v2
    check-cast v2, Ljava/lang/String;

    const/4 v3, 0x1
    aget-object v3, v1, v3
    check-cast v3, Ljava/lang/ClassLoader;

    invoke-virtual {v0, v2, v3}, Ldalvik/system/DexFile;->loadClass(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljava/lang/Class;
    move-result-object v0

    # ...
.end method

CalebFenton avatar Oct 05 '18 18:10 CalebFenton