/
summary_collector.dart
2400 lines (2107 loc) · 77.2 KB
/
summary_collector.dart
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 (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Creation of type flow summaries out of kernel AST.
library vm.transformations.type_flow.summary_collector;
import 'dart:core' hide Type;
import 'package:kernel/target/targets.dart';
import 'package:kernel/ast.dart' hide Statement, StatementVisitor;
import 'package:kernel/ast.dart' as ast show Statement, StatementVisitor;
import 'package:kernel/class_hierarchy.dart'
show ClassHierarchy, ClosedWorldClassHierarchy;
import 'package:kernel/type_environment.dart'
show StaticTypeContext, SubtypeCheckMode, TypeEnvironment;
import 'package:kernel/type_algebra.dart' show Substitution;
import 'calls.dart';
import 'native_code.dart';
import 'summary.dart';
import 'types.dart';
import 'utils.dart';
/// Summary collector relies on either full or partial mixin resolution.
/// Currently VmTarget.performModularTransformationsOnLibraries performs
/// partial mixin resolution.
const bool kPartialMixinResolution = true;
/// Normalizes and optimizes summary after it is created.
/// More specifically:
/// * Breaks loops between statements.
/// * Removes unused statements (except parameters and calls).
/// * Eliminates joins with a single input.
class _SummaryNormalizer extends StatementVisitor {
final Summary _summary;
final TypesBuilder _typesBuilder;
Set<Statement> _processed = new Set<Statement>();
Set<Statement> _pending = new Set<Statement>();
bool _inLoop = false;
_SummaryNormalizer(this._summary, this._typesBuilder);
void normalize() {
final List<Statement> statements = _summary.statements;
_summary.reset();
for (int i = 0; i < _summary.positionalParameterCount; i++) {
_processed.add(statements[i]);
_summary.add(statements[i]);
}
// Sort named parameters.
// TODO(dartbug.com/32292): make sure parameters are sorted in kernel AST
// and remove this sorting.
if (_summary.positionalParameterCount < _summary.parameterCount) {
List<Statement> namedParams = statements.sublist(
_summary.positionalParameterCount, _summary.parameterCount);
namedParams.sort((Statement s1, Statement s2) =>
(s1 as Parameter).name.compareTo((s2 as Parameter).name));
namedParams.forEach((Statement st) {
_processed.add(st);
_summary.add(st);
});
}
for (Statement st in statements) {
if (st is Call || st is TypeCheck) {
_normalizeExpr(st, false);
} else if (st is Use) {
_normalizeExpr(st.arg, true);
}
}
_summary.result = _normalizeExpr(_summary.result, true);
}
TypeExpr _normalizeExpr(TypeExpr st, bool isResultUsed) {
assertx(!_inLoop);
assertx(st is! Use);
if (st is Statement) {
if (isResultUsed && (st is Call)) {
st.setResultUsed();
}
if (_processed.contains(st)) {
return st;
}
if (_pending.add(st)) {
st.accept(this);
_pending.remove(st);
if (_inLoop) {
return _handleLoop(st);
}
if (st is Join) {
final n = st.values.length;
if (n == 0) {
return const EmptyType();
} else if (n == 1) {
return st.values.single;
} else {
final first = st.values.first;
if (first is Type) {
bool allMatch = true;
for (int i = 1; i < n; ++i) {
if (first != st.values[i]) {
allMatch = false;
break;
}
}
if (allMatch) {
return first;
}
}
}
} else if (st is Narrow) {
// This pattern may appear after approximations during summary
// normalization (so it's not enough to handle it in _makeNarrow).
final arg = st.arg;
if (arg is Type && st.type == const AnyType()) {
return (arg is NullableType) ? arg.baseType : arg;
}
}
_processed.add(st);
_summary.add(st);
return st;
} else {
// Cyclic expression.
return _handleLoop(st);
}
} else {
assertx(st is Type);
return st;
}
}
TypeExpr _handleLoop(Statement st) {
if (st is Join) {
// Approximate Join with static type.
_inLoop = false;
debugPrint("Approximated ${st} with ${st.staticType}");
Statistics.joinsApproximatedToBreakLoops++;
return _typesBuilder.fromStaticType(st.staticType, true);
} else {
// Step back until Join is found.
_inLoop = true;
return st;
}
}
@override
void visitNarrow(Narrow expr) {
expr.arg = _normalizeExpr(expr.arg, true);
}
@override
void visitJoin(Join expr) {
for (int i = 0; i < expr.values.length; i++) {
expr.values[i] = _normalizeExpr(expr.values[i], true);
if (_inLoop) {
return;
}
}
}
@override
void visitUse(Use expr) {
throw '\'Use\' statement should not be referenced: $expr';
}
@override
void visitCall(Call expr) {
for (int i = 0; i < expr.args.values.length; i++) {
expr.args.values[i] = _normalizeExpr(expr.args.values[i], true);
if (_inLoop) {
return;
}
}
}
@override
void visitCreateConcreteType(CreateConcreteType expr) {
for (int i = 0; i < expr.flattenedTypeArgs.length; ++i) {
expr.flattenedTypeArgs[i] =
_normalizeExpr(expr.flattenedTypeArgs[i], true);
if (_inLoop) return;
}
}
@override
void visitCreateRuntimeType(CreateRuntimeType expr) {
for (int i = 0; i < expr.flattenedTypeArgs.length; ++i) {
expr.flattenedTypeArgs[i] =
_normalizeExpr(expr.flattenedTypeArgs[i], true);
if (_inLoop) return;
}
}
@override
void visitTypeCheck(TypeCheck expr) {
expr.arg = _normalizeExpr(expr.arg, true);
if (_inLoop) return;
expr.type = _normalizeExpr(expr.type, true);
}
@override
void visitExtract(Extract expr) {
expr.arg = _normalizeExpr(expr.arg, true);
}
}
/// Detects whether the control flow can pass through the function body and
/// reach its end. Returns 'false' if it can prove that control never reaches
/// the end. Otherwise, conservatively returns 'true'.
class _FallthroughDetector extends ast.StatementVisitor<bool> {
// This fallthrough detector does not build control flow graph nor detect if
// a function has unreachable code. For simplicity, it assumes that all
// statements are reachable, so it just inspects the last statements of a
// function and checks if control can fall through them or not.
bool controlCanFallThrough(FunctionNode function) {
return function.body.accept(this);
}
@override
bool defaultStatement(ast.Statement node) =>
throw "Unexpected statement of type ${node.runtimeType}";
@override
bool visitExpressionStatement(ExpressionStatement node) =>
(node.expression is! Throw) && (node.expression is! Rethrow);
@override
bool visitBlock(Block node) =>
node.statements.isEmpty || node.statements.last.accept(this);
@override
bool visitEmptyStatement(EmptyStatement node) => true;
@override
bool visitAssertStatement(AssertStatement node) => true;
@override
bool visitLabeledStatement(LabeledStatement node) => true;
@override
bool visitBreakStatement(BreakStatement node) => false;
@override
bool visitWhileStatement(WhileStatement node) => true;
@override
bool visitDoStatement(DoStatement node) => true;
@override
bool visitForStatement(ForStatement node) => true;
@override
bool visitForInStatement(ForInStatement node) => true;
@override
bool visitSwitchStatement(SwitchStatement node) => true;
@override
bool visitContinueSwitchStatement(ContinueSwitchStatement node) => false;
@override
bool visitIfStatement(IfStatement node) =>
node.then == null ||
node.otherwise == null ||
node.then.accept(this) ||
node.otherwise.accept(this);
@override
bool visitReturnStatement(ReturnStatement node) => false;
@override
bool visitTryCatch(TryCatch node) =>
node.body.accept(this) ||
node.catches.any((Catch catch_) => catch_.body.accept(this));
@override
bool visitTryFinally(TryFinally node) =>
node.body.accept(this) && node.finalizer.accept(this);
@override
bool visitYieldStatement(YieldStatement node) => true;
@override
bool visitVariableDeclaration(VariableDeclaration node) => true;
@override
bool visitFunctionDeclaration(FunctionDeclaration node) => true;
}
/// Collects sets of captured variables, as well as variables
/// modified in loops and try blocks.
class _VariablesInfoCollector extends RecursiveVisitor<Null> {
/// Maps declared variables to their declaration index.
final Map<VariableDeclaration, int> varIndex = <VariableDeclaration, int>{};
/// Variable declarations.
final List<VariableDeclaration> varDeclarations = <VariableDeclaration>[];
/// Set of captured variables.
Set<VariableDeclaration> captured;
/// Set of variables which were modified for each loop, switch statement
/// and try block statement. Doesn't include captured variables and
/// variables declared inside the statement's body.
final Map<ast.Statement, Set<int>> modifiedSets = <ast.Statement, Set<int>>{};
/// Number of variables at function entry.
int numVariablesAtFunctionEntry = 0;
/// Active loops, switch statements and try blocks.
List<ast.Statement> activeStatements;
/// Number of variables at entry of active statements.
List<int> numVariablesAtActiveStatements;
_VariablesInfoCollector(Member member) {
member.accept(this);
}
int get numVariables => varDeclarations.length;
bool isCaptured(VariableDeclaration variable) =>
captured != null && captured.contains(variable);
Set<int> getModifiedVariables(ast.Statement st) {
return modifiedSets[st] ?? const <int>{};
}
void _visitFunction(LocalFunction node) {
final savedActiveStatements = activeStatements;
activeStatements = null;
final savedNumVariablesAtActiveStatements = numVariablesAtActiveStatements;
numVariablesAtActiveStatements = null;
final savedNumVariablesAtFunctionEntry = numVariablesAtFunctionEntry;
numVariablesAtFunctionEntry = numVariables;
node.function.accept(this);
activeStatements = savedActiveStatements;
numVariablesAtActiveStatements = savedNumVariablesAtActiveStatements;
numVariablesAtFunctionEntry = savedNumVariablesAtFunctionEntry;
}
bool _isDeclaredBefore(int variableIndex, int entryDeclarationCounter) =>
variableIndex < entryDeclarationCounter;
void _useVariable(VariableDeclaration variable, bool isVarAssignment) {
final index = varIndex[variable];
if (_isDeclaredBefore(index, numVariablesAtFunctionEntry)) {
(captured ??= <VariableDeclaration>{}).add(variable);
return;
}
if (isVarAssignment && activeStatements != null) {
for (int i = activeStatements.length - 1; i >= 0; --i) {
if (_isDeclaredBefore(index, numVariablesAtActiveStatements[i])) {
final st = activeStatements[i];
(modifiedSets[st] ??= <int>{}).add(index);
} else {
break;
}
}
}
}
void _startCollectingModifiedVariables(ast.Statement node) {
(activeStatements ??= <ast.Statement>[]).add(node);
(numVariablesAtActiveStatements ??= <int>[]).add(numVariables);
}
void _endCollectingModifiedVariables() {
activeStatements.removeLast();
numVariablesAtActiveStatements.removeLast();
}
@override
visitConstructor(Constructor node) {
// Need to visit parameters before initializers.
visitList(node.function.positionalParameters, this);
visitList(node.function.namedParameters, this);
visitList(node.initializers, this);
node.function.body?.accept(this);
}
@override
visitFunctionDeclaration(FunctionDeclaration node) {
node.variable.accept(this);
_visitFunction(node);
}
@override
visitFunctionExpression(FunctionExpression node) {
_visitFunction(node);
}
@override
visitVariableDeclaration(VariableDeclaration node) {
final int index = numVariables;
varDeclarations.add(node);
varIndex[node] = index;
node.visitChildren(this);
}
@override
visitVariableGet(VariableGet node) {
node.visitChildren(this);
_useVariable(node.variable, false);
}
@override
visitVariableSet(VariableSet node) {
node.visitChildren(this);
_useVariable(node.variable, true);
}
@override
visitTryCatch(TryCatch node) {
_startCollectingModifiedVariables(node);
node.body?.accept(this);
_endCollectingModifiedVariables();
visitList(node.catches, this);
}
@override
visitTryFinally(TryFinally node) {
_startCollectingModifiedVariables(node);
node.body?.accept(this);
_endCollectingModifiedVariables();
node.finalizer?.accept(this);
}
@override
visitWhileStatement(WhileStatement node) {
_startCollectingModifiedVariables(node);
node.visitChildren(this);
_endCollectingModifiedVariables();
}
@override
visitDoStatement(DoStatement node) {
_startCollectingModifiedVariables(node);
node.visitChildren(this);
_endCollectingModifiedVariables();
}
@override
visitForStatement(ForStatement node) {
visitList(node.variables, this);
_startCollectingModifiedVariables(node);
node.condition?.accept(this);
node.body?.accept(this);
visitList(node.updates, this);
_endCollectingModifiedVariables();
}
@override
visitForInStatement(ForInStatement node) {
node.iterable.accept(this);
_startCollectingModifiedVariables(node);
node.variable.accept(this);
node.body.accept(this);
_endCollectingModifiedVariables();
}
@override
visitSwitchStatement(SwitchStatement node) {
node.expression.accept(this);
_startCollectingModifiedVariables(node);
visitList(node.cases, this);
_endCollectingModifiedVariables();
}
}
Iterable<Name> getSelectors(ClassHierarchy hierarchy, Class cls,
{bool setters = false}) =>
hierarchy
.getInterfaceMembers(cls, setters: setters)
.map((Member m) => m.name);
enum FieldSummaryType { kFieldGuard, kInitializer }
/// Create a type flow summary for a member from the kernel AST.
class SummaryCollector extends RecursiveVisitor<TypeExpr> {
final Target target;
final TypeEnvironment _environment;
final ClosedWorldClassHierarchy _hierarchy;
final EntryPointsListener _entryPointsListener;
final TypesBuilder _typesBuilder;
final NativeCodeOracle _nativeCodeOracle;
final GenericInterfacesInfo _genericInterfacesInfo;
final Map<TreeNode, Call> callSites = <TreeNode, Call>{};
final Map<AsExpression, TypeCheck> explicitCasts =
<AsExpression, TypeCheck>{};
final _FallthroughDetector _fallthroughDetector = new _FallthroughDetector();
final Set<Name> _nullMethodsAndGetters = <Name>{};
final Set<Name> _nullSetters = <Name>{};
Summary _summary;
_VariablesInfoCollector _variablesInfo;
// Current value of each variable. May contain null if variable is not
// declared yet, or EmptyType if current location is unreachable
// (e.g. after return or throw).
List<TypeExpr> _variableValues;
// Contains Joins which accumulate all values of certain variables.
// Used only when all variable values should be merged regardless of control
// flow. Such accumulating joins are used for
// 1. captured variables, as closures may potentially see any value;
// 2. variables modified inside try blocks (while in the try block), as
// catch can potentially see any value assigned to a variable inside try
// block.
// If _variableCells[i] != null, then all values are accumulated in the
// _variableCells[i]. _variableValues[i] does not change and remains equal
// to _variableCells[i].
List<Join> _variableCells;
// Counts number of Joins inserted for each variable. Only used to set
// readable names for such joins (foo_0, foo_1 etc.)
List<int> _variableVersions;
// State of variables after corresponding LabeledStatement.
// Used to collect states from BreakStatements.
Map<LabeledStatement, List<TypeExpr>> _variableValuesAfterLabeledStatements;
// Joins corresponding to variables on entry to switch cases.
// Used to propagate state from ContinueSwitchStatement to a target case.
Map<SwitchCase, List<Join>> _joinsAtSwitchCases;
// Join which accumulates all return values.
Join _returnValue;
Parameter _receiver;
ConstantAllocationCollector constantAllocationCollector;
RuntimeTypeTranslatorImpl _translator;
StaticTypeContext _staticTypeContext;
// Currently only used for factory constructors.
Map<TypeParameter, TypeExpr> _fnTypeVariables;
SummaryCollector(
this.target,
this._environment,
this._hierarchy,
this._entryPointsListener,
this._typesBuilder,
this._nativeCodeOracle,
this._genericInterfacesInfo) {
assertx(_genericInterfacesInfo != null);
constantAllocationCollector = new ConstantAllocationCollector(this);
_nullMethodsAndGetters.addAll(getSelectors(
_hierarchy, _environment.coreTypes.nullClass,
setters: false));
_nullSetters.addAll(getSelectors(
_hierarchy, _environment.coreTypes.nullClass,
setters: true));
}
Summary createSummary(Member member,
{fieldSummaryType: FieldSummaryType.kInitializer}) {
debugPrint("===== ${member} =====");
assertx(!member.isAbstract);
_staticTypeContext = new StaticTypeContext(member, _environment);
_variablesInfo = new _VariablesInfoCollector(member);
_variableValues = new List<TypeExpr>(_variablesInfo.numVariables);
_variableCells = new List<Join>(_variablesInfo.numVariables);
_variableVersions = new List<int>.filled(_variablesInfo.numVariables, 0);
_variableValuesAfterLabeledStatements = null;
_joinsAtSwitchCases = null;
_returnValue = null;
_receiver = null;
final hasReceiver = hasReceiverArg(member);
if (member is Field) {
if (hasReceiver) {
final int numArgs =
fieldSummaryType == FieldSummaryType.kInitializer ? 1 : 2;
_summary = new Summary(
parameterCount: numArgs, positionalParameterCount: numArgs);
// TODO(alexmarkov): subclass cone
_receiver = _declareParameter("this",
_environment.coreTypes.legacyRawType(member.enclosingClass), null,
isReceiver: true);
} else {
_summary = new Summary();
}
_translator = new RuntimeTypeTranslatorImpl(
_summary, _receiver, null, _genericInterfacesInfo);
if (fieldSummaryType == FieldSummaryType.kInitializer) {
assertx(member.initializer != null);
_summary.result = _visit(member.initializer);
} else {
final Parameter valueParam =
_declareParameter("value", member.type, null);
_summary.result = _typeCheck(valueParam, member.type, member);
}
} else {
FunctionNode function = member.function;
final numTypeParameters = numTypeParams(member);
final firstParamIndex = (hasReceiver ? 1 : 0) + numTypeParameters;
_summary = new Summary(
parameterCount: firstParamIndex +
function.positionalParameters.length +
function.namedParameters.length,
positionalParameterCount:
firstParamIndex + function.positionalParameters.length,
requiredParameterCount:
firstParamIndex + function.requiredParameterCount);
if (numTypeParameters > 0) {
_fnTypeVariables = <TypeParameter, TypeExpr>{};
for (int i = 0; i < numTypeParameters; ++i) {
_fnTypeVariables[function.typeParameters[i]] =
_declareParameter(function.typeParameters[i].name, null, null);
}
}
if (hasReceiver) {
// TODO(alexmarkov): subclass cone
_receiver = _declareParameter("this",
_environment.coreTypes.legacyRawType(member.enclosingClass), null,
isReceiver: true);
}
_translator = new RuntimeTypeTranslatorImpl(
_summary, _receiver, _fnTypeVariables, _genericInterfacesInfo);
// Handle forwarding stubs. We need to check types against the types of
// the forwarding stub's target, [member.forwardingStubSuperTarget].
FunctionNode useTypesFrom = member.function;
if (member is Procedure &&
member.isForwardingStub &&
member.forwardingStubSuperTarget != null) {
final target = member.forwardingStubSuperTarget;
if (target is Field) {
useTypesFrom = FunctionNode(null, positionalParameters: [
VariableDeclaration("value", type: target.type)
]);
} else {
useTypesFrom = member.forwardingStubSuperTarget.function;
}
}
for (int i = 0; i < function.positionalParameters.length; ++i) {
final decl = function.positionalParameters[i];
_declareParameter(
decl.name,
_useTypeCheckForParameter(decl)
? null
: useTypesFrom.positionalParameters[i].type,
decl.initializer);
}
for (int i = 0; i < function.namedParameters.length; ++i) {
final decl = function.namedParameters[i];
_declareParameter(
decl.name,
_useTypeCheckForParameter(decl)
? null
: useTypesFrom.namedParameters[i].type,
decl.initializer);
}
int count = firstParamIndex;
for (int i = 0; i < function.positionalParameters.length; ++i) {
final decl = function.positionalParameters[i];
final type = useTypesFrom.positionalParameters[i].type;
TypeExpr param = _summary.statements[count++];
if (_useTypeCheckForParameter(decl)) {
param = _typeCheck(param, type, decl);
}
_declareVariable(decl, param);
}
for (int i = 0; i < function.namedParameters.length; ++i) {
final decl = function.namedParameters[i];
final type = useTypesFrom.namedParameters[i].type;
TypeExpr param = _summary.statements[count++];
if (_useTypeCheckForParameter(decl)) {
param = _typeCheck(param, type, decl);
}
_declareVariable(decl, param);
}
assertx(count == _summary.parameterCount);
_returnValue = new Join("%result", function.returnType);
_summary.add(_returnValue);
if (member is Constructor) {
// Make sure instance field initializers are visited.
for (var f in member.enclosingClass.members) {
if ((f is Field) && !f.isStatic && (f.initializer != null)) {
_entryPointsListener.addRawCall(
new DirectSelector(f, callKind: CallKind.FieldInitializer));
}
}
member.initializers.forEach(_visit);
}
if (function.body == null) {
TypeExpr type = _nativeCodeOracle.handleNativeProcedure(
member, _entryPointsListener, _typesBuilder, _translator);
if (type is! ConcreteType && type is! Statement) {
// Runtime type could be more precise than static type, so
// calculate intersection.
final typeCheck = _typeCheck(type, function.returnType, function);
_returnValue.values.add(typeCheck);
} else {
_returnValue.values.add(type);
}
} else {
_visit(function.body);
if (_fallthroughDetector.controlCanFallThrough(function)) {
_returnValue.values.add(_nullType);
}
}
_summary.result = _returnValue;
}
_staticTypeContext = null;
debugPrint("------------ SUMMARY ------------");
debugPrint(_summary);
debugPrint("---------------------------------");
new _SummaryNormalizer(_summary, _typesBuilder).normalize();
debugPrint("---------- NORM SUMMARY ---------");
debugPrint(_summary);
debugPrint("---------------------------------");
Statistics.summariesCreated++;
return _summary;
}
bool _useTypeCheckForParameter(VariableDeclaration decl) {
return decl.isCovariant || decl.isGenericCovariantImpl;
}
Args<Type> rawArguments(Selector selector) {
final member = selector.member;
assertx(member != null);
final List<Type> args = <Type>[];
final List<String> names = <String>[];
final numTypeParameters = numTypeParams(member);
for (int i = 0; i < numTypeParameters; ++i) {
args.add(const AnyType());
}
if (hasReceiverArg(member)) {
assertx(member.enclosingClass != null);
final receiver =
new ConeType(_typesBuilder.getTFClass(member.enclosingClass));
args.add(receiver);
}
switch (selector.callKind) {
case CallKind.Method:
if (member is! Field) {
final function = member.function;
assertx(function != null);
final int paramCount = function.positionalParameters.length +
function.namedParameters.length;
for (int i = 0; i < paramCount; i++) {
args.add(new Type.nullableAny());
}
if (function.namedParameters.isNotEmpty) {
for (var param in function.namedParameters) {
names.add(param.name);
}
// TODO(dartbug.com/32292): make sure parameters are sorted in
// kernel AST and remove this sorting.
names.sort();
}
}
break;
case CallKind.PropertyGet:
break;
case CallKind.PropertySet:
args.add(new Type.nullableAny());
break;
case CallKind.FieldInitializer:
break;
}
return new Args<Type>(args, names: names);
}
TypeExpr _visit(TreeNode node) => node.accept(this);
Args<TypeExpr> _visitArguments(TypeExpr receiver, Arguments arguments,
{bool passTypeArguments: false}) {
final args = <TypeExpr>[];
if (passTypeArguments) {
for (var type in arguments.types) {
args.add(_translator.translate(type));
}
}
if (receiver != null) {
args.add(receiver);
}
for (Expression arg in arguments.positional) {
args.add(_visit(arg));
}
if (arguments.named.isNotEmpty) {
final names = <String>[];
final map = <String, TypeExpr>{};
for (NamedExpression arg in arguments.named) {
final name = arg.name;
names.add(name);
map[name] = _visit(arg.value);
}
names.sort();
for (var name in names) {
args.add(map[name]);
}
return new Args<TypeExpr>(args, names: names);
} else {
return new Args<TypeExpr>(args);
}
}
Parameter _declareParameter(
String name, DartType type, Expression initializer,
{bool isReceiver: false}) {
Type staticType;
if (type != null) {
staticType = _typesBuilder.fromStaticType(type, !isReceiver);
}
final param = new Parameter(name, staticType);
_summary.add(param);
assertx(param.index < _summary.parameterCount);
if (param.index >= _summary.requiredParameterCount) {
if (initializer != null) {
if (initializer is ConstantExpression) {
param.defaultValue =
constantAllocationCollector.typeFor(initializer.constant);
} else if (initializer is BasicLiteral ||
initializer is SymbolLiteral ||
initializer is TypeLiteral) {
param.defaultValue = _visit(initializer);
} else {
throw 'Unexpected parameter $name default value ${initializer.runtimeType} $initializer';
}
} else {
param.defaultValue = _nullType;
}
} else {
assertx(initializer == null);
}
return param;
}
void _declareVariable(VariableDeclaration decl, TypeExpr initialValue) {
final int varIndex = _variablesInfo.varIndex[decl];
assertx(varIndex != null);
assertx(_variablesInfo.varDeclarations[varIndex] == decl);
assertx(_variableValues[varIndex] == null);
if (_variablesInfo.isCaptured(decl)) {
final join = _makeJoin(varIndex, initialValue);
_variableCells[varIndex] = join;
_variableValues[varIndex] = join;
} else {
_variableValues[varIndex] = initialValue;
}
}
void _writeVariable(VariableDeclaration variable, TypeExpr value) {
final int varIndex = _variablesInfo.varIndex[variable];
final Join join = _variableCells[varIndex];
if (join != null) {
join.values.add(value);
} else {
_variableValues[varIndex] = value;
}
}
List<TypeExpr> _cloneVariableValues(List<TypeExpr> values) =>
new List<TypeExpr>.from(values);
List<TypeExpr> _makeEmptyVariableValues() {
final values = new List<TypeExpr>(_variablesInfo.numVariables);
for (int i = 0; i < values.length; ++i) {
if (_variableCells[i] != null) {
values[i] = _variableValues[i];
} else if (_variableValues[i] != null) {
values[i] = const EmptyType();
}
}
return values;
}
Join _makeJoin(int varIndex, TypeExpr value) {
final VariableDeclaration variable =
_variablesInfo.varDeclarations[varIndex];
final name = '${variable.name}_${_variableVersions[varIndex]++}';
final Join join = new Join(name, variable.type);
_summary.add(join);
join.values.add(value);
return join;
}
void _mergeVariableValues(List<TypeExpr> dst, List<TypeExpr> src) {
assertx(dst.length == src.length);
for (int i = 0; i < dst.length; ++i) {
final TypeExpr dstValue = dst[i];
final TypeExpr srcValue = src[i];
if (identical(dstValue, srcValue)) {
continue;
}
if (dstValue == null || srcValue == null) {
dst[i] = null;
} else if (dstValue is EmptyType) {
dst[i] = srcValue;
} else if (dstValue is Join && dstValue.values.contains(srcValue)) {
continue;
} else if (srcValue is EmptyType) {
continue;
} else if (srcValue is Join && srcValue.values.contains(dstValue)) {
dst[i] = srcValue;
} else {
final Join join = _makeJoin(i, dst[i]);
join.values.add(src[i]);
dst[i] = join;
}
}
}
void _copyVariableValues(List<TypeExpr> dst, List<TypeExpr> src) {
assertx(dst.length == src.length);
for (int i = 0; i < dst.length; ++i) {
dst[i] = src[i];
}
}
bool _isIdenticalState(List<TypeExpr> state1, List<TypeExpr> state2) {
assertx(state1.length == state2.length);
for (int i = 0; i < state1.length; ++i) {
if (!identical(state1[i], state2[i])) {
return false;
}
}
return true;
}
List<Join> _insertJoinsForModifiedVariables(TreeNode node, bool isTry) {
final List<Join> joins = new List<Join>(_variablesInfo.numVariables);
for (var i in _variablesInfo.getModifiedVariables(node)) {
if (_variableCells[i] != null) {
assertx(_variableCells[i] == _variableValues[i]);
} else {
final join = _makeJoin(i, _variableValues[i]);
joins[i] = join;
_variableValues[i] = join;
if (isTry) {
// Inside try blocks all values of modified variables are merged,
// as catch can potentially see any value (in case exception
// is thrown after each assignment).
_variableCells[i] = join;
}
}
}
return joins;
}
/// Stops accumulating values in [joins] by removing them from
/// _variableCells.
void _restoreVariableCellsAfterTry(List<Join> joins) {
for (int i = 0; i < joins.length; ++i) {
if (joins[i] != null) {
assertx(_variableCells[i] == joins[i]);
_variableCells[i] = null;
}
}
}