summaryrefslogtreecommitdiffstats
path: root/src/proguard/optimize/evaluation/LivenessAnalyzer.java
blob: 87bd4e52f3260149475a8fd10dca3c08f1390b03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
 * ProGuard -- shrinking, optimization, obfuscation, and preverification
 *             of Java bytecode.
 *
 * Copyright (c) 2002-2014 Eric Lafortune (eric@graphics.cornell.edu)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package proguard.optimize.evaluation;

import proguard.classfile.*;
import proguard.classfile.attribute.*;
import proguard.classfile.attribute.visitor.*;
import proguard.classfile.instruction.*;
import proguard.classfile.instruction.visitor.InstructionVisitor;
import proguard.classfile.util.SimplifiedVisitor;
import proguard.evaluation.value.*;

/**
 * This AttributeVisitor analyzes the liveness of the variables in the code
 * attributes that it visits, based on partial evaluation.
 *
 * @author Eric Lafortune
 */
public class LivenessAnalyzer
extends      SimplifiedVisitor
implements   AttributeVisitor,
             InstructionVisitor,
             ExceptionInfoVisitor
{
    //*
    private static final boolean DEBUG = false;
    /*/
    private static       boolean DEBUG = true;
    //*/

    private static final int MAX_VARIABLES_SIZE = 64;

    private final PartialEvaluator partialEvaluator;

    private long[] isAliveBefore = new long[ClassConstants.TYPICAL_CODE_LENGTH];
    private long[] isAliveAfter  = new long[ClassConstants.TYPICAL_CODE_LENGTH];
    private long[] isCategory2   = new long[ClassConstants.TYPICAL_CODE_LENGTH];

    // Fields acting as global temporary variables.
    private boolean checkAgain;
    private long    alive;


    /**
     * Creates a new LivenessAnalyzer.
     */
    public LivenessAnalyzer()
    {
        this(new PartialEvaluator());
    }


    /**
     * Creates a new LivenessAnalyzer that will use the given partial evaluator.
     * It will run this evaluator on every code attribute that it visits.
     */
    public LivenessAnalyzer(PartialEvaluator partialEvaluator)
    {
        this.partialEvaluator = partialEvaluator;
    }


    /**
     * Returns whether the instruction at the given offset has ever been
     * executed during the partial evaluation.
     */
    public boolean isTraced(int instructionOffset)
    {
        return partialEvaluator.isTraced(instructionOffset);
    }


    /**
     * Returns whether the specified variable is alive before the instruction
     * at the given offset.
     */
    public boolean isAliveBefore(int instructionOffset, int variableIndex)
    {
        return variableIndex >= MAX_VARIABLES_SIZE ||
               (isAliveBefore[instructionOffset] & (1L << variableIndex)) != 0;
    }


    /**
     * Sets whether the specified variable is alive before the instruction
     * at the given offset.
     */
    public void setAliveBefore(int instructionOffset, int variableIndex, boolean alive)
    {
        if (variableIndex < MAX_VARIABLES_SIZE)
        {
            if (alive)
            {
                isAliveBefore[instructionOffset] |= 1L << variableIndex;
            }
            else
            {
                isAliveBefore[instructionOffset] &= ~(1L << variableIndex);
            }
        }
    }


    /**
     * Returns whether the specified variable is alive after the instruction
     * at the given offset.
     */
    public boolean isAliveAfter(int instructionOffset, int variableIndex)
    {
        return variableIndex >= MAX_VARIABLES_SIZE ||
               (isAliveAfter[instructionOffset] & (1L << variableIndex)) != 0;
    }


    /**
     * Sets whether the specified variable is alive after the instruction
     * at the given offset.
     */
    public void setAliveAfter(int instructionOffset, int variableIndex, boolean alive)
    {
        if (variableIndex < MAX_VARIABLES_SIZE)
        {
            if (alive)
            {
                isAliveAfter[instructionOffset] |= 1L << variableIndex;
            }
            else
            {
                isAliveAfter[instructionOffset] &= ~(1L << variableIndex);
            }
        }
    }


    /**
     * Returns whether the specified variable takes up two entries after the
     * instruction at the given offset.
     */
    public boolean isCategory2(int instructionOffset, int variableIndex)
    {
        return variableIndex < MAX_VARIABLES_SIZE &&
               (isCategory2[instructionOffset] & (1L << variableIndex)) != 0;
    }


    /**
     * Sets whether the specified variable takes up two entries after the
     * instruction at the given offset.
     */
    public void setCategory2(int instructionOffset, int variableIndex, boolean category2)
    {
        if (variableIndex < MAX_VARIABLES_SIZE)
        {
            if (category2)
            {
                isCategory2[instructionOffset] |= 1L << variableIndex;
            }
            else
            {
                isCategory2[instructionOffset] &= ~(1L << variableIndex);
            }
        }
    }


    // Implementations for AttributeVisitor.

    public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}


    public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
    {
//        DEBUG =
//            clazz.getName().equals("abc/Def") &&
//            method.getName(clazz).equals("abc");

        if (DEBUG)
        {
            System.out.println();
            System.out.println("Liveness analysis: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
        }

        // Initialize the global arrays.
        initializeArrays(codeAttribute);

        // Evaluate the method.
        partialEvaluator.visitCodeAttribute(clazz, method, codeAttribute);

        int codeLength    = codeAttribute.u4codeLength;
        int variablesSize = codeAttribute.u2maxLocals;

        // We'll only really analyze the first 64 variables.
        if (variablesSize > MAX_VARIABLES_SIZE)
        {
            variablesSize = MAX_VARIABLES_SIZE;
        }

        // Mark liveness blocks, as many times as necessary.
        do
        {
            checkAgain = false;
            alive      = 0L;

            // Loop over all traced instructions, backward.
            for (int offset = codeLength - 1; offset >= 0; offset--)
            {
                if (partialEvaluator.isTraced(offset))
                {
                    // Update the liveness based on the branch targets.
                    InstructionOffsetValue branchTargets = partialEvaluator.branchTargets(offset);
                    if (branchTargets != null)
                    {
                        // Update the liveness right after the branch instruction.
                        alive = combinedLiveness(branchTargets);
                    }

                    // Merge the current liveness.
                    alive |= isAliveAfter[offset];

                    // Update the liveness after the instruction.
                    isAliveAfter[offset] = alive;

                    // Update the current liveness based on the instruction.
                    codeAttribute.instructionAccept(clazz, method, offset, this);

                    // Merge the current liveness.
                    alive |= isAliveBefore[offset];

                    // Update the liveness before the instruction.
                    if ((~isAliveBefore[offset] & alive) != 0L)
                    {
                        isAliveBefore[offset] = alive;

                        // Do we have to check again after this loop?
                        checkAgain |= offset < maxOffset(partialEvaluator.branchOrigins(offset));
                    }
                }
            }

            // Account for the liveness at the start of the exception handlers.
            codeAttribute.exceptionsAccept(clazz, method, this);
        }
        while (checkAgain);

        // Loop over all instructions, to mark variables that take up two entries.
        for (int offset = 0; offset < codeLength; offset++)
        {
            if (partialEvaluator.isTraced(offset))
            {
                // Loop over all variables.
                for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
                {
                    // Is the variable alive and a category 2 type?
                    if (isAliveBefore(offset, variableIndex))
                    {
                        Value value = partialEvaluator.getVariablesBefore(offset).getValue(variableIndex);
                        if (value != null && value.isCategory2())
                        {
                            // Mark it as such.
                            setCategory2(offset, variableIndex, true);

                            // Mark the next variable as well.
                            setAliveBefore(offset, variableIndex + 1, true);
                            setCategory2(  offset, variableIndex + 1, true);
                        }
                    }

                    // Is the variable alive and a category 2 type?
                    if (isAliveAfter(offset, variableIndex))
                    {
                        Value value = partialEvaluator.getVariablesAfter(offset).getValue(variableIndex);
                        if (value != null && value.isCategory2())
                        {
                            // Mark it as such.
                            setCategory2(offset, variableIndex, true);

                            // Mark the next variable as well.
                            setAliveAfter(offset, variableIndex + 1, true);
                            setCategory2( offset, variableIndex + 1, true);
                        }
                    }
                }
            }
        }

        if (DEBUG)
        {
            // Loop over all instructions.
            for (int offset = 0; offset < codeLength; offset++)
            {
                if (partialEvaluator.isTraced(offset))
                {
                    long aliveBefore = isAliveBefore[offset];
                    long aliveAfter  = isAliveAfter[offset];
                    long category2   = isCategory2[offset];

                    // Print out the liveness of all variables before the instruction.
                    for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
                    {
                        long variableMask = (1L << variableIndex);
                        System.out.print((aliveBefore & variableMask) == 0L ? '.' :
                                         (category2   & variableMask) == 0L ? 'x' :
                                                                              '*');
                    }

                    // Print out the instruction itself.
                    System.out.println(" "+ InstructionFactory.create(codeAttribute.code, offset).toString(offset));

                    // Print out the liveness of all variables after the instruction.
                    for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
                    {
                        long variableMask = (1L << variableIndex);
                        System.out.print((aliveAfter & variableMask) == 0L ? '.' :
                                         (category2  & variableMask) == 0L ? 'x' :
                                                                             '=');
                    }

                    System.out.println();
                }
            }
        }
    }


    // Implementations for InstructionVisitor.

    public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}


    public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
    {
        int variableIndex = variableInstruction.variableIndex;
        if (variableIndex < MAX_VARIABLES_SIZE)
        {
            long livenessMask = 1L << variableIndex;

            // Is it a load instruction or a store instruction?
            if (variableInstruction.isLoad())
            {
                // Start marking the variable before the load instruction.
                alive |= livenessMask;
            }
            else
            {
                // Stop marking the variable before the store instruction.
                alive &= ~livenessMask;

                // But do mark the variable right after the store instruction.
                isAliveAfter[offset] |= livenessMask;
            }
        }
    }


    public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
    {
        // Special case: variable 0 ('this') in an initializer has to be alive
        // as long as it hasn't been initialized.
         if (offset == partialEvaluator.superInitializationOffset())
        {
            alive |= 1L;
        }
    }


    // Implementations for ExceptionInfoVisitor.

    public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
    {
        // Are any variables alive at the start of the handler?
        long alive = isAliveBefore[exceptionInfo.u2handlerPC];
        if (alive != 0L)
        {
            // Set the same liveness flags for the entire try block.
            int startOffset = exceptionInfo.u2startPC;
            int endOffset   = exceptionInfo.u2endPC;

            for (int offset = startOffset; offset < endOffset; offset++)
            {
                if (partialEvaluator.isTraced(offset))
                {
                    if ((~(isAliveBefore[offset] & isAliveAfter[offset]) & alive) != 0L)
                    {
                        isAliveBefore[offset] |= alive;
                        isAliveAfter[offset]  |= alive;

                        // Check again after having marked this try block.
                        checkAgain = true;
                    }
                }
            }
        }
    }


    // Small utility methods.

    /**
     * Initializes the global arrays.
     */
    private void initializeArrays(CodeAttribute codeAttribute)
    {
        int codeLength = codeAttribute.u4codeLength;

        // Create new arrays for storing information at each instruction offset.
        if (isAliveBefore.length < codeLength)
        {
            isAliveBefore = new long[codeLength];
            isAliveAfter  = new long[codeLength];
            isCategory2   = new long[codeLength];
        }
        else
        {
            for (int index = 0; index < codeLength; index++)
            {
                isAliveBefore[index] = 0L;
                isAliveAfter[index]  = 0L;
                isCategory2[index]   = 0L;
            }
        }
    }


    /**
     * Returns the combined liveness mask of the variables right before the
     * specified instruction offsets.
     */
    private long combinedLiveness(InstructionOffsetValue instructionOffsetValue)
    {
        long alive = 0L;

        int count = instructionOffsetValue.instructionOffsetCount();
        for (int index = 0; index < count; index++)
        {
            alive |= isAliveBefore[instructionOffsetValue.instructionOffset(index)];
        }

        return alive;
    }


    /**
     * Returns the minimum offset from the given instruction offsets.
     */
    private int minOffset(Value instructionOffsets)
    {
        return minOffset(instructionOffsets, Integer.MAX_VALUE);
    }


    /**
     * Returns the minimum offset from the given instruction offsets.
     */
    private int minOffset(Value instructionOffsets, int minOffset)
    {
        if (instructionOffsets != null)
        {
            InstructionOffsetValue instructionOffsetValue =
                instructionOffsets.instructionOffsetValue();

            int count = instructionOffsetValue.instructionOffsetCount();
            for (int index = 0; index < count; index++)
            {
                int offset = instructionOffsetValue.instructionOffset(index);
                if (minOffset > offset)
                {
                    minOffset = offset;
                }
            }
        }

        return minOffset;
    }


    /**
     * Returns the maximum offset from the given instruction offsets.
     */
    private int maxOffset(Value instructionOffsets)
    {
        return maxOffset(instructionOffsets, Integer.MIN_VALUE);
    }


    /**
     * Returns the maximum offset from the given instruction offsets.
     */
    private int maxOffset(Value instructionOffsets, int maxOffset)
    {
        if (instructionOffsets != null)
        {
            InstructionOffsetValue instructionOffsetValue =
                instructionOffsets.instructionOffsetValue();

            int count = instructionOffsetValue.instructionOffsetCount();
            for (int index = 0; index < count; index++)
            {
                int offset = instructionOffsetValue.instructionOffset(index);
                if (maxOffset < offset)
                {
                    maxOffset = offset;
                }
            }
        }

        return maxOffset;
    }
}