-
Notifications
You must be signed in to change notification settings - Fork 578
/
BetterCFGBuilder2.java
1305 lines (1140 loc) · 48.7 KB
/
BetterCFGBuilder2.java
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Bytecode Analysis Framework
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.ba;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.bcel.Const;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ACONST_NULL;
import org.apache.bcel.generic.ALOAD;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.CodeExceptionGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.ExceptionThrower;
import org.apache.bcel.generic.GETFIELD;
import org.apache.bcel.generic.GETSTATIC;
import org.apache.bcel.generic.GOTO;
import org.apache.bcel.generic.GotoInstruction;
import org.apache.bcel.generic.ICONST;
import org.apache.bcel.generic.IFNONNULL;
import org.apache.bcel.generic.IFNULL;
import org.apache.bcel.generic.IF_ACMPEQ;
import org.apache.bcel.generic.IF_ACMPNE;
import org.apache.bcel.generic.INSTANCEOF;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.IfInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.JsrInstruction;
import org.apache.bcel.generic.LDC;
import org.apache.bcel.generic.MONITOREXIT;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.NOP;
import org.apache.bcel.generic.POP;
import org.apache.bcel.generic.POP2;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.PUTSTATIC;
import org.apache.bcel.generic.ReturnInstruction;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.type.ExceptionSetFactory;
import edu.umd.cs.findbugs.ba.type.StandardTypeMerger;
import edu.umd.cs.findbugs.bcel.generic.NONNULL2Z;
import edu.umd.cs.findbugs.bcel.generic.NULL2Z;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.classfile.FieldDescriptor;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.IAnalysisCache;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
/**
* A CFGBuilder that really tries to construct accurate control flow graphs. The
* CFGs it creates have accurate exception edges, and have accurately inlined
* JSR subroutines.
*
* @author David Hovemeyer
* @see CFG
*/
public class BetterCFGBuilder2 implements CFGBuilder, EdgeTypes, Debug {
private static final boolean DEBUG = SystemProperties.getBoolean("cfgbuilder.debug");
/*
* ----------------------------------------------------------------------
* Helper classes
* ----------------------------------------------------------------------
*/
/**
* A work list item for creating the CFG for a subroutine.
*/
private static class WorkListItem {
private final InstructionHandle start;
private final BasicBlock basicBlock;
/**
* Constructor.
*
* @param start
* first instruction in the basic block
* @param basicBlock
* the basic block to build
*/
public WorkListItem(InstructionHandle start, BasicBlock basicBlock) {
this.start = start;
this.basicBlock = basicBlock;
}
/**
* Get the start instruction.
*/
public InstructionHandle getStartInstruction() {
return start;
}
/**
* Get the basic block.
*/
public BasicBlock getBasicBlock() {
return basicBlock;
}
}
/**
* A placeholder for a control edge that escapes its subroutine to return
* control back to an outer (calling) subroutine. It will turn into a real
* edge during inlining.
*/
private static class EscapeTarget {
private final InstructionHandle target;
private final @Edge.Type int edgeType;
/**
* Constructor.
*
* @param target
* the target instruction in a calling subroutine
* @param edgeType
* the type of edge that should be created when the
* subroutine is inlined into its calling context
*/
public EscapeTarget(InstructionHandle target, @Edge.Type int edgeType) {
this.target = target;
this.edgeType = edgeType;
}
/**
* Get the target instruction.
*/
public InstructionHandle getTarget() {
return target;
}
/**
* Get the edge type.
*/
public @Edge.Type int getEdgeType() {
return edgeType;
}
}
/**
* JSR subroutine. The top level subroutine is where execution starts. Each
* subroutine has its own CFG. Eventually, all JSR subroutines will be
* inlined into the top level subroutine, resulting in an accurate CFG for
* the overall method.
*/
private class Subroutine {
private final InstructionHandle start;
private final BitSet instructionSet;
private final CFG cfgSub;
private final IdentityHashMap<InstructionHandle, BasicBlock> blockMap;
private final IdentityHashMap<BasicBlock, List<EscapeTarget>> escapeTargetListMap;
private final BitSet returnBlockSet;
private final BitSet exitBlockSet;
private final BitSet unhandledExceptionBlockSet;
private final LinkedList<WorkListItem> workList;
/**
* Constructor.
*
* @param start
* the start instruction for the subroutine
*/
public Subroutine(InstructionHandle start) {
this.start = start;
this.instructionSet = new BitSet();
this.cfgSub = new CFG();
this.blockMap = new IdentityHashMap<>();
this.escapeTargetListMap = new IdentityHashMap<>();
this.returnBlockSet = new BitSet();
this.exitBlockSet = new BitSet();
this.unhandledExceptionBlockSet = new BitSet();
this.workList = new LinkedList<>();
}
/**
* Get the start instruction.
*/
public InstructionHandle getStartInstruction() {
return start;
}
/**
* Allocate a new basic block in the subroutine.
*/
public BasicBlock allocateBasicBlock() {
return cfgSub.allocate();
}
/**
* Add a work list item for a basic block to be constructed.
*/
public void addItem(WorkListItem item) {
workList.add(item);
}
/**
* Are there more work list items?
*/
public boolean hasMoreWork() {
return !workList.isEmpty();
}
/**
* Get the next work list item.
*/
public WorkListItem nextItem() {
return workList.removeFirst();
}
/**
* Get the entry block for the subroutine's CFG.
*/
public BasicBlock getEntry() {
return cfgSub.getEntry();
}
/**
* Get the exit block for the subroutine's CFG.
*/
public BasicBlock getExit() {
return cfgSub.getExit();
}
/**
* Get the start block for the subroutine's CFG. (I.e., the block
* containing the start instruction.)
*/
public BasicBlock getStartBlock() {
return getBlock(start);
}
/**
* Get the subroutine's CFG.
*/
public CFG getCFG() {
return cfgSub;
}
/**
* Add an instruction to the subroutine. We keep track of which
* instructions are part of which subroutines. No instruction may be
* part of more than one subroutine.
*
* @param handle
* the instruction to be added to the subroutine
*/
public void addInstruction(InstructionHandle handle) throws CFGBuilderException {
int position = handle.getPosition();
if (usedInstructionSet.get(position)) {
throw new CFGBuilderException("Instruction " + handle + " visited in multiple subroutines");
}
instructionSet.set(position);
usedInstructionSet.set(position);
}
/**
* Is the given instruction part of this subroutine?
*/
public boolean containsInstruction(InstructionHandle handle) {
return instructionSet.get(handle.getPosition());
}
/**
* Get the basic block in the subroutine for the given instruction. If
* the block doesn't exist yet, it is created, and a work list item is
* added which will populate it. Note that if start is an exception
* thrower, the block returned will be its ETB.
*
* @param start
* the start instruction for the block
* @return the basic block for the instruction
*/
public BasicBlock getBlock(InstructionHandle start) {
BasicBlock block = blockMap.get(start);
if (block == null) {
block = allocateBasicBlock();
blockMap.put(start, block);
// Block is an exception handler?
CodeExceptionGen exceptionGen = exceptionHandlerMap.getHandlerForStartInstruction(start);
if (exceptionGen != null) {
block.setExceptionGen(null, exceptionGen);
}
addItem(new WorkListItem(start, block));
}
return block;
}
/**
* Indicate that the method returns at the end of the given block.
*
* @param block
* the returning block
*/
public void setReturnBlock(BasicBlock block) {
returnBlockSet.set(block.getLabel());
}
/**
* Does the method return at the end of this block?
*/
public boolean isReturnBlock(BasicBlock block) {
return returnBlockSet.get(block.getLabel());
}
/**
* Indicate that System.exit() is called at the end of the given block.
*
* @param block
* the exiting block
*/
public void setExitBlock(BasicBlock block) {
exitBlockSet.set(block.getLabel());
}
/**
* Is System.exit() called at the end of this block?
*/
public boolean isExitBlock(BasicBlock block) {
return exitBlockSet.get(block.getLabel());
}
/**
* Indicate that an unhandled exception may be thrown by the given
* block.
*
* @param block
* the block throwing an unhandled exception
*/
public void setUnhandledExceptionBlock(BasicBlock block) {
unhandledExceptionBlockSet.set(block.getLabel());
}
/**
* Does this block throw an unhandled exception?
*/
public boolean isUnhandledExceptionBlock(BasicBlock block) {
return unhandledExceptionBlockSet.get(block.getLabel());
}
/**
* Add a control flow edge to the subroutine. If the control target has
* not yet been added to the subroutine, a new work list item is added.
* If the control target is in another subroutine, an EscapeTarget is
* added.
*
* @param sourceBlock
* the source basic block
* @param target
* the control target
* @param edgeType
* the type of control edge
*/
public void addEdgeAndExplore(BasicBlock sourceBlock, InstructionHandle target, @Edge.Type int edgeType) {
if (usedInstructionSet.get(target.getPosition()) && !containsInstruction(target)) {
// Control escapes this subroutine
List<EscapeTarget> escapeTargetList = escapeTargetListMap.computeIfAbsent(sourceBlock,
k -> new LinkedList<>());
escapeTargetList.add(new EscapeTarget(target, edgeType));
} else {
// Edge within the current subroutine
BasicBlock targetBlock = getBlock(target);
addEdge(sourceBlock, targetBlock, edgeType);
}
}
/**
* Add an edge to the subroutine's CFG.
*
* @param sourceBlock
* the source basic block
* @param destBlock
* the destination basic block
* @param edgeType
* the type of edge
*/
public void addEdge(BasicBlock sourceBlock, BasicBlock destBlock, @Edge.Type int edgeType) {
if (VERIFY_INTEGRITY && destBlock.isExceptionHandler() && edgeType != HANDLED_EXCEPTION_EDGE) {
throw new IllegalStateException("In method " + SignatureConverter.convertMethodSignature(methodGen)
+ ": exception handler " + destBlock.getFirstInstruction() + " reachable by non exception edge type "
+ edgeType);
}
cfgSub.createEdge(sourceBlock, destBlock, edgeType);
}
/**
* Get an Iterator over the EscapeTargets of given basic block.
*
* @param sourceBlock
* the basic block
* @return an Iterator over the EscapeTargets
*/
public Iterator<EscapeTarget> escapeTargetIterator(BasicBlock sourceBlock) {
List<EscapeTarget> escapeTargetList = escapeTargetListMap.get(sourceBlock);
if (escapeTargetList == null) {
escapeTargetList = Collections.emptyList();
}
return escapeTargetList.iterator();
}
}
/**
* Inlining context. This essentially consists of a inlining site and a
* subroutine to be inlined. A stack of calling contexts is maintained in
* order to resolve EscapeTargets.
*/
private static class Context {
private final Context caller;
private final Subroutine subroutine;
private final CFG result;
private final IdentityHashMap<BasicBlock, BasicBlock> blockMap;
private final LinkedList<BasicBlock> workList;
/**
* Constructor.
*
* @param caller
* the calling context
* @param subroutine
* the subroutine being inlined
* @param result
* the result CFG
*/
public Context(@Nullable Context caller, Subroutine subroutine, CFG result) {
this.caller = caller;
this.subroutine = subroutine;
this.result = result;
this.blockMap = new IdentityHashMap<>();
this.workList = new LinkedList<>();
}
/**
* Get the calling context.
*/
public Context getCaller() {
return caller;
}
/**
* Get the subroutine being inlined.
*/
public Subroutine getSubroutine() {
return subroutine;
}
/**
* Get the result CFG.
*/
public CFG getResult() {
return result;
}
/**
* Add a basic block to the inlining work list.
*
public void addItem(BasicBlock item) {
workList.add(item);
}*/
/**
* Are there more work list items?
*/
public boolean hasMoreWork() {
return !workList.isEmpty();
}
/**
* Get the next work list item (basic block to be inlined).
*/
public BasicBlock nextItem() {
return workList.removeFirst();
}
/**
* Map a basic block in a subroutine to the corresponding block in the
* resulting CFG.
*
* @param subBlock
* the subroutine block
* @param resultBlock
* the result CFG block
*/
public void mapBlock(BasicBlock subBlock, BasicBlock resultBlock) {
blockMap.put(subBlock, resultBlock);
}
/**
* Get the block in the result CFG corresponding to the given subroutine
* block.
*
* @param subBlock
* the subroutine block
* @return the result CFG block
*/
public BasicBlock getBlock(BasicBlock subBlock) {
BasicBlock resultBlock = blockMap.get(subBlock);
if (resultBlock == null) {
resultBlock = result.allocate();
blockMap.put(subBlock, resultBlock);
workList.add(subBlock);
}
return resultBlock;
}
/**
* Check to ensure that this context is not the result of recursion.
*/
public void checkForRecursion() throws CFGBuilderException {
Context callerContext = caller;
while (callerContext != null) {
if (callerContext.subroutine == this.subroutine) {
throw new CFGBuilderException("JSR recursion detected!");
}
callerContext = callerContext.caller;
}
}
}
/*
* ----------------------------------------------------------------------
* Instance data
* ----------------------------------------------------------------------
*/
private final MethodGen methodGen;
private final ConstantPoolGen cpg;
private final ExceptionHandlerMap exceptionHandlerMap;
private final BitSet usedInstructionSet;
private final LinkedList<Subroutine> subroutineWorkList;
private final IdentityHashMap<InstructionHandle, Subroutine> jsrSubroutineMap;
private final Map<FieldDescriptor, Integer> addedFields = new HashMap<>();
private Subroutine topLevelSubroutine;
private CFG cfg;
/*
* ----------------------------------------------------------------------
* Public methods
* ----------------------------------------------------------------------
*/
/**
* Constructor.
*
* @param methodGen
* the method to build a CFG for
*/
public BetterCFGBuilder2(@Nonnull MethodDescriptor descriptor, @Nonnull MethodGen methodGen) {
this.methodGen = methodGen;
this.cpg = methodGen.getConstantPool();
IAnalysisCache analysisCache = Global.getAnalysisCache();
StandardTypeMerger merger = null;
ExceptionSetFactory exceptionSetFactory;
try {
exceptionSetFactory = analysisCache.getMethodAnalysis(ExceptionSetFactory.class, descriptor);
merger = new StandardTypeMerger(AnalysisContext.currentAnalysisContext()
.getLookupFailureCallback(), exceptionSetFactory);
} catch (CheckedAnalysisException e) {
AnalysisContext.logError("Unable to generate exceptionSetFactory for " + descriptor, e);
}
this.exceptionHandlerMap = new ExceptionHandlerMap(methodGen, merger);
this.usedInstructionSet = new BitSet();
this.jsrSubroutineMap = new IdentityHashMap<>();
this.subroutineWorkList = new LinkedList<>();
}
public int getIndex(FieldDescriptor f) {
Integer i = addedFields.get(f);
if (i != null) {
return i;
}
int index = cpg.addFieldref(f.getSlashedClassName(), f.getName(), f.getSignature());
addedFields.put(f, index);
return index;
}
public void optimize(InstructionList instructionList) {
InstructionHandle head = instructionList.getStart();
while (head != null) {
Instruction i = head.getInstruction();
if (i instanceof INVOKESTATIC) {
INVOKESTATIC is = (INVOKESTATIC) i;
String name = is.getMethodName(cpg);
String signature = is.getSignature(cpg);
if (name.startsWith("access$")) {
XMethod invoked = XFactory.createXMethod(is, cpg);
FieldDescriptor field = invoked.getAccessMethodForField();
if (field != null) {
boolean isSetter = signature.endsWith("V");
Instruction replacement;
int index = getIndex(field);
if (field.isStatic()) {
if (isSetter) {
replacement = new PUTSTATIC(index);
} else {
replacement = new GETSTATIC(index);
}
} else {
if (isSetter) {
replacement = new PUTFIELD(index);
} else {
replacement = new GETFIELD(index);
}
}
head.swapInstruction(replacement);
/*
if (false)
System.out.println("Substituting " + (isSetter ? "set" : "get") + " of " + field + " for call of "
+ invoked + " in " + methodGen.getClassName() + "." + methodGen.getName()
+ methodGen.getSignature());
*/
}
}
}
if (i instanceof IfInstruction) {
IfInstruction ii = (IfInstruction) i;
InstructionHandle target = ii.getTarget();
InstructionHandle next = head.getNext();
if (target.equals(next)) {
int consumed = ii.consumeStack(methodGen.getConstantPool());
if (consumed != 1 && consumed != 2) {
throw new IllegalStateException();
}
head.swapInstruction(consumed == 1 ? new POP() : new POP2());
}
}
if (i instanceof IFNULL || i instanceof IFNONNULL) {
IfInstruction ii = (IfInstruction) i;
InstructionHandle target = ii.getTarget();
InstructionHandle next1 = head.getNext(); // ICONST
if (next1 == null) {
break;
}
if (next1.getInstruction() instanceof ICONST) {
InstructionHandle next2 = next1.getNext(); // GOTO
if (next2 == null) {
break;
}
InstructionHandle next3 = next2.getNext(); // ICONST
if (next3 == null) {
break;
}
InstructionHandle next4 = next3.getNext();
if (next4 == null) {
break;
}
if (target.equals(next3) && next2.getInstruction() instanceof GOTO
&& next3.getInstruction() instanceof ICONST && next1.getTargeters().length == 0
&& next2.getTargeters().length == 0 && next3.getTargeters().length == 1
&& next4.getTargeters().length == 1) {
int c1 = ((ICONST) next1.getInstruction()).getValue().intValue();
GOTO g = (GOTO) next2.getInstruction();
int c2 = ((ICONST) next3.getInstruction()).getValue().intValue();
if (g.getTarget().equals(next4) && (c1 == 1 && c2 == 0 || c1 == 0 && c2 == 1)) {
boolean nullIsTrue = i instanceof IFNULL && c2 == 1 || i instanceof IFNONNULL && c2 == 0;
if (nullIsTrue) {
// System.out.println("Found NULL2Z instruction");
head.swapInstruction(new NULL2Z());
} else {
// System.out.println("Found NONNULL2Z instruction");
head.swapInstruction(new NONNULL2Z());
}
next3.removeAllTargeters();
next4.removeAllTargeters();
next1.swapInstruction(new NOP());
next2.swapInstruction(new NOP());
next3.swapInstruction(new NOP());
}
}
}
}
if (i instanceof ACONST_NULL) {
InstructionHandle next = head.getNext();
assert next != null;
InstructionHandle next2 = next.getNext();
if (next2 != null && next.getInstruction() instanceof ALOAD) {
Instruction check = next2.getInstruction();
if (check instanceof IF_ACMPNE || check instanceof IF_ACMPEQ) {
// need to update
head.swapInstruction(new NOP());
IfInstruction ifTest = (IfInstruction) check;
if (check instanceof IF_ACMPNE) {
next2.swapInstruction(new IFNONNULL(ifTest.getTarget()));
} else {
next2.swapInstruction(new IFNULL(ifTest.getTarget()));
}
}
}
}
head = head.getNext();
}
}
@Override
public void build() throws CFGBuilderException {
InstructionList instructionList = methodGen.getInstructionList();
optimize(instructionList);
topLevelSubroutine = new Subroutine(instructionList.getStart());
subroutineWorkList.add(topLevelSubroutine);
// Build top level subroutine and all JSR subroutines
while (!subroutineWorkList.isEmpty()) {
Subroutine subroutine = subroutineWorkList.removeFirst();
if (DEBUG) {
System.out.println("Starting subroutine " + subroutine.getStartInstruction());
}
build(subroutine);
}
// Inline everything into the top level subroutine
cfg = inlineAll();
// Add a NOP instruction to the entry block.
// This allows analyses to construct a Location
// representing the entry to the method.
BasicBlock entryBlock = cfg.getEntry();
InstructionList il = new InstructionList();
entryBlock.addInstruction(il.append(new NOP()));
cfg.checkIntegrity();
}
@Override
public CFG getCFG() {
return cfg;
}
/*
* ----------------------------------------------------------------------
* Implementation
* ----------------------------------------------------------------------
*/
/**
* Build a subroutine. We iteratively add basic blocks to the subroutine
* until there are no more blocks reachable from the calling context. As JSR
* instructions are encountered, new Subroutines are added to the subroutine
* work list.
*
* @param subroutine
* the subroutine
*/
private void build(Subroutine subroutine) throws CFGBuilderException {
// Prime the work list
subroutine.addEdgeAndExplore(subroutine.getEntry(), subroutine.getStartInstruction(), START_EDGE);
// Keep going until all basic blocks in the subroutine have been added
while (subroutine.hasMoreWork()) {
WorkListItem item = subroutine.nextItem();
InstructionHandle handle = item.getStartInstruction();
BasicBlock basicBlock = item.getBasicBlock();
// Add exception handler block (ETB) for exception-throwing
// instructions
if (isPEI(handle)) {
if (DEBUG) {
System.out.println("ETB block " + basicBlock.getLabel() + " for " + handle);
}
handleExceptions(subroutine, handle, basicBlock);
BasicBlock body = subroutine.allocateBasicBlock();
subroutine.addEdge(basicBlock, body, FALL_THROUGH_EDGE);
basicBlock = body;
}
if (DEBUG) {
System.out.println("BODY block " + basicBlock.getLabel() + " for " + handle);
}
if (!basicBlock.isEmpty()) {
throw new IllegalStateException("Block isn't empty!");
}
// Add instructions until we get to the end of the block
boolean endOfBasicBlock = false;
do {
Instruction ins = handle.getInstruction();
// Add the instruction to the block
if (DEBUG) {
System.out.println("BB " + basicBlock.getLabel() + ": adding" + handle);
}
basicBlock.addInstruction(handle);
subroutine.addInstruction(handle);
short opcode = ins.getOpcode();
// TODO: should check instruction to ensure that in a JSR
// subroutine
// no assignments are made to the local containing the return
// address.
// if (ins instanceof ASTORE) ...
if (opcode == Const.JSR || opcode == Const.JSR_W) {
// Find JSR subroutine, add it to subroutine work list if
// we haven't built a CFG for it yet
JsrInstruction jsr = (JsrInstruction) ins;
InstructionHandle jsrTarget = jsr.getTarget();
Subroutine jsrSubroutine = jsrSubroutineMap.get(jsrTarget);
if (jsrSubroutine == null) {
jsrSubroutine = new Subroutine(jsrTarget);
jsrSubroutineMap.put(jsrTarget, jsrSubroutine);
subroutineWorkList.add(jsrSubroutine);
}
// This ends the basic block.
// Add a JSR_EDGE to the successor.
// It will be replaced later by the inlined JSR subroutine.
subroutine.addEdgeAndExplore(basicBlock, handle.getNext(), JSR_EDGE);
endOfBasicBlock = true;
} else if (opcode == Const.RET) {
// End of JSR subroutine
subroutine.addEdge(basicBlock, subroutine.getExit(), RET_EDGE);
endOfBasicBlock = true;
} else {
TargetEnumeratingVisitor visitor = new TargetEnumeratingVisitor(handle, cpg);
if (visitor.isEndOfBasicBlock()) {
endOfBasicBlock = true;
// Add control edges as appropriate
if (visitor.instructionIsThrow()) {
handleExceptions(subroutine, handle, basicBlock);
} else if (visitor.instructionIsExit()) {
subroutine.setExitBlock(basicBlock);
} else if (visitor.instructionIsReturn()) {
subroutine.setReturnBlock(basicBlock);
} else {
Iterator<Target> i = visitor.targetIterator();
while (i.hasNext()) {
Target target = i.next();
subroutine.addEdgeAndExplore(basicBlock, target.getTargetInstruction(), target.getEdgeType());
}
}
}
}
if (!endOfBasicBlock) {
InstructionHandle next = handle.getNext();
if (next == null) {
throw new CFGBuilderException("Control falls off end of method: " + handle);
}
// Is the next instruction a control merge or a PEI?
if (isMerge(next) || isPEI(next)) {
subroutine.addEdgeAndExplore(basicBlock, next, FALL_THROUGH_EDGE);
endOfBasicBlock = true;
} else {
// Basic block continues
handle = next;
}
}
} while (!endOfBasicBlock);
}
}
/**
* Add exception edges for given instruction.
*
* @param subroutine
* the subroutine containing the instruction
* @param pei
* the instruction which throws an exception
* @param etb
* the exception thrower block (ETB) for the instruction
*/
private void handleExceptions(Subroutine subroutine, InstructionHandle pei, BasicBlock etb) {
etb.setExceptionThrower(pei);
// Remember whether or not a universal exception handler
// is reachable. If so, then we know that exceptions raised
// at this instruction cannot propagate out of the method.
boolean sawUniversalExceptionHandler = false;
List<CodeExceptionGen> exceptionHandlerList = exceptionHandlerMap.getHandlerList(pei);
if (exceptionHandlerList != null) {
for (CodeExceptionGen exceptionHandler : exceptionHandlerList) {
InstructionHandle handlerStart = exceptionHandler.getHandlerPC();
subroutine.addEdgeAndExplore(etb, handlerStart, HANDLED_EXCEPTION_EDGE);
if (Hierarchy.isUniversalExceptionHandler(exceptionHandler.getCatchType())) {
sawUniversalExceptionHandler = true;
}
}
}
// If required, mark this block as throwing an unhandled exception.
// For now, we assume that if there is no reachable handler that handles
// ANY exception type, then the exception can be thrown out of the
// method.
if (!sawUniversalExceptionHandler) {
if (DEBUG) {
System.out.println("Adding unhandled exception edge from " + pei);
}
subroutine.setUnhandledExceptionBlock(etb);
}
}
/**
* Return whether or not the given instruction can throw exceptions.
*
* @param handle
* the instruction
* @return true if the instruction can throw an exception, false otherwise
* @throws CFGBuilderException
*/
private boolean isPEI(InstructionHandle handle) throws CFGBuilderException {
Instruction ins = handle.getInstruction();
if (!(ins instanceof ExceptionThrower)) {
return false;
}
if (ins instanceof NEW) {
return false;
}
// if (ins instanceof ATHROW) return false;
if (ins instanceof GETSTATIC) {
return false;
}
if (ins instanceof PUTSTATIC) {
return false;
}
if (ins instanceof ReturnInstruction) {
return false;
}
if (ins instanceof INSTANCEOF) {
return false;
}
if (ins instanceof MONITOREXIT) {