Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(152)

Side by Side Diff: pkg/compiler/lib/src/cps_ir/cps_ir_nodes.dart

Issue 2246623002: Delete CPS IR (Closed) Base URL: git@github.com:dart-lang/sdk.git@master
Patch Set: Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4 library dart2js.ir_nodes;
5
6 import 'dart:collection';
7 import 'cps_fragment.dart' show CpsFragment;
8 import 'cps_ir_nodes_sexpr.dart';
9 import '../constants/values.dart' as values;
10 import '../dart_types.dart' show DartType, InterfaceType, TypeVariableType;
11 import '../elements/elements.dart';
12 import '../io/source_information.dart' show SourceInformation;
13 import '../types/types.dart' show TypeMask;
14 import '../universe/selector.dart' show Selector;
15
16 import 'builtin_operator.dart';
17 export 'builtin_operator.dart';
18
19 import 'effects.dart';
20
21 // These imports are only used for the JavaScript specific nodes. If we want to
22 // support more than one native backend, we should probably create better
23 // abstractions for native code and its type and effect system.
24 import '../js/js.dart' as js show Template, isNullGuardOnFirstArgument;
25 import '../native/native.dart' as native show NativeBehavior;
26
27 abstract class Node {
28 /// A pointer to the parent node. Is null until set by optimization passes.
29 Node parent;
30
31 /// Workaround for a slow Object.hashCode in the VM.
32 static int _usedHashCodes = 0;
33 final int hashCode = ++_usedHashCodes;
34
35 Node() {
36 setParentPointers();
37 }
38
39 accept(Visitor visitor);
40
41 /// Updates the [parent] of the immediate children to refer to this node.
42 ///
43 /// All constructors call this method to initialize parent pointers.
44 void setParentPointers();
45
46 /// Returns the SExpression for the subtree rooted at this node.
47 ///
48 /// [annotations] maps strings to nodes and/or nodes to values that will be
49 /// converted to strings. Each binding causes the annotation to appear on the
50 /// given node.
51 ///
52 /// For example, the following could be used to diagnose a problem with nodes
53 /// not appearing in an environment map:
54 ///
55 /// if (environment[node] == null)
56 /// root.debugPrint({
57 /// 'currentNode': node,
58 /// 'caller': someContinuation
59 /// });
60 /// throw 'Node was not in environment';
61 /// }
62 ///
63 /// If two strings map to the same node, it will be given both annotations.
64 ///
65 /// Avoid using nodes as keys if there is a chance that two keys are the
66 /// same node.
67 String debugString([Map annotations = const {}]) {
68 return new SExpressionStringifier()
69 .withAnnotations(annotations)
70 .withTypes()
71 .visit(this);
72 }
73
74 /// Prints the result of [debugString].
75 void debugPrint([Map annotations = const {}]) {
76 print(debugString(annotations));
77 }
78 }
79
80 /// Expressions can be evaluated, and may diverge, throw, and/or have
81 /// side-effects.
82 ///
83 /// Evaluation continues by stepping into a sub-expression, invoking a
84 /// continuation, or throwing an exception.
85 ///
86 /// Expressions do not a return value. Expressions that produce values should
87 /// invoke a [Continuation] with the result as argument. Alternatively, values
88 /// that can be obtained without side-effects, divergence, or throwing
89 /// exceptions can be built using a [LetPrim].
90 ///
91 /// All subclasses implement exactly one of [CallExpression],
92 /// [InteriorExpression], or [TailExpression].
93 abstract class Expression extends Node {
94 InteriorNode get parent; // Only InteriorNodes may contain expressions.
95
96 Expression plug(Expression expr) => throw 'impossible';
97
98 /// The next expression in the basic block.
99 ///
100 /// For [InteriorExpression]s this is the body, for [CallExpressions] it is
101 /// the body of the continuation, and for [TailExpressions] it is `null`.
102 Expression get next;
103
104 accept(BlockVisitor visitor);
105 }
106
107 /// Represents a node with a child node, which can be accessed through the
108 /// `body` member. A typical usage is when removing a node from the CPS graph:
109 ///
110 /// Node child = node.body;
111 /// InteriorNode parent = node.parent;
112 ///
113 /// child.parent = parent;
114 /// parent.body = child;
115 abstract class InteriorNode extends Node {
116 Expression get body;
117 void set body(Expression body);
118
119 accept(BlockVisitor visitor);
120 }
121
122 /// The base class of things that variables can refer to: primitives,
123 /// continuations, function and continuation parameters, etc.
124 abstract class Definition<T extends Definition<T>> extends Node {
125 // The head of a linked-list of occurrences, in no particular order.
126 Reference<T> firstRef;
127
128 bool get hasAtMostOneUse => firstRef == null || firstRef.next == null;
129 bool get hasExactlyOneUse => firstRef != null && firstRef.next == null;
130 bool get hasNoUses => firstRef == null;
131 bool get hasAtLeastOneUse => firstRef != null;
132 bool get hasMultipleUses => !hasAtMostOneUse;
133
134 void replaceUsesWith(Definition<T> newDefinition) {
135 if (newDefinition == this) return;
136 if (hasNoUses) return;
137 Reference<T> previous, current = firstRef;
138 do {
139 current.definition = newDefinition;
140 previous = current;
141 current = current.next;
142 } while (current != null);
143 previous.next = newDefinition.firstRef;
144 if (newDefinition.firstRef != null) {
145 newDefinition.firstRef.previous = previous;
146 }
147 newDefinition.firstRef = firstRef;
148 firstRef = null;
149 }
150 }
151
152 /// Operands to invocations and primitives are always variables. They point to
153 /// their definition and are doubly-linked into a list of occurrences.
154 class Reference<T extends Definition<T>> {
155 T definition;
156 Reference<T> previous;
157 Reference<T> next;
158
159 /// A pointer to the parent node. Is null until set by optimization passes.
160 Node parent;
161
162 Reference(this.definition) {
163 next = definition.firstRef;
164 if (next != null) next.previous = this;
165 definition.firstRef = this;
166 }
167
168 /// Unlinks this reference from the list of occurrences.
169 void unlink() {
170 if (previous == null) {
171 assert(definition.firstRef == this);
172 definition.firstRef = next;
173 } else {
174 previous.next = next;
175 }
176 if (next != null) next.previous = previous;
177 }
178
179 /// Changes the definition referenced by this object and updates
180 /// the reference chains accordingly.
181 void changeTo(Definition<T> newDefinition) {
182 unlink();
183 previous = null;
184 definition = newDefinition;
185 next = definition.firstRef;
186 if (next != null) next.previous = this;
187 definition.firstRef = this;
188 }
189 }
190
191 class EffectiveUseIterator extends Iterator<Reference<Primitive>> {
192 Reference<Primitive> current;
193 Reference<Primitive> next;
194 final List<Refinement> stack = <Refinement>[];
195
196 EffectiveUseIterator(Primitive prim) : next = prim.firstRef;
197
198 bool moveNext() {
199 Reference<Primitive> ref = next;
200 while (true) {
201 if (ref == null) {
202 if (stack.isNotEmpty) {
203 ref = stack.removeLast().firstRef;
204 } else {
205 current = null;
206 return false;
207 }
208 } else if (ref.parent is Refinement) {
209 stack.add(ref.parent);
210 ref = ref.next;
211 } else {
212 current = ref;
213 next = current.next;
214 return true;
215 }
216 }
217 }
218 }
219
220 class RefinedUseIterable extends IterableBase<Reference<Primitive>> {
221 Primitive primitive;
222 RefinedUseIterable(this.primitive);
223 EffectiveUseIterator get iterator => new EffectiveUseIterator(primitive);
224 }
225
226 /// A named value.
227 ///
228 /// The identity of the [Primitive] object is the name of the value.
229 /// The subclass describes how to compute the value.
230 ///
231 /// All primitives except [Parameter] must be bound by a [LetPrim].
232 abstract class Primitive extends Variable<Primitive> {
233 Primitive() : super(null);
234
235 /// Returns a bitmask with the non-local side effects and dependencies of
236 /// this primitive, as defined by [Effects].
237 int get effects => Effects.none;
238
239 /// True if this primitive has a value that can be used by other expressions.
240 bool get hasValue;
241
242 /// True if the primitive can be removed, assuming it has no uses
243 /// (this getter does not check if there are any uses).
244 ///
245 /// False must be returned for primitives that may throw, diverge, or have
246 /// observable side-effects.
247 bool get isSafeForElimination;
248
249 /// True if time-of-evaluation is irrelevant for the given primitive,
250 /// assuming its inputs are the same values.
251 bool get isSafeForReordering;
252
253 /// The source information associated with this primitive.
254 // TODO(johnniwinther): Require source information for all primitives.
255 SourceInformation get sourceInformation => null;
256
257 /// If this is a [Refinement], [BoundsCheck] or [ReceiverCheck] node, returns
258 /// the value being refined, the indexable object being checked, or the value
259 /// that was checked to be non-null, respectively.
260 ///
261 /// Those instructions all return the corresponding operand directly, and
262 /// this getter can be used to get (closer to) where the value came from.
263 //
264 // TODO(asgerf): Also do this for [TypeCast]?
265 Primitive get effectiveDefinition => this;
266
267 /// Like [effectiveDefinition] but only unfolds [Refinement] nodes.
268 Primitive get unrefined => this;
269
270 /// True if the two primitives are (refinements of) the same value.
271 bool sameValue(Primitive other) {
272 return effectiveDefinition == other.effectiveDefinition;
273 }
274
275 /// Iterates all non-refinement uses of the primitive and all uses of
276 /// a [Refinement] of this primitive (transitively).
277 ///
278 /// Notes regarding concurrent modification:
279 /// - The current reference may safely be unlinked.
280 /// - Yet unvisited references may not be unlinked.
281 /// - References to this primitive created during iteration will not be seen.
282 /// - References to a refinement of this primitive may not be created during
283 /// iteration.
284 RefinedUseIterable get refinedUses => new RefinedUseIterable(this);
285
286 bool get hasMultipleRefinedUses {
287 Iterator it = refinedUses.iterator;
288 return it.moveNext() && it.moveNext();
289 }
290
291 bool get hasNoRefinedUses {
292 return refinedUses.isEmpty;
293 }
294
295 /// Unlinks all references contained in this node.
296 void destroy() {
297 assert(hasNoUses);
298 RemovalVisitor.remove(this);
299 }
300
301 /// Replaces this definition, both at the binding site and at all uses sites.
302 ///
303 /// This can be thought of as changing the definition of a `let` while
304 /// preserving the variable name:
305 ///
306 /// let x = OLD in BODY
307 /// ==>
308 /// let x = NEW in BODY
309 ///
310 void replaceWith(Primitive newDefinition) {
311 assert(this is! Parameter);
312 assert(newDefinition is! Parameter);
313 assert(newDefinition.parent == null);
314 replaceUsesWith(newDefinition);
315 destroy();
316 LetPrim let = parent;
317 let.primitive = newDefinition;
318 newDefinition.parent = let;
319 newDefinition.useElementAsHint(hint);
320 }
321
322 /// Replaces this definition with a CPS fragment (a term with a hole in it),
323 /// given the value to replace the uses of the definition with.
324 ///
325 /// This can be thought of as substituting:
326 ///
327 /// let x = OLD in BODY
328 /// ==>
329 /// FRAGMENT[BODY{newPrimitive/x}]
330 void replaceWithFragment(CpsFragment fragment, Primitive newPrimitive) {
331 assert(this is! Parameter);
332 replaceUsesWith(newPrimitive);
333 destroy();
334 LetPrim let = parent;
335 fragment.insertBelow(let);
336 let.remove();
337 }
338 }
339
340 /// Continuations are normally bound by 'let cont'. A continuation with one
341 /// parameter and no body is used to represent a function's return continuation.
342 /// The return continuation is bound by the function, not by 'let cont'.
343 class Continuation extends Definition<Continuation> implements InteriorNode {
344 final List<Parameter> parameters;
345 Expression body = null;
346
347 // A continuation is recursive if it has any recursive invocations.
348 bool isRecursive;
349
350 /// True if this is the return continuation. The return continuation is bound
351 /// by [FunctionDefinition].
352 bool get isReturnContinuation => body == null;
353
354 /// True if this is a branch continuation. Branch continuations are bound
355 /// by [LetCont] and can only have one use.
356 bool get isBranchContinuation => firstRef?.parent is Branch;
357
358 /// True if this is the exception handler bound by a [LetHandler].
359 bool get isHandlerContinuation => parent is LetHandler;
360
361 /// True if this is a non-return continuation that can be targeted by
362 /// [InvokeContinuation].
363 bool get isJoinContinuation {
364 return body != null &&
365 parent is! LetHandler &&
366 (firstRef == null || firstRef.parent is InvokeContinuation);
367 }
368
369 Continuation(this.parameters, {this.isRecursive: false});
370
371 Continuation.retrn()
372 : parameters = <Parameter>[new Parameter(null)],
373 isRecursive = false;
374
375 accept(BlockVisitor visitor) => visitor.visitContinuation(this);
376
377 void setParentPointers() {
378 _setParentsOnNodes(parameters, this);
379 if (body != null) body.parent = this;
380 }
381 }
382
383 /// Common interface for [Primitive] and [MutableVariable].
384 abstract class Variable<T extends Variable<T>> extends Definition<T> {
385 /// Type of value held in the variable.
386 ///
387 /// Is `null` until initialized by type propagation.
388 TypeMask type;
389
390 /// The [VariableElement] or [ParameterElement] from which the variable
391 /// binding originated.
392 Entity hint;
393
394 Variable(this.hint);
395
396 /// Use the given element as a hint for naming this primitive.
397 ///
398 /// Has no effect if this primitive already has a non-null [element].
399 void useElementAsHint(Entity hint) {
400 this.hint ??= hint;
401 }
402 }
403
404 /// Identifies a mutable variable.
405 class MutableVariable extends Variable<MutableVariable> {
406 MutableVariable(Entity hint) : super(hint);
407
408 accept(Visitor v) => v.visitMutableVariable(this);
409
410 void setParentPointers() {}
411 }
412
413 /// A function definition, consisting of parameters and a body.
414 ///
415 /// There is an explicit parameter for the `this` argument, and a return
416 /// continuation to invoke when returning from the function.
417 class FunctionDefinition extends InteriorNode {
418 final ExecutableElement element;
419 Parameter interceptorParameter;
420 final Parameter receiverParameter;
421 final List<Parameter> parameters;
422 final Continuation returnContinuation;
423 final SourceInformation sourceInformation;
424 Expression body;
425
426 FunctionDefinition(this.element, this.receiverParameter, this.parameters,
427 this.returnContinuation, this.body,
428 {this.interceptorParameter, this.sourceInformation});
429
430 accept(BlockVisitor visitor) => visitor.visitFunctionDefinition(this);
431
432 void setParentPointers() {
433 if (interceptorParameter != null) interceptorParameter.parent = this;
434 if (receiverParameter != null) receiverParameter.parent = this;
435 _setParentsOnNodes(parameters, this);
436 returnContinuation.parent = this;
437 if (body != null) body.parent = this;
438 }
439 }
440
441 // ----------------------------------------------------------------------------
442 // PRIMITIVES
443 // ----------------------------------------------------------------------------
444
445 class Parameter extends Primitive {
446 Parameter(Entity hint) {
447 super.hint = hint;
448 }
449
450 accept(Visitor visitor) => visitor.visitParameter(this);
451
452 String toString() => 'Parameter(${hint == null ? null : hint.name})';
453
454 bool get hasValue => true;
455 bool get isSafeForElimination => true;
456 bool get isSafeForReordering => true;
457
458 void setParentPointers() {}
459 }
460
461 /// A primitive that is generally not safe for elimination, but may be marked
462 /// as safe by type propagation
463 abstract class UnsafePrimitive extends Primitive {
464 int effects = Effects.all;
465 bool isSafeForElimination = false;
466 bool isSafeForReordering = false;
467 }
468
469 enum CallingConvention {
470 /// JS receiver is the Dart receiver, there are no extra arguments.
471 ///
472 /// This includes cases (e.g., static functions, constructors) where there
473 /// is no receiver.
474 ///
475 /// For example: `foo.bar$1(x)`
476 Normal,
477
478 /// JS receiver is an interceptor, the first argument is the Dart receiver.
479 ///
480 /// For example: `getInterceptor(foo).bar$1(foo, x)`
481 Intercepted,
482
483 /// JS receiver is the Dart receiver, the first argument is a dummy value.
484 ///
485 /// For example: `foo.bar$1(0, x)`
486 DummyIntercepted,
487
488 /// JS receiver is the Dart receiver, there are no extra arguments.
489 ///
490 /// Compiles to a one-shot interceptor, e.g: `J.bar$1(foo, x)`
491 OneShotIntercepted,
492 }
493
494 /// Base class of function invocations.
495 ///
496 /// This class defines the common interface of function invocations.
497 abstract class InvocationPrimitive extends UnsafePrimitive {
498 Reference<Primitive> get interceptorRef => null;
499 Primitive get interceptor => interceptorRef?.definition;
500
501 Reference<Primitive> get receiverRef => null;
502 Primitive get receiver => receiverRef?.definition;
503
504 List<Reference<Primitive>> get argumentRefs;
505 Primitive argument(int n) => argumentRefs[n].definition;
506 Iterable<Primitive> get arguments => _dereferenceList(argumentRefs);
507
508 CallingConvention get callingConvention => CallingConvention.Normal;
509
510 SourceInformation get sourceInformation;
511 }
512
513 /// Invoke a static function.
514 ///
515 /// All optional arguments declared by [target] are passed in explicitly, and
516 /// occur at the end of [arguments] list, in normalized order.
517 ///
518 /// Discussion:
519 /// All information in the [selector] is technically redundant; it will likely
520 /// be removed.
521 class InvokeStatic extends InvocationPrimitive {
522 final FunctionElement target;
523 final Selector selector;
524 final List<Reference<Primitive>> argumentRefs;
525 final SourceInformation sourceInformation;
526
527 InvokeStatic(this.target, this.selector, List<Primitive> args,
528 [this.sourceInformation])
529 : argumentRefs = _referenceList(args);
530
531 InvokeStatic.byReference(this.target, this.selector, this.argumentRefs,
532 [this.sourceInformation]);
533
534 accept(Visitor visitor) => visitor.visitInvokeStatic(this);
535
536 bool get hasValue => true;
537
538 void setParentPointers() {
539 _setParentsOnList(argumentRefs, this);
540 }
541 }
542
543 /// Invoke a method on an object.
544 ///
545 /// This includes getters, setters, operators, and index getter/setters.
546 ///
547 /// Tearing off a method is treated like a getter invocation (getters and
548 /// tear-offs cannot be distinguished at compile-time).
549 ///
550 /// The [selector] records the names of named arguments. The value of named
551 /// arguments occur at the end of the [arguments] list, in normalized order.
552 class InvokeMethod extends InvocationPrimitive {
553 Reference<Primitive> interceptorRef;
554 Reference<Primitive> receiverRef;
555 Selector selector;
556 TypeMask mask;
557 final List<Reference<Primitive>> argumentRefs;
558 final SourceInformation sourceInformation;
559 CallingConvention _callingConvention;
560
561 CallingConvention get callingConvention => _callingConvention;
562
563 InvokeMethod(
564 Primitive receiver, this.selector, this.mask, List<Primitive> arguments,
565 {this.sourceInformation,
566 CallingConvention callingConvention,
567 Primitive interceptor})
568 : this.receiverRef = new Reference<Primitive>(receiver),
569 this.argumentRefs = _referenceList(arguments),
570 this.interceptorRef = _optionalReference(interceptor),
571 this._callingConvention = callingConvention ??
572 (interceptor != null
573 ? CallingConvention.Intercepted
574 : CallingConvention.Normal);
575
576 accept(Visitor visitor) => visitor.visitInvokeMethod(this);
577
578 bool get hasValue => true;
579
580 void setParentPointers() {
581 interceptorRef?.parent = this;
582 receiverRef.parent = this;
583 _setParentsOnList(argumentRefs, this);
584 }
585
586 void makeIntercepted(Primitive interceptor) {
587 interceptorRef?.unlink();
588 interceptorRef = new Reference<Primitive>(interceptor)..parent = this;
589 _callingConvention = CallingConvention.Intercepted;
590 }
591
592 void makeOneShotIntercepted() {
593 interceptorRef?.unlink();
594 interceptorRef = null;
595 _callingConvention = CallingConvention.OneShotIntercepted;
596 }
597
598 void makeDummyIntercepted() {
599 interceptorRef?.unlink();
600 interceptorRef = null;
601 _callingConvention = CallingConvention.DummyIntercepted;
602 }
603 }
604
605 /// Invoke [target] on [receiver], bypassing dispatch and override semantics.
606 ///
607 /// That is, if [receiver] is an instance of a class that overrides [target]
608 /// with a different implementation, the overriding implementation is bypassed
609 /// and [target]'s implementation is invoked.
610 ///
611 /// As with [InvokeMethod], this can be used to invoke a method, operator,
612 /// getter, setter, or index getter/setter.
613 ///
614 /// If it is known that [target] does not use its receiver argument, then
615 /// [receiver] may refer to a null constant primitive. This happens for direct
616 /// invocations to intercepted methods, where the effective receiver is instead
617 /// passed as a formal parameter.
618 ///
619 /// TODO(sra): Review. A direct call to a method that is mixed into a native
620 /// class will still require an explicit argument.
621 ///
622 /// All optional arguments declared by [target] are passed in explicitly, and
623 /// occur at the end of [arguments] list, in normalized order.
624 class InvokeMethodDirectly extends InvocationPrimitive {
625 Reference<Primitive> interceptorRef;
626 Reference<Primitive> receiverRef;
627 final FunctionElement target;
628 final Selector selector;
629 final List<Reference<Primitive>> argumentRefs;
630 final SourceInformation sourceInformation;
631
632 InvokeMethodDirectly(Primitive receiver, this.target, this.selector,
633 List<Primitive> arguments, this.sourceInformation,
634 {Primitive interceptor})
635 : this.receiverRef = new Reference<Primitive>(receiver),
636 this.argumentRefs = _referenceList(arguments),
637 this.interceptorRef = _optionalReference(interceptor);
638
639 accept(Visitor visitor) => visitor.visitInvokeMethodDirectly(this);
640
641 bool get hasValue => true;
642
643 void setParentPointers() {
644 interceptorRef?.parent = this;
645 receiverRef.parent = this;
646 _setParentsOnList(argumentRefs, this);
647 }
648
649 bool get isConstructorBodyCall => target is ConstructorBodyElement;
650 bool get isTearOff => selector.isGetter && !target.isGetter;
651
652 void makeIntercepted(Primitive interceptor) {
653 interceptorRef?.unlink();
654 interceptorRef = new Reference<Primitive>(interceptor)..parent = this;
655 }
656 }
657
658 /// Non-const call to a constructor.
659 ///
660 /// The [target] may be a generative constructor (forwarding or normal)
661 /// or a non-redirecting factory.
662 ///
663 /// All optional arguments declared by [target] are passed in explicitly, and
664 /// occur in the [arguments] list, in normalized order.
665 ///
666 /// Last in the [arguments] list, after the mandatory and optional arguments,
667 /// the internal representation of each type argument occurs, unless it could
668 /// be determined at build-time that the constructed class has no need for its
669 /// runtime type information.
670 ///
671 /// Note that [InvokeConstructor] does it itself allocate an object.
672 /// The invoked constructor will do that using [CreateInstance].
673 class InvokeConstructor extends InvocationPrimitive {
674 final DartType dartType;
675 final ConstructorElement target;
676 final List<Reference<Primitive>> argumentRefs;
677 final Selector selector;
678 final SourceInformation sourceInformation;
679
680 /// If non-null, this is an allocation site-specific type that is potentially
681 /// better than the inferred return type of [target].
682 ///
683 /// In particular, container type masks depend on the allocation site and
684 /// can therefore not be inferred solely based on the call target.
685 TypeMask allocationSiteType;
686
687 InvokeConstructor(this.dartType, this.target, this.selector,
688 List<Primitive> args, this.sourceInformation,
689 {this.allocationSiteType})
690 : argumentRefs = _referenceList(args);
691
692 accept(Visitor visitor) => visitor.visitInvokeConstructor(this);
693
694 bool get hasValue => true;
695
696 void setParentPointers() {
697 _setParentsOnList(argumentRefs, this);
698 }
699 }
700
701 /// An alias for [value] in a context where the value is known to satisfy
702 /// [type].
703 ///
704 /// Refinement nodes are inserted before the type propagator pass and removed
705 /// afterwards, so as not to complicate passes that don't reason about types,
706 /// but need to reason about value references being identical (i.e. referring
707 /// to the same primitive).
708 class Refinement extends Primitive {
709 Reference<Primitive> value;
710 final TypeMask refineType;
711
712 Refinement(Primitive value, this.refineType)
713 : value = new Reference<Primitive>(value);
714
715 bool get hasValue => true;
716 bool get isSafeForElimination => false;
717 bool get isSafeForReordering => false;
718
719 accept(Visitor visitor) => visitor.visitRefinement(this);
720
721 Primitive get effectiveDefinition => value.definition.effectiveDefinition;
722
723 Primitive get unrefined => value.definition.unrefined;
724
725 void setParentPointers() {
726 value.parent = this;
727 }
728 }
729
730 /// Checks that [index] is a valid index on a given indexable [object].
731 ///
732 /// In the simplest form, compiles to the following:
733 ///
734 /// if (index < 0 || index >= object.length)
735 /// ThrowIndexOutOfRangeException(object, index);
736 ///
737 /// In the general form, any of the following conditions can be checked:
738 ///
739 /// Lower bound: `index >= 0`
740 /// Upper bound: `index < object.length`
741 /// Emptiness: `object.length !== 0`
742 /// Integerness: `index >>> 0 === index`
743 ///
744 /// [index] must be an integer unless integerness is checked, and [object] must
745 /// refer to null or an indexable object, and [length] must be the length of
746 /// [object] at the time of the check.
747 ///
748 /// Returns [object] so the bounds check can be used to restrict code motion.
749 /// It is possible to have a bounds check node that performs no checks but
750 /// is retained to restrict code motion.
751 ///
752 /// The [index] reference may be null if there are no checks to perform,
753 /// and the [length] reference may be null if there is no upper bound or
754 /// emptiness check.
755 ///
756 /// If a separate code motion guard for the index is required, e.g. because it
757 /// must be known to be non-negative in an operator that does not involve
758 /// [object], a [Refinement] can be created for it with the non-negative integer
759 /// type.
760 class BoundsCheck extends Primitive {
761 final Reference<Primitive> objectRef;
762 Reference<Primitive> indexRef;
763 Reference<Primitive> lengthRef;
764 int checks;
765 final SourceInformation sourceInformation;
766
767 Primitive get object => objectRef.definition;
768 Primitive get index => indexRef?.definition;
769 Primitive get length => lengthRef?.definition;
770
771 /// If true, check that `index >= 0`.
772 bool get hasLowerBoundCheck => checks & LOWER_BOUND != 0;
773
774 /// If true, check that `index < object.length`.
775 bool get hasUpperBoundCheck => checks & UPPER_BOUND != 0;
776
777 /// If true, check that `object.length !== 0`.
778 ///
779 /// Equivalent to a lower bound check with `object.length - 1` as the index,
780 /// but this check is faster.
781 ///
782 /// Although [index] is not used in the condition, it is used to generate
783 /// the thrown error. Currently it is always `-1` for emptiness checks,
784 /// because that corresponds to `object.length - 1` in the error case.
785 bool get hasEmptinessCheck => checks & EMPTINESS != 0;
786
787 /// If true, check that `index` is an integer.
788 bool get hasIntegerCheck => checks & INTEGER != 0;
789
790 /// True if the [length] is needed to perform the check.
791 bool get lengthUsedInCheck => checks & (UPPER_BOUND | EMPTINESS) != 0;
792
793 bool get hasNoChecks => checks == NONE;
794
795 static const int UPPER_BOUND = 1 << 0;
796 static const int LOWER_BOUND = 1 << 1;
797 static const int EMPTINESS = 1 << 2; // See [hasEmptinessCheck].
798 static const int INTEGER = 1 << 3; // Check if index is an int.
799 static const int BOTH_BOUNDS = UPPER_BOUND | LOWER_BOUND;
800 static const int NONE = 0;
801
802 BoundsCheck(Primitive object, Primitive index, Primitive length,
803 [this.checks = BOTH_BOUNDS, this.sourceInformation])
804 : this.objectRef = new Reference<Primitive>(object),
805 this.indexRef = new Reference<Primitive>(index),
806 this.lengthRef = _optionalReference(length);
807
808 BoundsCheck.noCheck(Primitive object, [this.sourceInformation])
809 : this.objectRef = new Reference<Primitive>(object),
810 this.checks = NONE;
811
812 accept(Visitor visitor) => visitor.visitBoundsCheck(this);
813
814 void setParentPointers() {
815 objectRef.parent = this;
816 if (indexRef != null) {
817 indexRef.parent = this;
818 }
819 if (lengthRef != null) {
820 lengthRef.parent = this;
821 }
822 }
823
824 String get checkString {
825 if (hasNoChecks) return 'no-check';
826 return [
827 hasUpperBoundCheck ? 'upper' : null,
828 hasLowerBoundCheck ? 'lower' : null,
829 hasEmptinessCheck ? 'emptiness' : null,
830 hasIntegerCheck ? 'integer' : null,
831 'check'
832 ].where((x) => x != null).join('-');
833 }
834
835 bool get isSafeForElimination => checks == NONE;
836 bool get isSafeForReordering => false;
837 bool get hasValue => true; // Can be referenced to restrict code motion.
838
839 Primitive get effectiveDefinition => object.effectiveDefinition;
840 }
841
842 /// Throw a [NoSuchMethodError] if [value] cannot respond to [selector].
843 ///
844 /// Returns [value] so this can be used to restrict code motion.
845 ///
846 /// The check can take one of three forms:
847 ///
848 /// value.toString;
849 /// value.selectorName;
850 /// value.selectorName(); (should only be used if check always fails)
851 ///
852 /// The first two forms are used when it is known that only null fails the
853 /// check. Additionally, the check may be guarded by a [condition], allowing
854 /// for three more forms:
855 ///
856 /// if (condition) value.toString; (this form is valid but unused)
857 /// if (condition) value.selectorName;
858 /// if (condition) value.selectorName();
859 ///
860 /// The condition must be true if and only if the check should fail. It should
861 /// ideally be of a form understood by JS engines, e.g. a `typeof` test.
862 ///
863 /// If [useSelector] is false, the first form instead becomes `value.toString;`.
864 /// This form is faster when the value is non-null and the accessed property has
865 /// been removed by tree shaking.
866 ///
867 /// [selector] may not be one of the selectors implemented by the null object.
868 class ReceiverCheck extends Primitive {
869 final Reference<Primitive> valueRef;
870 final Selector selector;
871 final SourceInformation sourceInformation;
872 final Reference<Primitive> conditionRef;
873 final int _flags;
874
875 Primitive get value => valueRef.definition;
876 Primitive get condition => conditionRef?.definition;
877
878 static const int _USE_SELECTOR = 1 << 0;
879 static const int _NULL_CHECK = 1 << 1;
880
881 /// True if the selector name should be used in the check; otherwise
882 /// `toString` will be used.
883 bool get useSelector => _flags & _USE_SELECTOR != 0;
884
885 /// True if null is the only possible input that cannot respond to [selector].
886 bool get isNullCheck => _flags & _NULL_CHECK != 0;
887
888 /// Constructor for creating checks in arbitrary configurations.
889 ///
890 /// Consider using one of the named constructors instead.
891 ///
892 /// [useSelector] and [isNullCheck] are mandatory named arguments.
893 ReceiverCheck(Primitive value, this.selector, this.sourceInformation,
894 {Primitive condition, bool useSelector, bool isNullCheck})
895 : valueRef = new Reference<Primitive>(value),
896 conditionRef = _optionalReference(condition),
897 _flags =
898 (useSelector ? _USE_SELECTOR : 0) | (isNullCheck ? _NULL_CHECK : 0);
899
900 /// Simplified constructor for building null checks.
901 ///
902 /// Null must be the only possible input value that does not respond to
903 /// [selector].
904 ReceiverCheck.nullCheck(
905 Primitive value, Selector selector, SourceInformation sourceInformation,
906 {Primitive condition})
907 : this(value, selector, sourceInformation,
908 condition: condition,
909 useSelector: condition != null,
910 isNullCheck: true);
911
912 /// Simplified constructor for building the general check of form:
913 ///
914 /// if (condition) value.selectorName();
915 ///
916 ReceiverCheck.generalCheck(Primitive value, Selector selector,
917 SourceInformation sourceInformation, Primitive condition)
918 : this(value, selector, sourceInformation,
919 condition: condition, useSelector: true, isNullCheck: false);
920
921 bool get isSafeForElimination => false;
922 bool get isSafeForReordering => false;
923 bool get hasValue => true;
924
925 accept(Visitor visitor) => visitor.visitReceiverCheck(this);
926
927 void setParentPointers() {
928 valueRef.parent = this;
929 if (conditionRef != null) {
930 conditionRef.parent = this;
931 }
932 }
933
934 Primitive get effectiveDefinition => value.effectiveDefinition;
935
936 String get nullCheckString => isNullCheck ? 'null-check' : 'general-check';
937 String get useSelectorString => useSelector ? 'use-selector' : 'no-selector';
938 String get flagString => '$nullCheckString $useSelectorString';
939 }
940
941 /// An "is" type test.
942 ///
943 /// Returns `true` if [value] is an instance of [dartType].
944 ///
945 /// [type] must not be the [Object], `dynamic` or [Null] types (though it might
946 /// be a type variable containing one of these types). This design is chosen
947 /// to simplify code generation for type tests.
948 class TypeTest extends Primitive {
949 Reference<Primitive> valueRef;
950 final DartType dartType;
951
952 /// If [dartType] is an [InterfaceType], this holds the internal
953 /// representation of the type arguments to [dartType]. Since these may
954 /// reference type variables from the enclosing class, they are not constant.
955 ///
956 /// If [dartType] is a [TypeVariableType], this is a singleton list with the
957 /// internal representation of the type held in that type variable.
958 ///
959 /// If [dartType] is a [FunctionType], this is a singleton list with the
960 /// internal representation of that type,
961 ///
962 /// Otherwise the list is empty.
963 final List<Reference<Primitive>> typeArgumentRefs;
964
965 Primitive get value => valueRef.definition;
966 Primitive typeArgument(int n) => typeArgumentRefs[n].definition;
967 Iterable<Primitive> get typeArguments => _dereferenceList(typeArgumentRefs);
968
969 TypeTest(Primitive value, this.dartType, List<Primitive> typeArguments)
970 : this.valueRef = new Reference<Primitive>(value),
971 this.typeArgumentRefs = _referenceList(typeArguments);
972
973 accept(Visitor visitor) => visitor.visitTypeTest(this);
974
975 bool get hasValue => true;
976 bool get isSafeForElimination => true;
977 bool get isSafeForReordering => true;
978
979 void setParentPointers() {
980 valueRef.parent = this;
981 _setParentsOnList(typeArgumentRefs, this);
982 }
983 }
984
985 /// An "is" type test for a raw type, performed by testing a flag property.
986 ///
987 /// Returns `true` if [interceptor] is for [dartType].
988 class TypeTestViaFlag extends Primitive {
989 Reference<Primitive> interceptorRef;
990 final DartType dartType;
991
992 Primitive get interceptor => interceptorRef.definition;
993
994 TypeTestViaFlag(Primitive interceptor, this.dartType)
995 : this.interceptorRef = new Reference<Primitive>(interceptor);
996
997 accept(Visitor visitor) => visitor.visitTypeTestViaFlag(this);
998
999 bool get hasValue => true;
1000 bool get isSafeForElimination => true;
1001 bool get isSafeForReordering => true;
1002
1003 void setParentPointers() {
1004 interceptorRef.parent = this;
1005 }
1006 }
1007
1008 /// An "as" type cast.
1009 ///
1010 /// If [value] is `null` or is an instance of [type], [continuation] is invoked
1011 /// with [value] as argument. Otherwise, a [CastError] is thrown.
1012 ///
1013 /// Discussion:
1014 /// The parameter to [continuation] is redundant since it will always equal
1015 /// [value], which is typically in scope in the continuation. However, it might
1016 /// simplify type propagation, since a better type can be computed for the
1017 /// continuation parameter without needing flow-sensitive analysis.
1018 class TypeCast extends UnsafePrimitive {
1019 Reference<Primitive> valueRef;
1020 final DartType dartType;
1021
1022 /// See the corresponding field on [TypeTest].
1023 final List<Reference<Primitive>> typeArgumentRefs;
1024
1025 Primitive get value => valueRef.definition;
1026 Primitive typeArgument(int n) => typeArgumentRefs[n].definition;
1027 Iterable<Primitive> get typeArguments => _dereferenceList(typeArgumentRefs);
1028
1029 TypeCast(Primitive value, this.dartType, List<Primitive> typeArguments)
1030 : this.valueRef = new Reference<Primitive>(value),
1031 this.typeArgumentRefs = _referenceList(typeArguments);
1032
1033 accept(Visitor visitor) => visitor.visitTypeCast(this);
1034
1035 bool get hasValue => true;
1036
1037 void setParentPointers() {
1038 valueRef.parent = this;
1039 _setParentsOnList(typeArgumentRefs, this);
1040 }
1041 }
1042
1043 /// Apply a built-in operator.
1044 ///
1045 /// It must be known that the arguments have the proper types.
1046 class ApplyBuiltinOperator extends Primitive {
1047 BuiltinOperator operator;
1048 List<Reference<Primitive>> argumentRefs;
1049 final SourceInformation sourceInformation;
1050
1051 Primitive argument(int n) => argumentRefs[n].definition;
1052 Iterable<Primitive> get arguments => _dereferenceList(argumentRefs);
1053
1054 ApplyBuiltinOperator(
1055 this.operator, List<Primitive> arguments, this.sourceInformation)
1056 : this.argumentRefs = _referenceList(arguments);
1057
1058 accept(Visitor visitor) => visitor.visitApplyBuiltinOperator(this);
1059
1060 bool get hasValue => true;
1061 bool get isSafeForElimination => true;
1062 bool get isSafeForReordering => true;
1063
1064 void setParentPointers() {
1065 _setParentsOnList(argumentRefs, this);
1066 }
1067 }
1068
1069 /// Apply a built-in method.
1070 ///
1071 /// It must be known that the arguments have the proper types.
1072 class ApplyBuiltinMethod extends Primitive {
1073 BuiltinMethod method;
1074 Reference<Primitive> receiverRef;
1075 List<Reference<Primitive>> argumentRefs;
1076 final SourceInformation sourceInformation;
1077
1078 Primitive get receiver => receiverRef.definition;
1079 Primitive argument(int n) => argumentRefs[n].definition;
1080 Iterable<Primitive> get arguments => _dereferenceList(argumentRefs);
1081
1082 ApplyBuiltinMethod(this.method, Primitive receiver, List<Primitive> arguments,
1083 this.sourceInformation)
1084 : this.receiverRef = new Reference<Primitive>(receiver),
1085 this.argumentRefs = _referenceList(arguments);
1086
1087 accept(Visitor visitor) => visitor.visitApplyBuiltinMethod(this);
1088
1089 bool get hasValue => true;
1090 bool get isSafeForElimination => false;
1091 bool get isSafeForReordering => false;
1092
1093 void setParentPointers() {
1094 receiverRef.parent = this;
1095 _setParentsOnList(argumentRefs, this);
1096 }
1097
1098 int get effects => getEffectsOfBuiltinMethod(method);
1099 }
1100
1101 /// Gets the value from a [MutableVariable].
1102 ///
1103 /// [MutableVariable]s can be seen as ref cells that are not first-class
1104 /// values. A [LetPrim] with a [GetMutable] can then be seen as:
1105 ///
1106 /// let prim p = ![variable] in [body]
1107 ///
1108 class GetMutable extends Primitive {
1109 final Reference<MutableVariable> variableRef;
1110 final SourceInformation sourceInformation;
1111
1112 MutableVariable get variable => variableRef.definition;
1113
1114 GetMutable(MutableVariable variable, {this.sourceInformation})
1115 : this.variableRef = new Reference<MutableVariable>(variable);
1116
1117 accept(Visitor visitor) => visitor.visitGetMutable(this);
1118
1119 bool get hasValue => true;
1120 bool get isSafeForElimination => true;
1121 bool get isSafeForReordering => false;
1122
1123 void setParentPointers() {
1124 variableRef.parent = this;
1125 }
1126 }
1127
1128 /// Assign a [MutableVariable].
1129 ///
1130 /// [MutableVariable]s can be seen as ref cells that are not first-class
1131 /// values. This can be seen as a dereferencing assignment:
1132 ///
1133 /// { [variable] := [value]; [body] }
1134 class SetMutable extends Primitive {
1135 final Reference<MutableVariable> variableRef;
1136 final Reference<Primitive> valueRef;
1137 final SourceInformation sourceInformation;
1138
1139 MutableVariable get variable => variableRef.definition;
1140 Primitive get value => valueRef.definition;
1141
1142 SetMutable(MutableVariable variable, Primitive value,
1143 {this.sourceInformation})
1144 : this.variableRef = new Reference<MutableVariable>(variable),
1145 this.valueRef = new Reference<Primitive>(value);
1146
1147 accept(Visitor visitor) => visitor.visitSetMutable(this);
1148
1149 bool get hasValue => false;
1150 bool get isSafeForElimination => false;
1151 bool get isSafeForReordering => false;
1152
1153 void setParentPointers() {
1154 variableRef.parent = this;
1155 valueRef.parent = this;
1156 }
1157 }
1158
1159 /// Directly reads from a field on a given object.
1160 ///
1161 /// The [object] must either be `null` or an object that has [field].
1162 class GetField extends Primitive {
1163 final Reference<Primitive> objectRef;
1164 FieldElement field;
1165 final SourceInformation sourceInformation;
1166
1167 /// True if the field never changes value.
1168 final bool isFinal;
1169
1170 /// True if the object is known not to be null.
1171 // TODO(asgerf): This is a placeholder until we agree on how to track
1172 // side effects.
1173 bool objectIsNotNull = false;
1174
1175 Primitive get object => objectRef.definition;
1176
1177 GetField(Primitive object, this.field,
1178 {this.sourceInformation, this.isFinal: false})
1179 : this.objectRef = new Reference<Primitive>(object);
1180
1181 accept(Visitor visitor) => visitor.visitGetField(this);
1182
1183 bool get hasValue => true;
1184 bool get isSafeForElimination => objectIsNotNull;
1185 bool get isSafeForReordering => false;
1186
1187 toString() => 'GetField($field)';
1188
1189 void setParentPointers() {
1190 objectRef.parent = this;
1191 }
1192
1193 int get effects => isFinal ? 0 : Effects.dependsOnInstanceField;
1194 }
1195
1196 /// Directly assigns to a field on a given object.
1197 class SetField extends Primitive {
1198 final Reference<Primitive> objectRef;
1199 FieldElement field;
1200 final Reference<Primitive> valueRef;
1201 final SourceInformation sourceInformation;
1202
1203 Primitive get object => objectRef.definition;
1204 Primitive get value => valueRef.definition;
1205
1206 SetField(Primitive object, this.field, Primitive value,
1207 {this.sourceInformation})
1208 : this.objectRef = new Reference<Primitive>(object),
1209 this.valueRef = new Reference<Primitive>(value);
1210
1211 accept(Visitor visitor) => visitor.visitSetField(this);
1212
1213 bool get hasValue => false;
1214 bool get isSafeForElimination => false;
1215 bool get isSafeForReordering => false;
1216
1217 void setParentPointers() {
1218 objectRef.parent = this;
1219 valueRef.parent = this;
1220 }
1221
1222 int get effects => Effects.changesInstanceField;
1223 }
1224
1225 /// Get the length of a string or native list.
1226 class GetLength extends Primitive {
1227 final Reference<Primitive> objectRef;
1228
1229 /// True if the length of the given object can never change.
1230 bool isFinal;
1231
1232 /// True if the object is known not to be null.
1233 bool objectIsNotNull = false;
1234
1235 Primitive get object => objectRef.definition;
1236
1237 GetLength(Primitive object, {this.isFinal: false})
1238 : this.objectRef = new Reference<Primitive>(object);
1239
1240 bool get hasValue => true;
1241 bool get isSafeForElimination => objectIsNotNull;
1242 bool get isSafeForReordering => false;
1243
1244 accept(Visitor v) => v.visitGetLength(this);
1245
1246 void setParentPointers() {
1247 objectRef.parent = this;
1248 }
1249
1250 int get effects => isFinal ? 0 : Effects.dependsOnIndexableLength;
1251 }
1252
1253 /// Read an entry from an indexable object.
1254 ///
1255 /// [object] must be null or an indexable object, and [index] must be
1256 /// an integer where `0 <= index < object.length`.
1257 class GetIndex extends Primitive {
1258 final Reference<Primitive> objectRef;
1259 final Reference<Primitive> indexRef;
1260
1261 /// True if the object is known not to be null.
1262 bool objectIsNotNull = false;
1263
1264 Primitive get object => objectRef.definition;
1265 Primitive get index => indexRef.definition;
1266
1267 GetIndex(Primitive object, Primitive index)
1268 : this.objectRef = new Reference<Primitive>(object),
1269 this.indexRef = new Reference<Primitive>(index);
1270
1271 bool get hasValue => true;
1272 bool get isSafeForElimination => objectIsNotNull;
1273 bool get isSafeForReordering => false;
1274
1275 accept(Visitor v) => v.visitGetIndex(this);
1276
1277 void setParentPointers() {
1278 objectRef.parent = this;
1279 indexRef.parent = this;
1280 }
1281
1282 int get effects => Effects.dependsOnIndexableContent;
1283 }
1284
1285 /// Set an entry on a native list.
1286 ///
1287 /// [object] must be null or a native list, and [index] must be an integer
1288 /// within the bounds of the indexable object.
1289 ///
1290 /// [SetIndex] may not be used to alter the length of a JS array.
1291 ///
1292 /// The primitive itself has no value and may not be referenced.
1293 class SetIndex extends Primitive {
1294 final Reference<Primitive> objectRef;
1295 final Reference<Primitive> indexRef;
1296 final Reference<Primitive> valueRef;
1297
1298 Primitive get object => objectRef.definition;
1299 Primitive get index => indexRef.definition;
1300 Primitive get value => valueRef.definition;
1301
1302 SetIndex(Primitive object, Primitive index, Primitive value)
1303 : this.objectRef = new Reference<Primitive>(object),
1304 this.indexRef = new Reference<Primitive>(index),
1305 this.valueRef = new Reference<Primitive>(value);
1306
1307 bool get hasValue => false;
1308 bool get isSafeForElimination => false;
1309 bool get isSafeForReordering => false;
1310
1311 accept(Visitor v) => v.visitSetIndex(this);
1312
1313 void setParentPointers() {
1314 objectRef.parent = this;
1315 indexRef.parent = this;
1316 valueRef.parent = this;
1317 }
1318
1319 int get effects => Effects.changesIndexableContent;
1320 }
1321
1322 /// Reads the value of a static field or tears off a static method.
1323 ///
1324 /// If [GetStatic] is used to load a lazily initialized static field, it must
1325 /// have been initialized beforehand, and a [witness] must be set to restrict
1326 /// code motion.
1327 class GetStatic extends Primitive {
1328 /// Can be [FieldElement] or [FunctionElement].
1329 final Element element;
1330 final SourceInformation sourceInformation;
1331
1332 /// True if the field never changes value.
1333 final bool isFinal;
1334
1335 /// If reading a lazily initialized field, [witness] must refer to a node
1336 /// that initializes the field or always occurs after the field initializer.
1337 ///
1338 /// The value of the witness is not used.
1339 Reference<Primitive> witnessRef;
1340
1341 Primitive get witness => witnessRef.definition;
1342
1343 GetStatic(this.element, {this.isFinal: false, this.sourceInformation});
1344
1345 /// Read a lazily initialized static field that is known to have been
1346 /// initialized by [witness] or earlier.
1347 GetStatic.witnessed(this.element, Primitive witness, {this.sourceInformation})
1348 : witnessRef = _optionalReference(witness),
1349 isFinal = false;
1350
1351 accept(Visitor visitor) => visitor.visitGetStatic(this);
1352
1353 bool get hasValue => true;
1354 bool get isSafeForElimination => true;
1355 bool get isSafeForReordering => isFinal;
1356
1357 void setParentPointers() {
1358 if (witnessRef != null) {
1359 witnessRef.parent = this;
1360 }
1361 }
1362
1363 int get effects => isFinal ? 0 : Effects.dependsOnStaticField;
1364 }
1365
1366 /// Sets the value of a static field.
1367 class SetStatic extends Primitive {
1368 final FieldElement element;
1369 final Reference<Primitive> valueRef;
1370 final SourceInformation sourceInformation;
1371
1372 Primitive get value => valueRef.definition;
1373
1374 SetStatic(this.element, Primitive value, [this.sourceInformation])
1375 : this.valueRef = new Reference<Primitive>(value);
1376
1377 accept(Visitor visitor) => visitor.visitSetStatic(this);
1378
1379 bool get hasValue => false;
1380 bool get isSafeForElimination => false;
1381 bool get isSafeForReordering => false;
1382
1383 void setParentPointers() {
1384 valueRef.parent = this;
1385 }
1386
1387 int get effects => Effects.changesStaticField;
1388 }
1389
1390 /// Reads the value of a lazily initialized static field.
1391 ///
1392 /// If the field has not yet been initialized, its initializer is evaluated
1393 /// and assigned to the field.
1394 class GetLazyStatic extends UnsafePrimitive {
1395 final FieldElement element;
1396 final SourceInformation sourceInformation;
1397
1398 /// True if the field never changes value.
1399 final bool isFinal;
1400
1401 GetLazyStatic(this.element, {this.isFinal: false, this.sourceInformation});
1402
1403 accept(Visitor visitor) => visitor.visitGetLazyStatic(this);
1404
1405 bool get hasValue => true;
1406
1407 void setParentPointers() {}
1408
1409 // TODO(asgerf): Track side effects of lazy field initializers.
1410 int get effects => Effects.all;
1411 }
1412
1413 /// Creates an object for holding boxed variables captured by a closure.
1414 class CreateBox extends Primitive {
1415 accept(Visitor visitor) => visitor.visitCreateBox(this);
1416
1417 bool get hasValue => true;
1418 bool get isSafeForElimination => true;
1419 bool get isSafeForReordering => true;
1420
1421 void setParentPointers() {}
1422 }
1423
1424 /// Creates an instance of a class and initializes its fields and runtime type
1425 /// information.
1426 class CreateInstance extends Primitive {
1427 final ClassElement classElement;
1428
1429 /// Initial values for the fields on the class.
1430 /// The order corresponds to the order of fields on the class.
1431 final List<Reference<Primitive>> argumentRefs;
1432
1433 /// The runtime type information structure which contains the type arguments.
1434 ///
1435 /// May be `null` to indicate that no type information is needed because the
1436 /// compiler determined that the type information for instances of this class
1437 /// is not needed at runtime.
1438 Reference<Primitive> typeInformationRef;
1439
1440 final SourceInformation sourceInformation;
1441
1442 Primitive argument(int n) => argumentRefs[n].definition;
1443 Iterable<Primitive> get arguments => _dereferenceList(argumentRefs);
1444 Primitive get typeInformation => typeInformationRef?.definition;
1445
1446 CreateInstance(this.classElement, List<Primitive> arguments,
1447 Primitive typeInformation, this.sourceInformation)
1448 : this.argumentRefs = _referenceList(arguments),
1449 this.typeInformationRef = _optionalReference(typeInformation);
1450
1451 accept(Visitor visitor) => visitor.visitCreateInstance(this);
1452
1453 bool get hasValue => true;
1454 bool get isSafeForElimination => true;
1455 bool get isSafeForReordering => true;
1456
1457 toString() => 'CreateInstance($classElement)';
1458
1459 void setParentPointers() {
1460 _setParentsOnList(argumentRefs, this);
1461 if (typeInformationRef != null) typeInformationRef.parent = this;
1462 }
1463 }
1464
1465 /// Obtains the interceptor for the given value. This is a method table
1466 /// corresponding to the Dart class of the value.
1467 ///
1468 /// All values are either intercepted or self-intercepted. The interceptor for
1469 /// an "intercepted value" is one of the subclasses of Interceptor.
1470 /// The interceptor for a "self-intercepted value" is the value itself.
1471 ///
1472 /// If the input is an intercepted value, and any of its superclasses is in
1473 /// [interceptedClasses], the method table for the input is returned.
1474 /// Otherwise, the input itself is returned.
1475 ///
1476 /// There are thus three significant cases:
1477 /// - the input is a self-interceptor
1478 /// - the input is an intercepted value and is caught by [interceptedClasses]
1479 /// - the input is an intercepted value but is bypassed by [interceptedClasses]
1480 ///
1481 /// The [flags] field indicates which of the above cases may happen, with
1482 /// additional special cases for null (which can either by intercepted or
1483 /// bypassed).
1484 class Interceptor extends Primitive {
1485 final Reference<Primitive> inputRef;
1486 final Set<ClassElement> interceptedClasses = new Set<ClassElement>();
1487 final SourceInformation sourceInformation;
1488
1489 Primitive get input => inputRef.definition;
1490
1491 Interceptor(Primitive input, this.sourceInformation)
1492 : this.inputRef = new Reference<Primitive>(input);
1493
1494 accept(Visitor visitor) => visitor.visitInterceptor(this);
1495
1496 bool get hasValue => true;
1497 bool get isSafeForElimination => true;
1498 bool get isSafeForReordering => true;
1499
1500 void setParentPointers() {
1501 inputRef.parent = this;
1502 }
1503 }
1504
1505 /// Create an instance of [Invocation] for use in a call to `noSuchMethod`.
1506 class CreateInvocationMirror extends Primitive {
1507 final Selector selector;
1508 final List<Reference<Primitive>> argumentRefs;
1509
1510 Primitive argument(int n) => argumentRefs[n].definition;
1511 Iterable<Primitive> get arguments => _dereferenceList(argumentRefs);
1512
1513 CreateInvocationMirror(this.selector, List<Primitive> arguments)
1514 : this.argumentRefs = _referenceList(arguments);
1515
1516 accept(Visitor visitor) => visitor.visitCreateInvocationMirror(this);
1517
1518 bool get hasValue => true;
1519 bool get isSafeForElimination => true;
1520 bool get isSafeForReordering => true;
1521
1522 void setParentPointers() {
1523 _setParentsOnList(argumentRefs, this);
1524 }
1525 }
1526
1527 class ForeignCode extends UnsafePrimitive {
1528 final js.Template codeTemplate;
1529 final TypeMask storedType;
1530 final List<Reference<Primitive>> argumentRefs;
1531 final native.NativeBehavior nativeBehavior;
1532 final SourceInformation sourceInformation;
1533 final FunctionElement dependency;
1534
1535 Primitive argument(int n) => argumentRefs[n].definition;
1536 Iterable<Primitive> get arguments => _dereferenceList(argumentRefs);
1537
1538 ForeignCode(this.codeTemplate, this.storedType, List<Primitive> arguments,
1539 this.nativeBehavior, this.sourceInformation,
1540 {this.dependency})
1541 : this.argumentRefs = _referenceList(arguments) {
1542 effects = Effects.from(nativeBehavior.sideEffects);
1543 }
1544
1545 accept(Visitor visitor) => visitor.visitForeignCode(this);
1546
1547 bool get hasValue => true;
1548
1549 void setParentPointers() {
1550 _setParentsOnList(argumentRefs, this);
1551 }
1552
1553 bool isNullGuardOnNullFirstArgument() {
1554 if (argumentRefs.length < 1) return false;
1555 // TODO(sra): Fix NativeThrowBehavior to distinguish MAY from
1556 // throws-nsm-on-null-followed-by-MAY and remove
1557 // [isNullGuardForFirstArgument].
1558 if (nativeBehavior.throwBehavior.isNullNSMGuard) return true;
1559 return js.isNullGuardOnFirstArgument(codeTemplate);
1560 }
1561 }
1562
1563 class Constant extends Primitive {
1564 final values.ConstantValue value;
1565 final SourceInformation sourceInformation;
1566
1567 Constant(this.value, {this.sourceInformation}) {
1568 assert(value != null);
1569 }
1570
1571 accept(Visitor visitor) => visitor.visitConstant(this);
1572
1573 bool get hasValue => true;
1574 bool get isSafeForElimination => true;
1575 bool get isSafeForReordering => true;
1576
1577 void setParentPointers() {}
1578 }
1579
1580 class LiteralList extends Primitive {
1581 /// The List type being created; this is not the type argument.
1582 final InterfaceType dartType;
1583 final List<Reference<Primitive>> valueRefs;
1584
1585 /// If non-null, this is an allocation site-specific type for the list
1586 /// created here.
1587 TypeMask allocationSiteType;
1588
1589 Primitive value(int n) => valueRefs[n].definition;
1590 Iterable<Primitive> get values => _dereferenceList(valueRefs);
1591
1592 LiteralList(this.dartType, List<Primitive> values, {this.allocationSiteType})
1593 : this.valueRefs = _referenceList(values);
1594
1595 accept(Visitor visitor) => visitor.visitLiteralList(this);
1596
1597 bool get hasValue => true;
1598 bool get isSafeForElimination => true;
1599 bool get isSafeForReordering => true;
1600
1601 void setParentPointers() {
1602 _setParentsOnList(valueRefs, this);
1603 }
1604 }
1605
1606 /// Converts the internal representation of a type to a Dart object of type
1607 /// [Type].
1608 class ReifyRuntimeType extends Primitive {
1609 /// Reference to the internal representation of a type (as produced, for
1610 /// example, by [ReadTypeVariable]).
1611 final Reference<Primitive> valueRef;
1612
1613 final SourceInformation sourceInformation;
1614
1615 Primitive get value => valueRef.definition;
1616
1617 ReifyRuntimeType(Primitive value, this.sourceInformation)
1618 : this.valueRef = new Reference<Primitive>(value);
1619
1620 @override
1621 accept(Visitor visitor) => visitor.visitReifyRuntimeType(this);
1622
1623 bool get hasValue => true;
1624 bool get isSafeForElimination => true;
1625 bool get isSafeForReordering => true;
1626
1627 void setParentPointers() {
1628 valueRef.parent = this;
1629 }
1630 }
1631
1632 /// Read the value the type variable [variable] from the target object.
1633 ///
1634 /// The resulting value is an internal representation (and not neccessarily a
1635 /// Dart object), and must be reified by [ReifyRuntimeType], if it should be
1636 /// used as a Dart value.
1637 class ReadTypeVariable extends Primitive {
1638 final TypeVariableType variable;
1639 final Reference<Primitive> targetRef;
1640 final SourceInformation sourceInformation;
1641
1642 Primitive get target => targetRef.definition;
1643
1644 ReadTypeVariable(this.variable, Primitive target, this.sourceInformation)
1645 : this.targetRef = new Reference<Primitive>(target);
1646
1647 @override
1648 accept(Visitor visitor) => visitor.visitReadTypeVariable(this);
1649
1650 bool get hasValue => true;
1651 bool get isSafeForElimination => true;
1652 bool get isSafeForReordering => true;
1653
1654 void setParentPointers() {
1655 targetRef.parent = this;
1656 }
1657 }
1658
1659 enum TypeExpressionKind { COMPLETE, INSTANCE }
1660
1661 /// Constructs a representation of a closed or ground-term type (that is, a type
1662 /// without type variables).
1663 ///
1664 /// There are two forms:
1665 ///
1666 /// - COMPLETE: A complete form that is self contained, used for the values of
1667 /// type parameters and non-raw is-checks.
1668 ///
1669 /// - INSTANCE: A headless flat form for representing the sequence of values of
1670 /// the type parameters of an instance of a generic type.
1671 ///
1672 /// The COMPLETE form value is constructed from [dartType] by replacing the type
1673 /// variables with consecutive values from [arguments], in the order generated
1674 /// by [DartType.forEachTypeVariable]. The type variables in [dartType] are
1675 /// treated as 'holes' in the term, which means that it must be ensured at
1676 /// construction, that duplicate occurences of a type variable in [dartType]
1677 /// are assigned the same value.
1678 ///
1679 /// The INSTANCE form is constructed as a list of [arguments]. This is the same
1680 /// as the COMPLETE form for the 'thisType', except the root term's type is
1681 /// missing; this is implicit as the raw type of instance. The [dartType] of
1682 /// the INSTANCE form must be the thisType of some class.
1683 ///
1684 /// While we would like to remove the constrains on the INSTANCE form, we can
1685 /// get by with a tree of TypeExpressions. Consider:
1686 ///
1687 /// class Foo<T> {
1688 /// ... new Set<List<T>>()
1689 /// }
1690 /// class Set<E1> {
1691 /// factory Set() => new _LinkedHashSet<E1>();
1692 /// }
1693 /// class List<E2> { ... }
1694 /// class _LinkedHashSet<E3> { ... }
1695 ///
1696 /// After inlining the factory constructor for `Set<E1>`, the CreateInstance
1697 /// should have type `_LinkedHashSet<List<T>>` and the TypeExpression should be
1698 /// a tree:
1699 ///
1700 /// CreateInstance(dartType: _LinkedHashSet<List<T>>,
1701 /// [], // No arguments
1702 /// TypeExpression(INSTANCE,
1703 /// dartType: _LinkedHashSet<E3>, // _LinkedHashSet's thisType
1704 /// TypeExpression(COMPLETE, // E3 = List<T>
1705 /// dartType: List<E2>,
1706 /// ReadTypeVariable(this, T)))) // E2 = T
1707 //
1708 // TODO(sra): The INSTANCE form requires the actual instance for full
1709 // interpretation. I want to move to a representation where the INSTANCE form is
1710 // also a complete form (possibly the same).
1711 class TypeExpression extends Primitive {
1712 final TypeExpressionKind kind;
1713 final DartType dartType;
1714 final List<Reference<Primitive>> argumentRefs;
1715
1716 Primitive argument(int n) => argumentRefs[n].definition;
1717 Iterable<Primitive> get arguments => _dereferenceList(argumentRefs);
1718
1719 TypeExpression(this.kind, this.dartType, List<Primitive> arguments)
1720 : this.argumentRefs = _referenceList(arguments) {
1721 assert(kind == TypeExpressionKind.INSTANCE
1722 ? dartType == (dartType.element as ClassElement).thisType
1723 : true);
1724 }
1725
1726 @override
1727 accept(Visitor visitor) {
1728 return visitor.visitTypeExpression(this);
1729 }
1730
1731 bool get hasValue => true;
1732 bool get isSafeForElimination => true;
1733 bool get isSafeForReordering => true;
1734
1735 void setParentPointers() {
1736 _setParentsOnList(argumentRefs, this);
1737 }
1738
1739 String get kindAsString {
1740 switch (kind) {
1741 case TypeExpressionKind.COMPLETE:
1742 return 'COMPLETE';
1743 case TypeExpressionKind.INSTANCE:
1744 return 'INSTANCE';
1745 }
1746 }
1747 }
1748
1749 class Await extends UnsafePrimitive {
1750 final Reference<Primitive> inputRef;
1751
1752 Primitive get input => inputRef.definition;
1753
1754 Await(Primitive input) : this.inputRef = new Reference<Primitive>(input);
1755
1756 @override
1757 accept(Visitor visitor) {
1758 return visitor.visitAwait(this);
1759 }
1760
1761 bool get hasValue => true;
1762
1763 void setParentPointers() {
1764 inputRef.parent = this;
1765 }
1766 }
1767
1768 class Yield extends UnsafePrimitive {
1769 final Reference<Primitive> inputRef;
1770 final bool hasStar;
1771
1772 Primitive get input => inputRef.definition;
1773
1774 Yield(Primitive input, this.hasStar)
1775 : this.inputRef = new Reference<Primitive>(input);
1776
1777 @override
1778 accept(Visitor visitor) {
1779 return visitor.visitYield(this);
1780 }
1781
1782 bool get hasValue => true;
1783
1784 void setParentPointers() {
1785 inputRef.parent = this;
1786 }
1787 }
1788
1789 // ---------------------------------------------------------------------------
1790 // EXPRESSIONS
1791 // ---------------------------------------------------------------------------
1792
1793 /// An expression that creates new bindings and continues evaluation in
1794 /// a subexpression.
1795 ///
1796 /// The interior expressions are [LetPrim], [LetCont], [LetHandler], and
1797 /// [LetMutable].
1798 abstract class InteriorExpression extends Expression implements InteriorNode {
1799 Expression get next => body;
1800
1801 /// Removes this expression from its current position in the IR.
1802 ///
1803 /// The node can be re-inserted elsewhere or remain orphaned.
1804 ///
1805 /// If orphaned, the caller is responsible for unlinking all references in
1806 /// the orphaned node. Use [Reference.unlink] or [Primitive.destroy] for this.
1807 void remove() {
1808 assert(parent != null);
1809 assert(parent.body == this);
1810 assert(body.parent == this);
1811 parent.body = body;
1812 body.parent = parent;
1813 parent = null;
1814 body = null;
1815 }
1816
1817 /// Inserts this above [node].
1818 ///
1819 /// This node must be orphaned first.
1820 void insertAbove(Expression node) {
1821 insertBelow(node.parent);
1822 }
1823
1824 /// Inserts this below [node].
1825 ///
1826 /// This node must be orphaned first.
1827 void insertBelow(InteriorNode newParent) {
1828 assert(parent == null);
1829 assert(body == null);
1830 Expression child = newParent.body;
1831 newParent.body = this;
1832 this.body = child;
1833 child.parent = this;
1834 this.parent = newParent;
1835 }
1836 }
1837
1838 /// An expression without a continuation or a subexpression body.
1839 ///
1840 /// These break straight-line control flow and can be thought of as ending a
1841 /// basic block.
1842 abstract class TailExpression extends Expression {
1843 Expression get next => null;
1844 }
1845
1846 /// Evaluates a primitive and binds it to variable: `let val x = V in E`.
1847 ///
1848 /// The bound value is in scope in the body.
1849 ///
1850 /// During one-pass construction a LetPrim with an empty body is used to
1851 /// represent the one-hole context `let val x = V in []`.
1852 class LetPrim extends InteriorExpression {
1853 Primitive primitive;
1854 Expression body;
1855
1856 LetPrim(this.primitive, [this.body = null]);
1857
1858 Expression plug(Expression expr) {
1859 assert(body == null);
1860 return body = expr;
1861 }
1862
1863 accept(BlockVisitor visitor) => visitor.visitLetPrim(this);
1864
1865 void setParentPointers() {
1866 primitive.parent = this;
1867 if (body != null) body.parent = this;
1868 }
1869 }
1870
1871 /// Binding continuations.
1872 ///
1873 /// let cont k0(v0 ...) = E0
1874 /// k1(v1 ...) = E1
1875 /// ...
1876 /// in E
1877 ///
1878 /// The bound continuations are in scope in the body and the continuation
1879 /// parameters are in scope in the respective continuation bodies.
1880 ///
1881 /// During one-pass construction a LetCont whose first continuation has an empty
1882 /// body is used to represent the one-hole context
1883 /// `let cont ... k(v) = [] ... in E`.
1884 class LetCont extends InteriorExpression {
1885 List<Continuation> continuations;
1886 Expression body;
1887
1888 LetCont(Continuation continuation, this.body)
1889 : continuations = <Continuation>[continuation];
1890
1891 LetCont.two(Continuation first, Continuation second, this.body)
1892 : continuations = <Continuation>[first, second];
1893
1894 LetCont.many(this.continuations, this.body);
1895
1896 Expression plug(Expression expr) {
1897 assert(continuations != null &&
1898 continuations.isNotEmpty &&
1899 continuations.first.body == null);
1900 return continuations.first.body = expr;
1901 }
1902
1903 accept(BlockVisitor visitor) => visitor.visitLetCont(this);
1904
1905 void setParentPointers() {
1906 _setParentsOnNodes(continuations, this);
1907 if (body != null) body.parent = this;
1908 }
1909 }
1910
1911 // Binding an exception handler.
1912 //
1913 // let handler h(v0, v1) = E0 in E1
1914 //
1915 // The handler is a two-argument (exception, stack trace) continuation which
1916 // is implicitly the error continuation of all the code in its body E1.
1917 // [LetHandler] differs from a [LetCont] binding in that it (1) has the
1918 // runtime semantics of pushing/popping a handler from the dynamic exception
1919 // handler stack and (2) it does not have any explicit invocations.
1920 class LetHandler extends InteriorExpression {
1921 Continuation handler;
1922 Expression body;
1923
1924 LetHandler(this.handler, this.body);
1925
1926 accept(BlockVisitor visitor) => visitor.visitLetHandler(this);
1927
1928 void setParentPointers() {
1929 handler.parent = this;
1930 if (body != null) body.parent = this;
1931 }
1932 }
1933
1934 /// Binding mutable variables.
1935 ///
1936 /// let mutable v = P in E
1937 ///
1938 /// [MutableVariable]s can be seen as ref cells that are not first-class
1939 /// values. They are therefore not [Primitive]s and not bound by [LetPrim]
1940 /// to prevent unrestricted use of references to them. During one-pass
1941 /// construction, a [LetMutable] with an empty body is use to represent the
1942 /// one-hole context 'let mutable v = P in []'.
1943 class LetMutable extends InteriorExpression {
1944 final MutableVariable variable;
1945 final Reference<Primitive> valueRef;
1946 Expression body;
1947
1948 Primitive get value => valueRef.definition;
1949
1950 LetMutable(this.variable, Primitive value)
1951 : this.valueRef = new Reference<Primitive>(value);
1952
1953 Expression plug(Expression expr) {
1954 return body = expr;
1955 }
1956
1957 accept(BlockVisitor visitor) => visitor.visitLetMutable(this);
1958
1959 void setParentPointers() {
1960 variable.parent = this;
1961 valueRef.parent = this;
1962 if (body != null) body.parent = this;
1963 }
1964 }
1965
1966 /// Throw a value.
1967 ///
1968 /// Throw is an expression, i.e., it always occurs in tail position with
1969 /// respect to a body or expression.
1970 class Throw extends TailExpression {
1971 Reference<Primitive> valueRef;
1972
1973 Primitive get value => valueRef.definition;
1974
1975 Throw(Primitive value) : valueRef = new Reference<Primitive>(value);
1976
1977 accept(BlockVisitor visitor) => visitor.visitThrow(this);
1978
1979 void setParentPointers() {
1980 valueRef.parent = this;
1981 }
1982 }
1983
1984 /// Rethrow
1985 ///
1986 /// Rethrow can only occur inside a continuation bound by [LetHandler]. It
1987 /// implicitly throws the exception parameter of the enclosing handler with
1988 /// the same stack trace as the enclosing handler.
1989 class Rethrow extends TailExpression {
1990 accept(BlockVisitor visitor) => visitor.visitRethrow(this);
1991 void setParentPointers() {}
1992 }
1993
1994 /// An expression that is known to be unreachable.
1995 ///
1996 /// This can be placed as the body of a call continuation, when the caller is
1997 /// known never to invoke it, e.g. because the calling expression always throws.
1998 class Unreachable extends TailExpression {
1999 accept(BlockVisitor visitor) => visitor.visitUnreachable(this);
2000 void setParentPointers() {}
2001 }
2002
2003 /// Invoke a continuation in tail position.
2004 class InvokeContinuation extends TailExpression {
2005 Reference<Continuation> continuationRef;
2006 List<Reference<Primitive>> argumentRefs;
2007 SourceInformation sourceInformation;
2008
2009 Continuation get continuation => continuationRef.definition;
2010 Primitive argument(int n) => argumentRefs[n].definition;
2011 Iterable<Primitive> get arguments => _dereferenceList(argumentRefs);
2012
2013 // An invocation of a continuation is recursive if it occurs in the body of
2014 // the continuation itself.
2015 bool isRecursive;
2016
2017 /// True if this invocation escapes from the body of a [LetHandler]
2018 /// (i.e. a try block). Notably, such an invocation cannot be inlined.
2019 bool isEscapingTry;
2020
2021 InvokeContinuation(Continuation cont, List<Primitive> args,
2022 {this.isRecursive: false,
2023 this.isEscapingTry: false,
2024 this.sourceInformation})
2025 : continuationRef = new Reference<Continuation>(cont),
2026 argumentRefs = _referenceList(args) {
2027 assert(cont.parameters == null || cont.parameters.length == args.length);
2028 if (isRecursive) cont.isRecursive = true;
2029 }
2030
2031 /// A continuation invocation whose target and arguments will be filled
2032 /// in later.
2033 ///
2034 /// Used as a placeholder for a jump whose target is not yet created
2035 /// (e.g., in the translation of break and continue).
2036 InvokeContinuation.uninitialized(
2037 {this.isRecursive: false, this.isEscapingTry: false})
2038 : continuationRef = null,
2039 argumentRefs = null,
2040 sourceInformation = null;
2041
2042 accept(BlockVisitor visitor) => visitor.visitInvokeContinuation(this);
2043
2044 void setParentPointers() {
2045 if (continuationRef != null) continuationRef.parent = this;
2046 if (argumentRefs != null) _setParentsOnList(argumentRefs, this);
2047 }
2048 }
2049
2050 /// Choose between a pair of continuations based on a condition value.
2051 ///
2052 /// The two continuations must not declare any parameters.
2053 class Branch extends TailExpression {
2054 final Reference<Primitive> conditionRef;
2055 final Reference<Continuation> trueContinuationRef;
2056 final Reference<Continuation> falseContinuationRef;
2057 final SourceInformation sourceInformation;
2058
2059 Primitive get condition => conditionRef.definition;
2060 Continuation get trueContinuation => trueContinuationRef.definition;
2061 Continuation get falseContinuation => falseContinuationRef.definition;
2062
2063 /// If true, only the value `true` satisfies the condition. Otherwise, any
2064 /// truthy value satisfies the check.
2065 ///
2066 /// Non-strict checks are preferable when the condition is known to be a
2067 /// boolean.
2068 bool isStrictCheck;
2069
2070 Branch(Primitive condition, Continuation trueCont, Continuation falseCont,
2071 this.sourceInformation,
2072 {bool strict})
2073 : this.conditionRef = new Reference<Primitive>(condition),
2074 trueContinuationRef = new Reference<Continuation>(trueCont),
2075 falseContinuationRef = new Reference<Continuation>(falseCont),
2076 isStrictCheck = strict {
2077 assert(strict != null);
2078 }
2079
2080 Branch.strict(Primitive condition, Continuation trueCont,
2081 Continuation falseCont, SourceInformation sourceInformation)
2082 : this(condition, trueCont, falseCont, sourceInformation, strict: true);
2083
2084 Branch.loose(Primitive condition, Continuation trueCont,
2085 Continuation falseCont, SourceInformation sourceInformation)
2086 : this(condition, trueCont, falseCont, sourceInformation, strict: false);
2087
2088 accept(BlockVisitor visitor) => visitor.visitBranch(this);
2089
2090 void setParentPointers() {
2091 conditionRef.parent = this;
2092 trueContinuationRef.parent = this;
2093 falseContinuationRef.parent = this;
2094 }
2095 }
2096
2097 // ----------------------------------------------------------------------------
2098 // UTILITY STUFF
2099 // ----------------------------------------------------------------------------
2100
2101 Reference<Primitive> _optionalReference(Primitive definition) {
2102 return definition == null ? null : new Reference<Primitive>(definition);
2103 }
2104
2105 List<Reference<Primitive>> _referenceList(Iterable<Primitive> definitions) {
2106 return definitions.map((e) => new Reference<Primitive>(e)).toList();
2107 }
2108
2109 Iterable<Primitive> _dereferenceList(List<Reference<Primitive>> references) {
2110 return references.map((ref) => ref.definition);
2111 }
2112
2113 void _setParentsOnNodes(List<Node> nodes, Node parent) {
2114 for (Node node in nodes) {
2115 node.parent = parent;
2116 }
2117 }
2118
2119 void _setParentsOnList(List<Reference> nodes, Node parent) {
2120 for (Reference node in nodes) {
2121 node.parent = parent;
2122 }
2123 }
2124
2125 // ----------------------------------------------------------------------------
2126 // VISITORS
2127 // ----------------------------------------------------------------------------
2128
2129 /// Visitor for block-level traversals that do not need to dispatch on
2130 /// primitives.
2131 abstract class BlockVisitor<T> {
2132 const BlockVisitor();
2133
2134 T visit(Node node) => node.accept(this);
2135
2136 // Block headers.
2137 T visitFunctionDefinition(FunctionDefinition node) => null;
2138 T visitContinuation(Continuation node) => null;
2139
2140 // Interior expressions.
2141 T visitLetPrim(LetPrim node) => null;
2142 T visitLetCont(LetCont node) => null;
2143 T visitLetHandler(LetHandler node) => null;
2144 T visitLetMutable(LetMutable node) => null;
2145
2146 // Tail expressions.
2147 T visitInvokeContinuation(InvokeContinuation node) => null;
2148 T visitThrow(Throw node) => null;
2149 T visitRethrow(Rethrow node) => null;
2150 T visitBranch(Branch node) => null;
2151 T visitUnreachable(Unreachable node) => null;
2152
2153 /// Visits block-level nodes in lexical post-order (not post-dominator order).
2154 ///
2155 /// Continuations and function definitions are considered "block headers".
2156 /// The block itself is the sequence of interior expressions in the body,
2157 /// terminated by a tail expression.
2158 ///
2159 /// Each block is visited starting with its tail expression, then every
2160 /// interior expression from bottom to top, and finally the block header
2161 /// is visited.
2162 ///
2163 /// Blocks are visited in post-order, so the body of a continuation is always
2164 /// processed before its non-recursive invocation sites.
2165 ///
2166 /// The IR may be transformed during the traversal, but only the original
2167 /// nodes will be visited.
2168 static void traverseInPostOrder(FunctionDefinition root, BlockVisitor v) {
2169 List<Continuation> stack = <Continuation>[];
2170 List<Node> nodes = <Node>[];
2171 void walkBlock(InteriorNode block) {
2172 nodes.add(block);
2173 Expression node = block.body;
2174 nodes.add(node);
2175 while (node.next != null) {
2176 if (node is LetCont) {
2177 stack.addAll(node.continuations);
2178 } else if (node is LetHandler) {
2179 stack.add(node.handler);
2180 }
2181 node = node.next;
2182 nodes.add(node);
2183 }
2184 }
2185
2186 walkBlock(root);
2187 while (stack.isNotEmpty) {
2188 walkBlock(stack.removeLast());
2189 }
2190 nodes.reversed.forEach(v.visit);
2191 }
2192
2193 /// Visits block-level nodes in lexical pre-order.
2194 ///
2195 /// Traversal continues at the original success for the current node, so:
2196 /// - The current node can safely be removed.
2197 /// - Nodes inserted immediately below the current node will not be seen.
2198 /// - The body of the current node should not be moved/removed, as traversal
2199 /// would otherwise continue into an orphaned or relocated node.
2200 static void traverseInPreOrder(FunctionDefinition root, BlockVisitor v) {
2201 List<Continuation> stack = <Continuation>[];
2202 void walkBlock(InteriorNode block) {
2203 v.visit(block);
2204 Expression node = block.body;
2205 while (node != null) {
2206 if (node is LetCont) {
2207 stack.addAll(node.continuations);
2208 } else if (node is LetHandler) {
2209 stack.add(node.handler);
2210 }
2211 Expression next = node.next;
2212 v.visit(node);
2213 node = next;
2214 }
2215 }
2216
2217 walkBlock(root);
2218 while (stack.isNotEmpty) {
2219 walkBlock(stack.removeLast());
2220 }
2221 }
2222 }
2223
2224 abstract class Visitor<T> implements BlockVisitor<T> {
2225 const Visitor();
2226
2227 T visit(Node node);
2228
2229 // Definitions.
2230 T visitInvokeStatic(InvokeStatic node);
2231 T visitInvokeMethod(InvokeMethod node);
2232 T visitInvokeMethodDirectly(InvokeMethodDirectly node);
2233 T visitInvokeConstructor(InvokeConstructor node);
2234 T visitTypeCast(TypeCast node);
2235 T visitSetMutable(SetMutable node);
2236 T visitSetStatic(SetStatic node);
2237 T visitSetField(SetField node);
2238 T visitGetLazyStatic(GetLazyStatic node);
2239 T visitAwait(Await node);
2240 T visitYield(Yield node);
2241 T visitLiteralList(LiteralList node);
2242 T visitConstant(Constant node);
2243 T visitGetMutable(GetMutable node);
2244 T visitParameter(Parameter node);
2245 T visitMutableVariable(MutableVariable node);
2246 T visitGetStatic(GetStatic node);
2247 T visitInterceptor(Interceptor node);
2248 T visitCreateInstance(CreateInstance node);
2249 T visitGetField(GetField node);
2250 T visitCreateBox(CreateBox node);
2251 T visitReifyRuntimeType(ReifyRuntimeType node);
2252 T visitReadTypeVariable(ReadTypeVariable node);
2253 T visitTypeExpression(TypeExpression node);
2254 T visitCreateInvocationMirror(CreateInvocationMirror node);
2255 T visitTypeTest(TypeTest node);
2256 T visitTypeTestViaFlag(TypeTestViaFlag node);
2257 T visitApplyBuiltinOperator(ApplyBuiltinOperator node);
2258 T visitApplyBuiltinMethod(ApplyBuiltinMethod node);
2259 T visitGetLength(GetLength node);
2260 T visitGetIndex(GetIndex node);
2261 T visitSetIndex(SetIndex node);
2262 T visitRefinement(Refinement node);
2263 T visitBoundsCheck(BoundsCheck node);
2264 T visitReceiverCheck(ReceiverCheck node);
2265 T visitForeignCode(ForeignCode node);
2266 }
2267
2268 /// Recursively visits all children of a CPS term.
2269 ///
2270 /// The user of the class is responsible for avoiding stack overflows from
2271 /// deep recursion, e.g. by overriding methods to cut off recursion at certain
2272 /// points.
2273 ///
2274 /// All recursive invocations occur through the [visit] method, which the
2275 /// subclass may override as a generic way to control the visitor without
2276 /// overriding all visitor methods.
2277 ///
2278 /// The `process*` methods are called in pre-order for every node visited.
2279 /// These can be overridden without disrupting the visitor traversal.
2280 class DeepRecursiveVisitor implements Visitor {
2281 const DeepRecursiveVisitor();
2282
2283 visit(Node node) => node.accept(this);
2284
2285 processReference(Reference ref) {}
2286
2287 processFunctionDefinition(FunctionDefinition node) {}
2288 visitFunctionDefinition(FunctionDefinition node) {
2289 processFunctionDefinition(node);
2290 if (node.interceptorParameter != null) visit(node.interceptorParameter);
2291 if (node.receiverParameter != null) visit(node.receiverParameter);
2292 node.parameters.forEach(visit);
2293 visit(node.body);
2294 }
2295
2296 processContinuation(Continuation node) {}
2297 visitContinuation(Continuation node) {
2298 processContinuation(node);
2299 node.parameters.forEach(visit);
2300 if (node.body != null) visit(node.body);
2301 }
2302
2303 // Expressions.
2304 processLetPrim(LetPrim node) {}
2305 visitLetPrim(LetPrim node) {
2306 processLetPrim(node);
2307 visit(node.primitive);
2308 visit(node.body);
2309 }
2310
2311 processLetCont(LetCont node) {}
2312 visitLetCont(LetCont node) {
2313 processLetCont(node);
2314 node.continuations.forEach(visit);
2315 visit(node.body);
2316 }
2317
2318 processLetHandler(LetHandler node) {}
2319 visitLetHandler(LetHandler node) {
2320 processLetHandler(node);
2321 visit(node.handler);
2322 visit(node.body);
2323 }
2324
2325 processLetMutable(LetMutable node) {}
2326 visitLetMutable(LetMutable node) {
2327 processLetMutable(node);
2328 visit(node.variable);
2329 processReference(node.valueRef);
2330 visit(node.body);
2331 }
2332
2333 processInvokeStatic(InvokeStatic node) {}
2334 visitInvokeStatic(InvokeStatic node) {
2335 processInvokeStatic(node);
2336 node.argumentRefs.forEach(processReference);
2337 }
2338
2339 processInvokeContinuation(InvokeContinuation node) {}
2340 visitInvokeContinuation(InvokeContinuation node) {
2341 processInvokeContinuation(node);
2342 processReference(node.continuationRef);
2343 node.argumentRefs.forEach(processReference);
2344 }
2345
2346 processInvokeMethod(InvokeMethod node) {}
2347 visitInvokeMethod(InvokeMethod node) {
2348 processInvokeMethod(node);
2349 if (node.interceptorRef != null) {
2350 processReference(node.interceptorRef);
2351 }
2352 processReference(node.receiverRef);
2353 node.argumentRefs.forEach(processReference);
2354 }
2355
2356 processInvokeMethodDirectly(InvokeMethodDirectly node) {}
2357 visitInvokeMethodDirectly(InvokeMethodDirectly node) {
2358 processInvokeMethodDirectly(node);
2359 if (node.interceptorRef != null) {
2360 processReference(node.interceptorRef);
2361 }
2362 processReference(node.receiverRef);
2363 node.argumentRefs.forEach(processReference);
2364 }
2365
2366 processInvokeConstructor(InvokeConstructor node) {}
2367 visitInvokeConstructor(InvokeConstructor node) {
2368 processInvokeConstructor(node);
2369 node.argumentRefs.forEach(processReference);
2370 }
2371
2372 processThrow(Throw node) {}
2373 visitThrow(Throw node) {
2374 processThrow(node);
2375 processReference(node.valueRef);
2376 }
2377
2378 processRethrow(Rethrow node) {}
2379 visitRethrow(Rethrow node) {
2380 processRethrow(node);
2381 }
2382
2383 processBranch(Branch node) {}
2384 visitBranch(Branch node) {
2385 processBranch(node);
2386 processReference(node.trueContinuationRef);
2387 processReference(node.falseContinuationRef);
2388 processReference(node.conditionRef);
2389 }
2390
2391 processTypeCast(TypeCast node) {}
2392 visitTypeCast(TypeCast node) {
2393 processTypeCast(node);
2394 processReference(node.valueRef);
2395 node.typeArgumentRefs.forEach(processReference);
2396 }
2397
2398 processTypeTest(TypeTest node) {}
2399 visitTypeTest(TypeTest node) {
2400 processTypeTest(node);
2401 processReference(node.valueRef);
2402 node.typeArgumentRefs.forEach(processReference);
2403 }
2404
2405 processTypeTestViaFlag(TypeTestViaFlag node) {}
2406 visitTypeTestViaFlag(TypeTestViaFlag node) {
2407 processTypeTestViaFlag(node);
2408 processReference(node.interceptorRef);
2409 }
2410
2411 processSetMutable(SetMutable node) {}
2412 visitSetMutable(SetMutable node) {
2413 processSetMutable(node);
2414 processReference(node.variableRef);
2415 processReference(node.valueRef);
2416 }
2417
2418 processGetLazyStatic(GetLazyStatic node) {}
2419 visitGetLazyStatic(GetLazyStatic node) {
2420 processGetLazyStatic(node);
2421 }
2422
2423 processLiteralList(LiteralList node) {}
2424 visitLiteralList(LiteralList node) {
2425 processLiteralList(node);
2426 node.valueRefs.forEach(processReference);
2427 }
2428
2429 processConstant(Constant node) {}
2430 visitConstant(Constant node) {
2431 processConstant(node);
2432 }
2433
2434 processMutableVariable(node) {}
2435 visitMutableVariable(MutableVariable node) {
2436 processMutableVariable(node);
2437 }
2438
2439 processGetMutable(GetMutable node) {}
2440 visitGetMutable(GetMutable node) {
2441 processGetMutable(node);
2442 processReference(node.variableRef);
2443 }
2444
2445 processParameter(Parameter node) {}
2446 visitParameter(Parameter node) {
2447 processParameter(node);
2448 }
2449
2450 processInterceptor(Interceptor node) {}
2451 visitInterceptor(Interceptor node) {
2452 processInterceptor(node);
2453 processReference(node.inputRef);
2454 }
2455
2456 processCreateInstance(CreateInstance node) {}
2457 visitCreateInstance(CreateInstance node) {
2458 processCreateInstance(node);
2459 node.argumentRefs.forEach(processReference);
2460 if (node.typeInformationRef != null) {
2461 processReference(node.typeInformationRef);
2462 }
2463 }
2464
2465 processSetField(SetField node) {}
2466 visitSetField(SetField node) {
2467 processSetField(node);
2468 processReference(node.objectRef);
2469 processReference(node.valueRef);
2470 }
2471
2472 processGetField(GetField node) {}
2473 visitGetField(GetField node) {
2474 processGetField(node);
2475 processReference(node.objectRef);
2476 }
2477
2478 processGetStatic(GetStatic node) {}
2479 visitGetStatic(GetStatic node) {
2480 processGetStatic(node);
2481 if (node.witnessRef != null) {
2482 processReference(node.witnessRef);
2483 }
2484 }
2485
2486 processSetStatic(SetStatic node) {}
2487 visitSetStatic(SetStatic node) {
2488 processSetStatic(node);
2489 processReference(node.valueRef);
2490 }
2491
2492 processCreateBox(CreateBox node) {}
2493 visitCreateBox(CreateBox node) {
2494 processCreateBox(node);
2495 }
2496
2497 processReifyRuntimeType(ReifyRuntimeType node) {}
2498 visitReifyRuntimeType(ReifyRuntimeType node) {
2499 processReifyRuntimeType(node);
2500 processReference(node.valueRef);
2501 }
2502
2503 processReadTypeVariable(ReadTypeVariable node) {}
2504 visitReadTypeVariable(ReadTypeVariable node) {
2505 processReadTypeVariable(node);
2506 processReference(node.targetRef);
2507 }
2508
2509 processTypeExpression(TypeExpression node) {}
2510 visitTypeExpression(TypeExpression node) {
2511 processTypeExpression(node);
2512 node.argumentRefs.forEach(processReference);
2513 }
2514
2515 processCreateInvocationMirror(CreateInvocationMirror node) {}
2516 visitCreateInvocationMirror(CreateInvocationMirror node) {
2517 processCreateInvocationMirror(node);
2518 node.argumentRefs.forEach(processReference);
2519 }
2520
2521 processApplyBuiltinOperator(ApplyBuiltinOperator node) {}
2522 visitApplyBuiltinOperator(ApplyBuiltinOperator node) {
2523 processApplyBuiltinOperator(node);
2524 node.argumentRefs.forEach(processReference);
2525 }
2526
2527 processApplyBuiltinMethod(ApplyBuiltinMethod node) {}
2528 visitApplyBuiltinMethod(ApplyBuiltinMethod node) {
2529 processApplyBuiltinMethod(node);
2530 processReference(node.receiverRef);
2531 node.argumentRefs.forEach(processReference);
2532 }
2533
2534 processForeignCode(ForeignCode node) {}
2535 visitForeignCode(ForeignCode node) {
2536 processForeignCode(node);
2537 node.argumentRefs.forEach(processReference);
2538 }
2539
2540 processUnreachable(Unreachable node) {}
2541 visitUnreachable(Unreachable node) {
2542 processUnreachable(node);
2543 }
2544
2545 processAwait(Await node) {}
2546 visitAwait(Await node) {
2547 processAwait(node);
2548 processReference(node.inputRef);
2549 }
2550
2551 processYield(Yield node) {}
2552 visitYield(Yield node) {
2553 processYield(node);
2554 processReference(node.inputRef);
2555 }
2556
2557 processGetLength(GetLength node) {}
2558 visitGetLength(GetLength node) {
2559 processGetLength(node);
2560 processReference(node.objectRef);
2561 }
2562
2563 processGetIndex(GetIndex node) {}
2564 visitGetIndex(GetIndex node) {
2565 processGetIndex(node);
2566 processReference(node.objectRef);
2567 processReference(node.indexRef);
2568 }
2569
2570 processSetIndex(SetIndex node) {}
2571 visitSetIndex(SetIndex node) {
2572 processSetIndex(node);
2573 processReference(node.objectRef);
2574 processReference(node.indexRef);
2575 processReference(node.valueRef);
2576 }
2577
2578 processRefinement(Refinement node) {}
2579 visitRefinement(Refinement node) {
2580 processRefinement(node);
2581 processReference(node.value);
2582 }
2583
2584 processBoundsCheck(BoundsCheck node) {}
2585 visitBoundsCheck(BoundsCheck node) {
2586 processBoundsCheck(node);
2587 processReference(node.objectRef);
2588 if (node.indexRef != null) {
2589 processReference(node.indexRef);
2590 }
2591 if (node.lengthRef != null) {
2592 processReference(node.lengthRef);
2593 }
2594 }
2595
2596 processNullCheck(ReceiverCheck node) {}
2597 visitReceiverCheck(ReceiverCheck node) {
2598 processNullCheck(node);
2599 processReference(node.valueRef);
2600 if (node.conditionRef != null) {
2601 processReference(node.conditionRef);
2602 }
2603 }
2604 }
2605
2606 typedef void StackAction();
2607
2608 /// Calls `process*` for all nodes in a tree.
2609 /// For simple usage, only override the `process*` methods.
2610 ///
2611 /// To avoid deep recursion, this class uses an "action stack" containing
2612 /// callbacks to be invoked after the processing of some term has finished.
2613 ///
2614 /// To avoid excessive overhead from the action stack, basic blocks of
2615 /// interior nodes are iterated in a loop without using the action stack.
2616 ///
2617 /// The iteration order can be controlled by overriding the `traverse*`
2618 /// methods for [LetCont], [LetPrim], [LetMutable], [LetHandler] and
2619 /// [Continuation].
2620 ///
2621 /// The `traverse*` methods return the expression to visit next, and may
2622 /// push other subterms onto the stack using [push] or [pushAction] to visit
2623 /// them later. Actions pushed onto the stack will be executed after the body
2624 /// has been processed (and the stack actions it pushed have been executed).
2625 ///
2626 /// By default, the `traverse` methods visit all non-recursive subterms,
2627 /// push all bound continuations on the stack, and return the body of the term.
2628 ///
2629 /// Subclasses should not override the `visit` methods for the nodes that have
2630 /// a `traverse` method.
2631 class TrampolineRecursiveVisitor extends DeepRecursiveVisitor {
2632 List<StackAction> _stack = <StackAction>[];
2633
2634 void pushAction(StackAction callback) {
2635 _stack.add(callback);
2636 }
2637
2638 void push(Continuation cont) {
2639 _stack.add(() {
2640 if (cont.isReturnContinuation) {
2641 traverseContinuation(cont);
2642 } else {
2643 _processBlock(traverseContinuation(cont));
2644 }
2645 });
2646 }
2647
2648 visitFunctionDefinition(FunctionDefinition node) {
2649 processFunctionDefinition(node);
2650 if (node.interceptorParameter != null) visit(node.interceptorParameter);
2651 if (node.receiverParameter != null) visit(node.receiverParameter);
2652 node.parameters.forEach(visit);
2653 visit(node.body);
2654 }
2655
2656 visitContinuation(Continuation cont) {
2657 if (cont.isReturnContinuation) {
2658 traverseContinuation(cont);
2659 } else {
2660 int initialHeight = _stack.length;
2661 Expression body = traverseContinuation(cont);
2662 _trampoline(body, initialHeight: initialHeight);
2663 }
2664 }
2665
2666 visitLetPrim(LetPrim node) => _trampoline(node);
2667 visitLetCont(LetCont node) => _trampoline(node);
2668 visitLetHandler(LetHandler node) => _trampoline(node);
2669 visitLetMutable(LetMutable node) => _trampoline(node);
2670
2671 Expression traverseContinuation(Continuation cont) {
2672 processContinuation(cont);
2673 cont.parameters.forEach(visitParameter);
2674 return cont.body;
2675 }
2676
2677 Expression traverseLetCont(LetCont node) {
2678 processLetCont(node);
2679 node.continuations.forEach(push);
2680 return node.body;
2681 }
2682
2683 Expression traverseLetHandler(LetHandler node) {
2684 processLetHandler(node);
2685 push(node.handler);
2686 return node.body;
2687 }
2688
2689 Expression traverseLetPrim(LetPrim node) {
2690 processLetPrim(node);
2691 visit(node.primitive);
2692 return node.body;
2693 }
2694
2695 Expression traverseLetMutable(LetMutable node) {
2696 processLetMutable(node);
2697 visit(node.variable);
2698 processReference(node.valueRef);
2699 return node.body;
2700 }
2701
2702 void _trampoline(Expression node, {int initialHeight}) {
2703 initialHeight = initialHeight ?? _stack.length;
2704 _processBlock(node);
2705 while (_stack.length > initialHeight) {
2706 StackAction callback = _stack.removeLast();
2707 callback();
2708 }
2709 }
2710
2711 _processBlock(Expression node) {
2712 while (node is InteriorExpression) {
2713 if (node is LetCont) {
2714 node = traverseLetCont(node);
2715 } else if (node is LetHandler) {
2716 node = traverseLetHandler(node);
2717 } else if (node is LetPrim) {
2718 node = traverseLetPrim(node);
2719 } else {
2720 node = traverseLetMutable(node);
2721 }
2722 }
2723 visit(node);
2724 }
2725 }
2726
2727 /// Visit a just-deleted subterm and unlink all [Reference]s in it.
2728 class RemovalVisitor extends TrampolineRecursiveVisitor {
2729 processReference(Reference reference) {
2730 reference.unlink();
2731 }
2732
2733 static void remove(Node node) {
2734 (new RemovalVisitor()).visit(node);
2735 }
2736 }
2737
2738 /// A visitor to copy instances of [Definition] or its subclasses, except for
2739 /// instances of [Continuation].
2740 ///
2741 /// The visitor maintains a map from original definitions to their copies.
2742 /// When the [copy] method is called for a non-Continuation definition,
2743 /// a copy is created, added to the map and returned as the result. Copying a
2744 /// definition assumes that the definitions of all references have already
2745 /// been copied by the same visitor.
2746 class DefinitionCopyingVisitor extends Visitor<Definition> {
2747 Map<Definition, Definition> _copies = <Definition, Definition>{};
2748
2749 /// Put a copy into the map.
2750 ///
2751 /// This method should be used instead of directly adding copies to the map.
2752 Definition putCopy(Definition original, Definition copy) {
2753 if (copy is Variable) {
2754 Variable originalVariable = original;
2755 copy.type = originalVariable.type;
2756 copy.hint = originalVariable.hint;
2757 }
2758 return _copies[original] = copy;
2759 }
2760
2761 /// Get the copy of a [Reference]'s definition from the map.
2762 Definition getCopy(Reference reference) => _copies[reference.definition];
2763
2764 /// Get the copy of a [Reference]'s definition from the map.
2765 Definition getCopyOrNull(Reference reference) =>
2766 reference == null ? null : getCopy(reference);
2767
2768 /// Map a list of [Reference]s to the list of their definition's copies.
2769 List<Definition> getList(List<Reference> list) => list.map(getCopy).toList();
2770
2771 /// Copy a non-[Continuation] [Definition].
2772 Definition copy(Definition node) {
2773 assert(node is! Continuation);
2774 return putCopy(node, visit(node));
2775 }
2776
2777 Definition visit(Node node) => node.accept(this);
2778
2779 visitFunctionDefinition(FunctionDefinition node) {}
2780 visitLetPrim(LetPrim node) {}
2781 visitLetCont(LetCont node) {}
2782 visitLetHandler(LetHandler node) {}
2783 visitLetMutable(LetMutable node) {}
2784 visitInvokeContinuation(InvokeContinuation node) {}
2785 visitThrow(Throw node) {}
2786 visitRethrow(Rethrow node) {}
2787 visitBranch(Branch node) {}
2788 visitUnreachable(Unreachable node) {}
2789 visitContinuation(Continuation node) {}
2790
2791 Definition visitInvokeStatic(InvokeStatic node) {
2792 return new InvokeStatic(node.target, node.selector,
2793 getList(node.argumentRefs), node.sourceInformation);
2794 }
2795
2796 Definition visitInvokeMethod(InvokeMethod node) {
2797 return new InvokeMethod(getCopy(node.receiverRef), node.selector, node.mask,
2798 getList(node.argumentRefs),
2799 sourceInformation: node.sourceInformation,
2800 callingConvention: node.callingConvention,
2801 interceptor: getCopyOrNull(node.interceptorRef));
2802 }
2803
2804 Definition visitInvokeMethodDirectly(InvokeMethodDirectly node) {
2805 return new InvokeMethodDirectly(getCopy(node.receiverRef), node.target,
2806 node.selector, getList(node.argumentRefs), node.sourceInformation,
2807 interceptor: getCopyOrNull(node.interceptorRef));
2808 }
2809
2810 Definition visitInvokeConstructor(InvokeConstructor node) {
2811 return new InvokeConstructor(
2812 node.dartType,
2813 node.target,
2814 node.selector,
2815 getList(node.argumentRefs),
2816 node.sourceInformation)..allocationSiteType = node.allocationSiteType;
2817 }
2818
2819 Definition visitTypeCast(TypeCast node) {
2820 return new TypeCast(
2821 getCopy(node.valueRef), node.dartType, getList(node.typeArgumentRefs));
2822 }
2823
2824 Definition visitSetMutable(SetMutable node) {
2825 return new SetMutable(getCopy(node.variableRef), getCopy(node.valueRef),
2826 sourceInformation: node.sourceInformation);
2827 }
2828
2829 Definition visitSetStatic(SetStatic node) {
2830 return new SetStatic(
2831 node.element, getCopy(node.valueRef), node.sourceInformation);
2832 }
2833
2834 Definition visitSetField(SetField node) {
2835 return new SetField(
2836 getCopy(node.objectRef), node.field, getCopy(node.valueRef),
2837 sourceInformation: node.sourceInformation);
2838 }
2839
2840 Definition visitGetLazyStatic(GetLazyStatic node) {
2841 return new GetLazyStatic(node.element,
2842 isFinal: node.isFinal, sourceInformation: node.sourceInformation);
2843 }
2844
2845 Definition visitAwait(Await node) {
2846 return new Await(getCopy(node.inputRef));
2847 }
2848
2849 Definition visitYield(Yield node) {
2850 return new Yield(getCopy(node.inputRef), node.hasStar);
2851 }
2852
2853 Definition visitLiteralList(LiteralList node) {
2854 return new LiteralList(node.dartType, getList(node.valueRefs))
2855 ..allocationSiteType = node.allocationSiteType;
2856 }
2857
2858 Definition visitConstant(Constant node) {
2859 return new Constant(node.value, sourceInformation: node.sourceInformation);
2860 }
2861
2862 Definition visitGetMutable(GetMutable node) {
2863 return new GetMutable(getCopy(node.variableRef),
2864 sourceInformation: node.sourceInformation);
2865 }
2866
2867 Definition visitParameter(Parameter node) {
2868 return new Parameter(node.hint);
2869 }
2870
2871 Definition visitMutableVariable(MutableVariable node) {
2872 return new MutableVariable(node.hint);
2873 }
2874
2875 Definition visitGetStatic(GetStatic node) {
2876 if (node.witnessRef != null) {
2877 return new GetStatic.witnessed(node.element, getCopy(node.witnessRef),
2878 sourceInformation: node.sourceInformation);
2879 } else {
2880 return new GetStatic(node.element,
2881 isFinal: node.isFinal, sourceInformation: node.sourceInformation);
2882 }
2883 }
2884
2885 Definition visitInterceptor(Interceptor node) {
2886 return new Interceptor(getCopy(node.inputRef), node.sourceInformation)
2887 ..interceptedClasses.addAll(node.interceptedClasses);
2888 }
2889
2890 Definition visitCreateInstance(CreateInstance node) {
2891 return new CreateInstance(node.classElement, getList(node.argumentRefs),
2892 getCopyOrNull(node.typeInformationRef), node.sourceInformation);
2893 }
2894
2895 Definition visitGetField(GetField node) {
2896 return new GetField(getCopy(node.objectRef), node.field,
2897 isFinal: node.isFinal);
2898 }
2899
2900 Definition visitCreateBox(CreateBox node) {
2901 return new CreateBox();
2902 }
2903
2904 Definition visitReifyRuntimeType(ReifyRuntimeType node) {
2905 return new ReifyRuntimeType(getCopy(node.valueRef), node.sourceInformation);
2906 }
2907
2908 Definition visitReadTypeVariable(ReadTypeVariable node) {
2909 return new ReadTypeVariable(
2910 node.variable, getCopy(node.targetRef), node.sourceInformation);
2911 }
2912
2913 Definition visitTypeExpression(TypeExpression node) {
2914 return new TypeExpression(
2915 node.kind, node.dartType, getList(node.argumentRefs));
2916 }
2917
2918 Definition visitCreateInvocationMirror(CreateInvocationMirror node) {
2919 return new CreateInvocationMirror(
2920 node.selector, getList(node.argumentRefs));
2921 }
2922
2923 Definition visitTypeTest(TypeTest node) {
2924 return new TypeTest(
2925 getCopy(node.valueRef), node.dartType, getList(node.typeArgumentRefs));
2926 }
2927
2928 Definition visitTypeTestViaFlag(TypeTestViaFlag node) {
2929 return new TypeTestViaFlag(getCopy(node.interceptorRef), node.dartType);
2930 }
2931
2932 Definition visitApplyBuiltinOperator(ApplyBuiltinOperator node) {
2933 return new ApplyBuiltinOperator(
2934 node.operator, getList(node.argumentRefs), node.sourceInformation);
2935 }
2936
2937 Definition visitApplyBuiltinMethod(ApplyBuiltinMethod node) {
2938 return new ApplyBuiltinMethod(node.method, getCopy(node.receiverRef),
2939 getList(node.argumentRefs), node.sourceInformation);
2940 }
2941
2942 Definition visitGetLength(GetLength node) {
2943 return new GetLength(getCopy(node.objectRef), isFinal: node.isFinal);
2944 }
2945
2946 Definition visitGetIndex(GetIndex node) {
2947 return new GetIndex(getCopy(node.objectRef), getCopy(node.indexRef));
2948 }
2949
2950 Definition visitSetIndex(SetIndex node) {
2951 return new SetIndex(getCopy(node.objectRef), getCopy(node.indexRef),
2952 getCopy(node.valueRef));
2953 }
2954
2955 Definition visitRefinement(Refinement node) {
2956 return new Refinement(getCopy(node.value), node.refineType);
2957 }
2958
2959 Definition visitBoundsCheck(BoundsCheck node) {
2960 if (node.hasNoChecks) {
2961 return new BoundsCheck.noCheck(
2962 getCopy(node.objectRef), node.sourceInformation);
2963 } else {
2964 return new BoundsCheck(getCopy(node.objectRef), getCopy(node.indexRef),
2965 getCopyOrNull(node.lengthRef), node.checks, node.sourceInformation);
2966 }
2967 }
2968
2969 Definition visitReceiverCheck(ReceiverCheck node) {
2970 return new ReceiverCheck(
2971 getCopy(node.valueRef), node.selector, node.sourceInformation,
2972 condition: getCopyOrNull(node.conditionRef),
2973 useSelector: node.useSelector,
2974 isNullCheck: node.isNullCheck);
2975 }
2976
2977 Definition visitForeignCode(ForeignCode node) {
2978 return new ForeignCode(node.codeTemplate, node.storedType,
2979 getList(node.argumentRefs), node.nativeBehavior, node.sourceInformation,
2980 dependency: node.dependency);
2981 }
2982 }
2983
2984 /// A trampolining visitor to copy [FunctionDefinition]s.
2985 class CopyingVisitor extends TrampolineRecursiveVisitor {
2986 // The visitor maintains a map from original continuations to their copies.
2987 Map<Continuation, Continuation> _copies = <Continuation, Continuation>{};
2988
2989 // The visitor uses an auxiliary visitor to copy definitions.
2990 DefinitionCopyingVisitor _definitions = new DefinitionCopyingVisitor();
2991
2992 // While copying a block, the state of the visitor is a 'linked list' of
2993 // the expressions in the block's body, with a pointer to the last element
2994 // of the list.
2995 Expression _first = null;
2996 Expression _current = null;
2997
2998 void plug(Expression body) {
2999 if (_first == null) {
3000 _first = body;
3001 } else {
3002 assert(_current != null);
3003 InteriorExpression interior = _current;
3004 interior.body = body;
3005 body.parent = interior;
3006 }
3007 _current = body;
3008 }
3009
3010 // Continuations are added to the visitor's stack to be visited after copying
3011 // the current block is finished. The stack action saves the current block,
3012 // copies the continuation's body, sets the body on the copy of the
3013 // continuation, and restores the current block.
3014 //
3015 // Note that continuations are added to the copy map before the stack action
3016 // to visit them is performed.
3017 void push(Continuation cont) {
3018 assert(!cont.isReturnContinuation);
3019 _stack.add(() {
3020 Expression savedFirst = _first;
3021 _first = _current = null;
3022 _processBlock(cont.body);
3023 Continuation contCopy = _copies[cont];
3024 contCopy.body = _first;
3025 _first.parent = contCopy;
3026 _first = savedFirst;
3027 _current = null;
3028 });
3029 }
3030
3031 FunctionDefinition copy(FunctionDefinition node) {
3032 assert(_first == null && _current == null);
3033 _first = _current = null;
3034 // Definitions are copied where they are bound, before processing
3035 // expressions in the scope of their binding.
3036 Parameter thisParameter = node.receiverParameter == null
3037 ? null
3038 : _definitions.copy(node.receiverParameter);
3039 Parameter interceptorParameter = node.interceptorParameter == null
3040 ? null
3041 : _definitions.copy(node.interceptorParameter);
3042 List<Parameter> parameters =
3043 node.parameters.map(_definitions.copy).toList();
3044 // Though the return continuation's parameter does not have any uses,
3045 // we still make a proper copy to ensure that hints, type, etc. are
3046 // copied.
3047 Parameter returnParameter =
3048 _definitions.copy(node.returnContinuation.parameters.first);
3049 Continuation returnContinuation =
3050 _copies[node.returnContinuation] = new Continuation([returnParameter]);
3051
3052 visit(node.body);
3053 FunctionDefinition copy = new FunctionDefinition(
3054 node.element, thisParameter, parameters, returnContinuation, _first,
3055 interceptorParameter: interceptorParameter,
3056 sourceInformation: node.sourceInformation);
3057 _first = _current = null;
3058 return copy;
3059 }
3060
3061 Node visit(Node node) => node.accept(this);
3062
3063 Expression traverseLetCont(LetCont node) {
3064 // Continuations are copied where they are bound, before processing
3065 // expressions in the scope of their binding.
3066 List<Continuation> continuations = node.continuations.map((Continuation c) {
3067 push(c);
3068 return _copies[c] =
3069 new Continuation(c.parameters.map(_definitions.copy).toList());
3070 }).toList();
3071 plug(new LetCont.many(continuations, null));
3072 return node.body;
3073 }
3074
3075 Expression traverseLetHandler(LetHandler node) {
3076 // Continuations are copied where they are bound, before processing
3077 // expressions in the scope of their binding.
3078 push(node.handler);
3079 Continuation handler = _copies[node.handler] = new Continuation(
3080 node.handler.parameters.map(_definitions.copy).toList());
3081 plug(new LetHandler(handler, null));
3082 return node.body;
3083 }
3084
3085 Expression traverseLetPrim(LetPrim node) {
3086 plug(new LetPrim(_definitions.copy(node.primitive)));
3087 return node.body;
3088 }
3089
3090 Expression traverseLetMutable(LetMutable node) {
3091 plug(new LetMutable(
3092 _definitions.copy(node.variable), _definitions.getCopy(node.valueRef)));
3093 return node.body;
3094 }
3095
3096 // Tail expressions do not have references, so we do not need to map them
3097 // to their copies.
3098 visitInvokeContinuation(InvokeContinuation node) {
3099 plug(new InvokeContinuation(
3100 _copies[node.continuation], _definitions.getList(node.argumentRefs),
3101 isRecursive: node.isRecursive,
3102 isEscapingTry: node.isEscapingTry,
3103 sourceInformation: node.sourceInformation));
3104 }
3105
3106 visitThrow(Throw node) {
3107 plug(new Throw(_definitions.getCopy(node.valueRef)));
3108 }
3109
3110 visitRethrow(Rethrow node) {
3111 plug(new Rethrow());
3112 }
3113
3114 visitBranch(Branch node) {
3115 plug(new Branch.loose(
3116 _definitions.getCopy(node.conditionRef),
3117 _copies[node.trueContinuation],
3118 _copies[node.falseContinuation],
3119 node.sourceInformation)..isStrictCheck = node.isStrictCheck);
3120 }
3121
3122 visitUnreachable(Unreachable node) {
3123 plug(new Unreachable());
3124 }
3125 }
OLDNEW
« no previous file with comments | « pkg/compiler/lib/src/cps_ir/cps_ir_integrity.dart ('k') | pkg/compiler/lib/src/cps_ir/cps_ir_nodes_sexpr.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698