/
TypeTightener.java
1020 lines (919 loc) · 36.2 KB
/
TypeTightener.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
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.dev.jjs.impl;
import com.google.gwt.dev.jjs.SourceOrigin;
import com.google.gwt.dev.jjs.ast.CanBeAbstract;
import com.google.gwt.dev.jjs.ast.CanBeStatic;
import com.google.gwt.dev.jjs.ast.Context;
import com.google.gwt.dev.jjs.ast.JArrayRef;
import com.google.gwt.dev.jjs.ast.JBinaryOperation;
import com.google.gwt.dev.jjs.ast.JBinaryOperator;
import com.google.gwt.dev.jjs.ast.JCastOperation;
import com.google.gwt.dev.jjs.ast.JClassType;
import com.google.gwt.dev.jjs.ast.JConditional;
import com.google.gwt.dev.jjs.ast.JDeclarationStatement;
import com.google.gwt.dev.jjs.ast.JDeclaredType;
import com.google.gwt.dev.jjs.ast.JExpression;
import com.google.gwt.dev.jjs.ast.JField;
import com.google.gwt.dev.jjs.ast.JFieldRef;
import com.google.gwt.dev.jjs.ast.JGwtCreate;
import com.google.gwt.dev.jjs.ast.JInstanceOf;
import com.google.gwt.dev.jjs.ast.JInterfaceType;
import com.google.gwt.dev.jjs.ast.JLocal;
import com.google.gwt.dev.jjs.ast.JMethod;
import com.google.gwt.dev.jjs.ast.JMethodCall;
import com.google.gwt.dev.jjs.ast.JNewInstance;
import com.google.gwt.dev.jjs.ast.JParameter;
import com.google.gwt.dev.jjs.ast.JParameterRef;
import com.google.gwt.dev.jjs.ast.JProgram;
import com.google.gwt.dev.jjs.ast.JReferenceType;
import com.google.gwt.dev.jjs.ast.JReturnStatement;
import com.google.gwt.dev.jjs.ast.JRunAsync;
import com.google.gwt.dev.jjs.ast.JTryStatement;
import com.google.gwt.dev.jjs.ast.JType;
import com.google.gwt.dev.jjs.ast.JTypeOracle;
import com.google.gwt.dev.jjs.ast.JVariable;
import com.google.gwt.dev.jjs.ast.JVariableRef;
import com.google.gwt.dev.jjs.ast.JVisitor;
import com.google.gwt.dev.jjs.ast.js.JsniFieldRef;
import com.google.gwt.dev.jjs.ast.js.JsniMethodRef;
import com.google.gwt.dev.util.log.speedtracer.CompilerEventType;
import com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger;
import com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger.Event;
import com.google.gwt.thirdparty.guava.common.annotations.VisibleForTesting;
import com.google.gwt.thirdparty.guava.common.base.Predicate;
import com.google.gwt.thirdparty.guava.common.collect.HashMultimap;
import com.google.gwt.thirdparty.guava.common.collect.ImmutableMap;
import com.google.gwt.thirdparty.guava.common.collect.Lists;
import com.google.gwt.thirdparty.guava.common.collect.Multimap;
import com.google.gwt.thirdparty.guava.common.collect.Sets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
/**
* The purpose of this pass is to record "type flow" information and then use
* the information to infer places where "tighter" (that is, more specific)
* types can be inferred for locals, fields, parameters, and method return
* types. We also optimize dynamic casts and instanceof operations.
*
* Examples:
*
* This declaration of variable foo:
*
* <pre>
* final List foo = new ArrayList();
* </pre>
*
* can be tightened from List to ArrayList because no type other than ArrayList
* can ever be assigned to foo.
*
* The return value of the method bar:
*
* <pre>
* Collection bar() {
* return new LinkedHashSet;
* }
* </pre>
*
* can be tightened from Collection to LinkedHashSet since it
* will never return any other type.
*
* By working in conjunction with {@link MethodCallTightener}, Type tightening
* can eliminate generating run-time dispatch code for polymorphic methods.
*
* Type flow occurs automatically in most JExpressions. But locals, fields,
* parameters, and method return types serve as "way points" where type
* information is fixed based on the declared type. Type tightening can be done
* by analyzing the types "flowing" into each way point, and then updating the
* declared type of the way point to be a more specific type than it had before.
*
* Oddly, it's quite possible to tighten a variable to the Null type, which
* means either the variable was never assigned, or it was only ever assigned
* null. This is great for two reasons:
*
* 1) Once a variable has been tightened to null, it will no longer impact the
* variables that depend on it.
*
* 2) It creates some very interesting opportunities to optimize later, since we
* know statically that the value of the variable is always null.
*
* Open issue: we don't handle recursion where a method passes (some of) its own
* args to itself or returns its own call result. With our naive analysis, we
* can't figure out that tightening might occur.
*
* Type flow is not supported for primitive types, only reference types.
*/
public class TypeTightener {
/**
* Replaces dangling null references with dummy calls.
*/
public class FixDanglingRefsVisitor extends JChangeTrackingVisitor {
public FixDanglingRefsVisitor(OptimizerContext optimizerCtx) {
super(optimizerCtx);
}
@Override
public void endVisit(JFieldRef x, Context ctx) {
JExpression instance = x.getInstance();
JField field = x.getField();
if (field.isStatic() && instance != null) {
// this doesn't really belong here, but while we're here let's remove
// non-side-effect qualifiers to statics
if (!instance.hasSideEffects()) {
JFieldRef fieldRef =
new JFieldRef(x.getSourceInfo(), null, field, x.getEnclosingType());
ctx.replaceMe(fieldRef);
}
} else if (isNullReference(field, instance)
&& field != program.getNullField()) {
// Change any dereference of null to use the null field
ctx.replaceMe(Pruner.transformToNullFieldRef(x, program));
}
}
@Override
public void endVisit(JMethodCall x, Context ctx) {
JExpression instance = x.getInstance();
JMethod method = x.getTarget();
boolean isStaticImpl = program.isStaticImpl(method);
if (method.isStatic() && !isStaticImpl && instance != null) {
// TODO: move to DeadCodeElimination.
// this doesn't really belong here, but while we're here let's remove
// non-side-effect qualifiers to statics
if (!instance.hasSideEffects()) {
JMethodCall newCall = new JMethodCall(x.getSourceInfo(), null, x.getTarget());
newCall.addArgs(x.getArgs());
ctx.replaceMe(newCall);
}
} else if (isNullReference(method, instance)) {
ctx.replaceMe(Pruner.transformToNullMethodCall(x, program));
} else if (isStaticImpl && method.getParams().size() > 0
&& method.getParams().get(0).isThis() && x.getArgs().size() > 0
&& x.getArgs().get(0).getType() == program.getTypeNull()) {
// bind null instance calls to the null method for static impls
ctx.replaceMe(Pruner.transformToNullMethodCall(x, program));
}
}
@Override
public void endVisit(JNewInstance x, Context ctx) {
// Do not visit.
}
}
/*
* TODO(later): handle recursion, self-assignment, arrays, method tightening
* on invocations from within JSNI blocks
*/
/**
* Record "type flow" information. Variables receive type flow via assignment.
* As a special case, Parameters also receive type flow based on the types of
* arguments used when calling the containing method (think of this as a kind
* of assignment). Method return types receive type flow from their contained
* return statements, plus the return type of any methods that
* override/implement them.
*
* Note that we only have to run this pass ONCE to record the relationships,
* because type tightening never changes any relationships, only the types of
* the things related. In my original implementation, I had naively mapped
* nodes onto sets of JReferenceType directly, which meant I had to rerun this
* visitor each time.
*/
private class RecordVisitor extends JVisitor {
private JMethod currentMethod;
private Predicate<JField> canUninitializedValueBeObserved;
/**
* The call trace invoked by arguments in a method call. It is used to record
* {@code callersByFieldRefArg} and {@code callersByMethodCallArg}.
* For example, fun1(fun2(fun3(), fun4()), fun5()); The stack would be ...
* fun1 -> fun2 -> fun3; (pop fun3, push fun4)
* fun1 -> fun2 -> fun4; (pop fun4)
* fun1 -> fun2; (pop fun2, push fun5)
* fun1 -> fun5; (pop fun5)
* fun1;
*/
private Stack<JMethod> nestedCallTrace = new Stack<JMethod>();
@Override
public void endVisit(JBinaryOperation x, Context ctx) {
if (x.isAssignment() && (x.getType() instanceof JReferenceType)) {
JExpression lhs = x.getLhs();
if (lhs instanceof JVariableRef) {
addAssignment(((JVariableRef) lhs).getTarget(), x.getRhs());
} else {
assert lhs instanceof JArrayRef;
}
}
}
@Override
public void endVisit(JClassType x, Context ctx) {
if (program.typeOracle.isInstantiatedType(x)) {
for (JClassType cur = x; cur != null; cur = cur.getSuperClass()) {
addImplementor(cur, x);
addInterfacesImplementorRecursive(cur, x);
}
}
}
@Override
public void endVisit(JDeclarationStatement x, Context ctx) {
JExpression initializer = x.getInitializer();
if (initializer != null) {
addAssignment(x.getVariableRef().getTarget(), initializer);
}
}
@Override
public void endVisit(JField x, Context ctx) {
if (!x.hasInitializer() || canUninitializedValueBeObserved.apply(x)) {
addAssignment(x, x.getType().getDefaultValue());
}
currentMethod = null;
}
@Override
public void endVisit(JFieldRef x, Context ctx) {
if (!nestedCallTrace.empty()) {
calledMethodsByFieldRefArg.put(x.getField(), nestedCallTrace.peek());
}
}
@Override
public void endVisit(JMethod x, Context ctx) {
currentMethod = null;
}
@Override
public void endVisit(JMethodCall x, Context ctx) {
// All of the params in the target method are considered to be assigned by
// the arguments from the caller
Iterator<JExpression> argIt = x.getArgs().iterator();
List<JParameter> params = x.getTarget().getParams();
for (JParameter param : params) {
JExpression arg = argIt.next();
if (param.getType() instanceof JReferenceType) {
addAssignment(param, arg);
}
}
nestedCallTrace.pop();
if (!nestedCallTrace.empty()) {
calledMethodsByMethodCallArg.put(x.getTarget(), nestedCallTrace.peek());
}
}
@Override
public void endVisit(JReturnStatement x, Context ctx) {
if (currentMethod.getType() instanceof JReferenceType) {
addReturn(currentMethod, x.getExpr());
}
}
@Override
public void endVisit(JsniFieldRef x, Context ctx) {
if (x.isLvalue()) {
// If this happens in JSNI, we can't make any type-tightening
// assumptions. Fake an assignment-to-self to prevent tightening.
addAssignment(x.getTarget(), x);
}
}
@Override
public void endVisit(JsniMethodRef x, Context ctx) {
// If this happens in JSNI, we can't make any type-tightening assumptions
// Fake an assignment-to-self on all args to prevent tightening
JMethod method = x.getTarget();
for (JParameter param : method.getParams()) {
addAssignment(param, new JParameterRef(SourceOrigin.UNKNOWN, param));
}
}
@Override
public void endVisit(JTryStatement x, Context ctx) {
// Never tighten args to catch blocks
// Fake an assignment-to-self to prevent tightening
for (JTryStatement.CatchClause clause : x.getCatchClauses()) {
addAssignment(clause.getArg().getTarget(), clause.getArg());
}
}
/**
* Merge param call args across overriders/implementors. We can't tighten a
* param type in an overriding method if the declaring method is looser.
*/
@Override
public boolean visit(JMethod x, Context ctx) {
currentMethod = x;
if (x.canBePolymorphic()) {
/*
* Add an assignment to each parameter from that same parameter in every
* method this method overrides.
*/
Collection<JMethod> overrides = x.getOverriddenMethods();
if (overrides.isEmpty()) {
return true;
}
for (int j = 0, c = x.getParams().size(); j < c; ++j) {
JParameter param = x.getParams().get(j);
Collection<JParameter> set = paramUpRefs.get(param);
if (set == null) {
set = new LinkedHashSet<JParameter>();
paramUpRefs.put(param, set);
}
for (JMethod baseMethod : overrides) {
JParameter baseParam = baseMethod.getParams().get(j);
set.add(baseParam);
}
}
}
return true;
}
@Override
public boolean visit(JMethodCall x, Context ctx) {
nestedCallTrace.push(x.getTarget());
return true;
}
public void record(JProgram program) {
canUninitializedValueBeObserved = ComputePotentiallyObservableUninitializedValues
.analyze(program);
accept(program);
}
private void addAssignment(JVariable target, JExpression rhs) {
add(target, rhs, assignments);
}
private void addImplementor(JReferenceType target, JClassType implementor) {
add(target, implementor, implementors);
}
private void addInterfacesImplementorRecursive(JDeclaredType target, JClassType implementor) {
for (JInterfaceType implment : target.getImplements()) {
addImplementor(implment, implementor);
addInterfacesImplementorRecursive(implment, implementor);
}
}
private void addReturn(JMethod target, JExpression expr) {
add(target, expr, returns);
}
}
/**
* Wherever possible, use the type flow information recorded by RecordVisitor
* to change the declared type of a field, local, parameter, or method to a
* more specific type.
*
* Also optimize dynamic casts and instanceof operations where possible.
*/
public class TightenTypesVisitor extends JChangeTrackingVisitor {
public TightenTypesVisitor(OptimizerContext optimizerCtx) {
super(optimizerCtx);
}
/**
* Tries to determine a specific concrete type for the cast, then either
* removes the cast, or tightens the cast to a narrower type.
*
* If static analysis determines that a cast is not possible, swap in a cast
* to a null type. This will later be normalized into throwing an
* Exception.
*
* @see ImplementCastsAndTypeChecks
*/
@Override
public void endVisit(JCastOperation x, Context ctx) {
JType argType = x.getExpr().getType();
if (!(x.getCastType() instanceof JReferenceType) || !(argType instanceof JReferenceType)) {
return;
}
JReferenceType toType = getSingleConcreteType(x.getCastType());
if (toType == null) {
toType = (JReferenceType) x.getCastType();
}
JReferenceType fromType = getSingleConcreteType(argType);
if (fromType == null) {
fromType = (JReferenceType) argType;
}
boolean triviallyTrue = false;
boolean triviallyFalse = false;
JTypeOracle typeOracle = program.typeOracle;
if (typeOracle.canTriviallyCast(fromType, toType)) {
triviallyTrue = true;
} else if (!typeOracle.isInstantiatedType(toType)) {
triviallyFalse = true;
} else if (!typeOracle.canTheoreticallyCast(fromType, toType)) {
triviallyFalse = true;
}
if (triviallyTrue) {
// remove the cast operation
ctx.replaceMe(x.getExpr());
} else if (triviallyFalse && toType != program.getTypeNull()) {
// replace with a placeholder cast to NULL, unless it's already a cast to NULL
JCastOperation newOp =
new JCastOperation(x.getSourceInfo(), program.getTypeNull(), x.getExpr());
ctx.replaceMe(newOp);
} else {
// If possible, try to use a narrower cast
JReferenceType tighterType = getSingleConcreteType(toType);
if (tighterType != null && tighterType != toType) {
JCastOperation newOp = new JCastOperation(x.getSourceInfo(), tighterType, x.getExpr());
ctx.replaceMe(newOp);
}
}
}
@Override
public void endVisit(JConditional x, Context ctx) {
if (x.getType() instanceof JReferenceType) {
JReferenceType refType = (JReferenceType) x.getType();
JReferenceType resultType = program.strengthenType(refType, Arrays.asList(
(JReferenceType) x.getThenExpr().getType(),
(JReferenceType) x.getElseExpr().getType()));
if (refType != resultType) {
x.setType(resultType);
madeChanges();
}
}
}
@Override
public void exit(JField x, Context ctx) {
// TODO: we should also skip @JsType fields when we implement them.
if (program.codeGenTypes.contains(x.getEnclosingType())
|| program.typeOracle.isExportedField(x)) {
// We cannot tighten this field as we don't know all callers.
return;
}
if (!x.isVolatile()) {
tighten(x);
}
}
@Override
public void endVisit(JGwtCreate x, Context ctx) {
List<JReferenceType> typeList = new ArrayList<JReferenceType>();
for (JExpression expr : x.getInstantiationExpressions()) {
JReferenceType type = (JReferenceType) expr.getType();
typeList.add(type);
}
JReferenceType refType = (JReferenceType) x.getType();
JReferenceType resultType = program.strengthenType(refType, typeList);
if (refType != resultType) {
x.setType(resultType);
madeChanges();
}
}
@Override
public void endVisit(JInstanceOf x, Context ctx) {
JType argType = x.getExpr().getType();
if (!(argType instanceof JReferenceType)) {
// TODO: is this even possible? Replace with assert maybe.
return;
}
JReferenceType toType = getSingleConcreteType(x.getTestType());
if (toType == null) {
toType = x.getTestType();
}
JReferenceType fromType = getSingleConcreteType(argType);
if (fromType == null) {
fromType = (JReferenceType) argType;
}
AnalysisResult analysisResult = staticallyEvaluateInstanceOf(fromType, toType);
switch (analysisResult) {
case TRUE:
if (x.getExpr().getType().canBeNull()) {
// replace with a simple null test
JBinaryOperation neq =
new JBinaryOperation(x.getSourceInfo(), program.getTypePrimitiveBoolean(),
JBinaryOperator.NEQ, x.getExpr(), program.getLiteralNull());
ctx.replaceMe(neq);
} else {
ctx.replaceMe(
JjsUtils.createOptimizedMultiExpression(x.getExpr(),
program.getLiteralBoolean(true)));
}
break;
case FALSE:
// replace with a false literal
ctx.replaceMe(
JjsUtils.createOptimizedMultiExpression(x.getExpr(), program.getLiteralBoolean(false)));
break;
case UNKNOWN:
default:
// If possible, try to use a narrower cast
JReferenceType concreteType = getSingleConcreteType(toType);
if (concreteType != null) {
JInstanceOf newOp = new JInstanceOf(x.getSourceInfo(), concreteType, x.getExpr());
ctx.replaceMe(newOp);
}
break;
}
}
@Override
public void endVisit(JLocal x, Context ctx) {
tighten(x);
}
/**
* Tighten based on return types and overrides.
*/
@Override
public void exit(JMethod x, Context ctx) {
if (program.codeGenTypes.contains(x.getEnclosingType())) {
return;
}
if (!(x.getType() instanceof JReferenceType)) {
return;
}
JReferenceType refType = (JReferenceType) x.getType();
if (refType == program.getTypeNull()) {
return;
}
// tighten based on non-instantiability
if (!program.typeOracle.isInstantiatedType(refType)) {
x.setType(program.getTypeNull());
madeChanges();
return;
}
JReferenceType concreteType = getSingleConcreteType(x.getType());
if (concreteType != null) {
x.setType(concreteType);
madeChanges();
}
/*
* The only information that we can infer about native methods is if they
* are declared to return a leaf type.
*/
if (x.isNative() || program.typeOracle.isJsTypeMethod(x)
|| program.typeOracle.isJsFunctionMethod(x)) {
return;
}
// tighten based on both returned types and possible overrides
List<JReferenceType> typeList = new ArrayList<JReferenceType>();
Collection<JExpression> myReturns = returns.get(x);
if (myReturns != null) {
for (JExpression expr : myReturns) {
typeList.add((JReferenceType) expr.getType());
}
}
Collection<JMethod> overridingMethods = x.getOverridingMethods();
if (overridingMethods != null) {
for (JMethod method : overridingMethods) {
typeList.add((JReferenceType) method.getType());
}
}
JReferenceType resultType = program.strengthenType(refType, typeList);
if (refType != resultType) {
x.setType(resultType);
madeChanges();
}
}
/**
* Tighten the target method from the abstract base method to the final
* implementation.
*/
@Override
public void endVisit(JMethodCall x, Context ctx) {
if (!x.canBePolymorphic() || x.isVolatile()) {
return;
}
JMethod target = x.getTarget();
JMethod concreteMethod = getSingleConcreteMethodOverride(target);
assert concreteMethod != target;
if (concreteMethod != null) {
assert !x.isStaticDispatchOnly();
JMethodCall newCall = new JMethodCall(x.getSourceInfo(), x.getInstance(), concreteMethod);
newCall.addArgs(x.getArgs());
ctx.replaceMe(newCall);
target = concreteMethod;
x = newCall;
}
/*
* Mark a call as non-polymorphic if the targeted method is the only
* possible dispatch, given the qualifying instance type.
*/
if (!target.isAbstract()) {
JExpression instance = x.getInstance();
assert (instance != null);
JReferenceType instanceType = (JReferenceType) instance.getType();
Collection<JMethod> myOverriders = target.getOverridingMethods();
if (myOverriders != null) {
for (JMethod override : myOverriders) {
JReferenceType overrideType = override.getEnclosingType();
if (program.typeOracle.canTheoreticallyCast(instanceType, overrideType)) {
// This call is truly polymorphic.
// TODO: composite types! :)
return;
}
}
// The instance type is incompatible with all overrides.
}
assert !x.isStaticDispatchOnly();
x.setCannotBePolymorphic();
madeChanges();
}
}
@Override
public void endVisit(JParameter x, Context ctx) {
JMethod currentMethod = getCurrentMethod();
if (program.codeGenTypes.contains(currentMethod.getEnclosingType())
|| program.typeOracle.isExportedMethod(currentMethod)
|| program.typeOracle.isJsFunctionMethod(currentMethod)
|| program.typeOracle.isJsTypeMethod(currentMethod)) {
// We cannot tighten this parameter as we don't know all callers.
return;
}
tighten(x);
}
@Override
public boolean visit(JRunAsync x, Context ctx) {
// JRunAsync's onSuccessCall is not normally traversed but should be here.
x.traverseOnSuccess(this);
return true;
}
@Override
public boolean visit(JClassType x, Context ctx) {
// don't mess with classes used in code gen
if (program.codeGenTypes.contains(x)) {
return false;
}
return true;
}
@Override
public boolean enter(JMethod x, Context ctx) {
/*
* Explicitly NOT visiting native methods since we can't infer further
* type information.
*/
return !x.isNative();
}
/**
* Find a replacement method. If the original method is abstract, this will
* return the leaf, final implementation of the method. If the method is
* already concrete, but enclosed by an abstract type, the overriding method
* from the leaf concrete type will be returned. If the method is static,
* return <code>null</code> no matter what.
*/
private JMethod getSingleConcreteMethodOverride(JMethod method) {
if (!method.canBePolymorphic()) {
return null;
}
if (getSingleConcreteType(method.getEnclosingType()) != null) {
return getSingleConcrete(method, ImmutableMap.of(method, method.getOverridingMethods()));
} else {
return null;
}
}
/**
* Given an abstract type, return the single concrete implementation of that
* type.
*/
private JReferenceType getSingleConcreteType(JType type) {
if (type instanceof JReferenceType) {
JReferenceType refType = (JReferenceType) type;
if (refType.isAbstract()) {
JClassType singleConcrete = getSingleConcrete(refType.getUnderlyingType(), implementors);
assert (singleConcrete == null || program.typeOracle.isInstantiatedType(singleConcrete));
if (singleConcrete == null) {
return null;
}
return refType.canBeNull() ? singleConcrete : singleConcrete.getNonNull();
}
}
return null;
}
/**
* Tighten based on assignment, and for parameters, callArgs as well.
*/
private void tighten(JVariable x) {
if (!(x.getType() instanceof JReferenceType)) {
return;
}
JReferenceType refType = (JReferenceType) x.getType();
if (refType == program.getTypeNull()) {
return;
}
// tighten based on non-instantiability
if (!program.typeOracle.isInstantiatedType(refType)) {
x.setType(program.getTypeNull());
madeChanges();
return;
}
// tighten based on leaf types
JReferenceType leafType = getSingleConcreteType(refType);
if (leafType != null) {
x.setType(leafType);
madeChanges();
return;
}
// tighten based on assignment
List<JReferenceType> typeList = Lists.newArrayList();
Collection<JExpression> myAssignments = assignments.get(x);
if (myAssignments != null) {
for (JExpression expr : myAssignments) {
JType type = expr.getType();
if (!(type instanceof JReferenceType)) {
return; // something fishy is going on, just abort
}
typeList.add((JReferenceType) type);
}
}
if (x instanceof JParameter) {
Collection<JParameter> myParams = paramUpRefs.get(x);
if (myParams != null) {
for (JParameter param : myParams) {
typeList.add((JReferenceType) param.getType());
}
}
}
JReferenceType resultType = program.strengthenType(refType, typeList);
if (refType != resultType) {
x.setType(resultType);
madeChanges();
}
}
}
private static final String NAME = TypeTightener.class.getSimpleName();
public static OptimizerStats exec(JProgram program, OptimizerContext optimizerCtx) {
Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
OptimizerStats stats = new TypeTightener(program).execImpl(optimizerCtx);
optimizerCtx.incOptimizationStep();
optimizeEvent.end("didChange", "" + stats.didChange());
return stats;
}
@VisibleForTesting
static OptimizerStats exec(JProgram program) {
return exec(program, new FullOptimizerContext(program));
}
private static <T, V> void add(T target, V value, Map<T, Collection<V>> map) {
Collection<V> list = map.get(target);
if (list == null) {
list = new LinkedHashSet<V>();
map.put(target, list);
}
list.add(value);
}
/**
* Find exactly one concrete element for a key in a Map of Sets. If there are
* none or more than one concrete element, return <code>null</code>.
*/
private static <B, T extends CanBeAbstract> T getSingleConcrete(B x,
Map<? super B, ? extends Collection<T>> map) {
Collection<T> collection = map.get(x);
// No collection, then no concrete version
if (collection == null) {
return null;
}
T toReturn = null;
for (T elt : collection) {
if (elt.isAbstract()) {
continue;
}
// If we already have previously seen a concrete element, fail
if (toReturn != null) {
return null;
} else {
toReturn = elt;
}
}
return toReturn;
}
/**
* For each program Variable (includes fields, locals and parameters) tracks the set
* of expressions that are assigned to them. Assignments include parameter instantiations.
*
*/
private final Map<JVariable, Collection<JExpression>> assignments =
new IdentityHashMap<JVariable, Collection<JExpression>>();
/**
* For each type tracks all classes the extend or implement it.
*/
private final Map<JReferenceType, Collection<JClassType>> implementors =
new IdentityHashMap<JReferenceType, Collection<JClassType>>();
/**
* For each parameter P (in method M) tracks the set of parameters that share its position in all
* the methods that are overridden by M.
*/
private final Map<JParameter, Collection<JParameter>> paramUpRefs =
new IdentityHashMap<JParameter, Collection<JParameter>>();
/**
* For each method tracks the set of all expressions that are returned.
*/
private final Map<JMethod, Collection<JExpression>> returns =
new IdentityHashMap<JMethod, Collection<JExpression>>();
/**
* For each method call, record the method calls and field references in its arguments.
* When the callee methods or the referenced fields in the arguments are modified,
* it would be possible for the target method to be type tightened.
*/
private final Multimap<JMethod, JMethod> calledMethodsByMethodCallArg = HashMultimap.create();
private final Multimap<JField, JMethod> calledMethodsByFieldRefArg = HashMultimap.create();
private final JProgram program;
private TypeTightener(JProgram program) {
this.program = program;
}
private OptimizerStats execImpl(OptimizerContext optimizerCtx) {
OptimizerStats stats = new OptimizerStats(NAME);
RecordVisitor recorder = new RecordVisitor();
recorder.record(program);
/*
* We must iterate multiple times because each way point we tighten creates
* more opportunities to do additional tightening for the things that depend
* on it.
*
* TODO(zundel): See if we can remove this loop, or otherwise run to less
* than completion if we compile with an option for less than 100% optimized
* output.
*/
int lastStep = optimizerCtx.getLastStepFor(NAME);
/*
* Set the last step to the step at which TypeTightener does the first iteration. Since the
* RecordVisitor is run only once, the information in {@code assignments} etc. is not updated.
* So it is still possible for the type tightened methods/fields to be type tightened for the
* next time.
*/
optimizerCtx.setLastStepFor(NAME, optimizerCtx.getOptimizationStep());
while (true) {
TightenTypesVisitor tightener = new TightenTypesVisitor(optimizerCtx);
Set<JMethod> affectedMethods =
computeAffectedMethods(optimizerCtx, lastStep);
Set<JField> affectedFields =
computeAffectedFields(optimizerCtx, lastStep);
optimizerCtx.traverse(tightener, affectedFields);
optimizerCtx.traverse(tightener, affectedMethods);
stats.recordModified(tightener.getNumMods());
lastStep = optimizerCtx.getOptimizationStep();
optimizerCtx.incOptimizationStep();
if (!tightener.didChange()) {
break;
}
}
if (stats.didChange()) {
FixDanglingRefsVisitor fixer = new FixDanglingRefsVisitor(optimizerCtx);
fixer.accept(program);
optimizerCtx.incOptimizationStep();
JavaAstVerifier.assertProgramIsConsistent(program);
}
return stats;
}
private Set<JMethod> computeAffectedMethods(OptimizerContext optimizerCtx, int lastStep) {
Set<JMethod> modifiedMethods = optimizerCtx.getModifiedMethodsSince(lastStep);
Set<JField> modifiedFields = optimizerCtx.getModifiedFieldsSince(lastStep);
Set<JMethod> affectedMethods = Sets.newLinkedHashSet();
// If the return type or parameters' types of a method are changed, its caller methods should be
// reanalyzed.
affectedMethods.addAll(optimizerCtx.getCallers(modifiedMethods));
// If a method is modified, its callee should be reanalyzed.
affectedMethods.addAll(optimizerCtx.getCallees(modifiedMethods));
// The removed callee methods (one or more method calls to it are removed) should be reanalyzed.
affectedMethods.addAll(optimizerCtx.getRemovedCalleeMethodsSince(lastStep));
// If a method's return type is changed, the called method whose argument calls the method
// should be reanalyzed.
for (JMethod method : modifiedMethods) {
affectedMethods.addAll(calledMethodsByMethodCallArg.get(method));
}
// If a method's return type or parameters' types are changed, its overriders and overridden
// methods should be reanalyzed. The overridden methods and overriders from typeOracle may have
// been pruned, so we have to check if they are in the AST.
for (JMethod method : modifiedMethods) {
affectedMethods.addAll(method.getOverriddenMethods());
affectedMethods.addAll(method.getOverridingMethods());
}
// If a field is changed, the methods that reference to it should be reanalyzed.
affectedMethods.addAll(optimizerCtx.getMethodsByReferencedFields(modifiedFields));
// If a field is changed, the caller methods which call it through argument should be
// reanalyzed.
for (JField field : modifiedFields) {
affectedMethods.addAll(calledMethodsByFieldRefArg.get(field));
}
// All the methods that are modified by other optimizer should be reanalyzed.
affectedMethods.addAll(modifiedMethods);
return affectedMethods;
}
private Set<JField> computeAffectedFields(OptimizerContext optimizerCtx, int lastStep) {
Set<JMethod> modifiedMethods = optimizerCtx.getModifiedMethodsSince(lastStep);
Set<JField> modifiedFields = optimizerCtx.getModifiedFieldsSince(lastStep);
Set<JField> affectedFields = Sets.newLinkedHashSet();
affectedFields.addAll(modifiedFields);
affectedFields.addAll(optimizerCtx.getReferencedFieldsByMethods(modifiedMethods));
return affectedFields;
}
private boolean isNullReference(CanBeStatic member, JExpression instance) {
return !member.isStatic() && instance.getType() == program.getTypeNull();
}
private enum AnalysisResult { TRUE, FALSE, UNKNOWN }
/**