forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathast-graph-builder.cc
More file actions
4310 lines (3719 loc) · 159 KB
/
ast-graph-builder.cc
File metadata and controls
4310 lines (3719 loc) · 159 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/ast-graph-builder.h"
#include "src/compiler.h"
#include "src/compiler/ast-loop-assignment-analyzer.h"
#include "src/compiler/control-builders.h"
#include "src/compiler/js-type-feedback.h"
#include "src/compiler/linkage.h"
#include "src/compiler/liveness-analyzer.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/operator-properties.h"
#include "src/compiler/state-values-utils.h"
#include "src/full-codegen/full-codegen.h"
#include "src/parser.h"
#include "src/scopes.h"
namespace v8 {
namespace internal {
namespace compiler {
// Each expression in the AST is evaluated in a specific context. This context
// decides how the evaluation result is passed up the visitor.
class AstGraphBuilder::AstContext BASE_EMBEDDED {
public:
bool IsEffect() const { return kind_ == Expression::kEffect; }
bool IsValue() const { return kind_ == Expression::kValue; }
bool IsTest() const { return kind_ == Expression::kTest; }
// Determines how to combine the frame state with the value
// that is about to be plugged into this AstContext.
OutputFrameStateCombine GetStateCombine() {
return IsEffect() ? OutputFrameStateCombine::Ignore()
: OutputFrameStateCombine::Push();
}
// Plug a node into this expression context. Call this function in tail
// position in the Visit functions for expressions.
virtual void ProduceValue(Node* value) = 0;
// Unplugs a node from this expression context. Call this to retrieve the
// result of another Visit function that already plugged the context.
virtual Node* ConsumeValue() = 0;
// Shortcut for "context->ProduceValue(context->ConsumeValue())".
void ReplaceValue() { ProduceValue(ConsumeValue()); }
protected:
AstContext(AstGraphBuilder* owner, Expression::Context kind);
virtual ~AstContext();
AstGraphBuilder* owner() const { return owner_; }
Environment* environment() const { return owner_->environment(); }
// We want to be able to assert, in a context-specific way, that the stack
// height makes sense when the context is filled.
#ifdef DEBUG
int original_height_;
#endif
private:
Expression::Context kind_;
AstGraphBuilder* owner_;
AstContext* outer_;
};
// Context to evaluate expression for its side effects only.
class AstGraphBuilder::AstEffectContext final : public AstContext {
public:
explicit AstEffectContext(AstGraphBuilder* owner)
: AstContext(owner, Expression::kEffect) {}
~AstEffectContext() final;
void ProduceValue(Node* value) final;
Node* ConsumeValue() final;
};
// Context to evaluate expression for its value (and side effects).
class AstGraphBuilder::AstValueContext final : public AstContext {
public:
explicit AstValueContext(AstGraphBuilder* owner)
: AstContext(owner, Expression::kValue) {}
~AstValueContext() final;
void ProduceValue(Node* value) final;
Node* ConsumeValue() final;
};
// Context to evaluate expression for a condition value (and side effects).
class AstGraphBuilder::AstTestContext final : public AstContext {
public:
explicit AstTestContext(AstGraphBuilder* owner)
: AstContext(owner, Expression::kTest) {}
~AstTestContext() final;
void ProduceValue(Node* value) final;
Node* ConsumeValue() final;
};
// Scoped class tracking context objects created by the visitor. Represents
// mutations of the context chain within the function body and allows to
// change the current {scope} and {context} during visitation.
class AstGraphBuilder::ContextScope BASE_EMBEDDED {
public:
ContextScope(AstGraphBuilder* builder, Scope* scope, Node* context)
: builder_(builder),
outer_(builder->execution_context()),
scope_(scope),
depth_(builder_->environment()->context_chain_length()) {
builder_->environment()->PushContext(context); // Push.
builder_->set_execution_context(this);
}
~ContextScope() {
builder_->set_execution_context(outer_); // Pop.
builder_->environment()->PopContext();
CHECK_EQ(depth_, builder_->environment()->context_chain_length());
}
// Current scope during visitation.
Scope* scope() const { return scope_; }
private:
AstGraphBuilder* builder_;
ContextScope* outer_;
Scope* scope_;
int depth_;
};
// Scoped class tracking control statements entered by the visitor. There are
// different types of statements participating in this stack to properly track
// local as well as non-local control flow:
// - IterationStatement : Allows proper 'break' and 'continue' behavior.
// - BreakableStatement : Allows 'break' from block and switch statements.
// - TryCatchStatement : Intercepts 'throw' and implicit exceptional edges.
// - TryFinallyStatement: Intercepts 'break', 'continue', 'throw' and 'return'.
class AstGraphBuilder::ControlScope BASE_EMBEDDED {
public:
explicit ControlScope(AstGraphBuilder* builder)
: builder_(builder),
outer_(builder->execution_control()),
context_length_(builder->environment()->context_chain_length()),
stack_height_(builder->environment()->stack_height()) {
builder_->set_execution_control(this); // Push.
}
virtual ~ControlScope() {
builder_->set_execution_control(outer_); // Pop.
}
// Either 'break' or 'continue' to the target statement.
void BreakTo(BreakableStatement* target);
void ContinueTo(BreakableStatement* target);
// Either 'return' or 'throw' the given value.
void ReturnValue(Node* return_value);
void ThrowValue(Node* exception_value);
class DeferredCommands;
protected:
enum Command { CMD_BREAK, CMD_CONTINUE, CMD_RETURN, CMD_THROW };
// Performs one of the above commands on this stack of control scopes. This
// walks through the stack giving each scope a chance to execute or defer the
// given command by overriding the {Execute} method appropriately. Note that
// this also drops extra operands from the environment for each skipped scope.
void PerformCommand(Command cmd, Statement* target, Node* value);
// Interface to execute a given command in this scope. Returning {true} here
// indicates successful execution whereas {false} requests to skip scope.
virtual bool Execute(Command cmd, Statement* target, Node* value) {
// For function-level control.
switch (cmd) {
case CMD_THROW:
builder()->BuildThrow(value);
return true;
case CMD_RETURN:
builder()->BuildReturn(value);
return true;
case CMD_BREAK:
case CMD_CONTINUE:
break;
}
return false;
}
Environment* environment() { return builder_->environment(); }
AstGraphBuilder* builder() const { return builder_; }
int context_length() const { return context_length_; }
int stack_height() const { return stack_height_; }
private:
AstGraphBuilder* builder_;
ControlScope* outer_;
int context_length_;
int stack_height_;
};
// Helper class for a try-finally control scope. It can record intercepted
// control-flow commands that cause entry into a finally-block, and re-apply
// them after again leaving that block. Special tokens are used to identify
// paths going through the finally-block to dispatch after leaving the block.
class AstGraphBuilder::ControlScope::DeferredCommands : public ZoneObject {
public:
explicit DeferredCommands(AstGraphBuilder* owner)
: owner_(owner), deferred_(owner->zone()) {}
// One recorded control-flow command.
struct Entry {
Command command; // The command type being applied on this path.
Statement* statement; // The target statement for the command or {NULL}.
Node* token; // A token identifying this particular path.
};
// Records a control-flow command while entering the finally-block. This also
// generates a new dispatch token that identifies one particular path.
Node* RecordCommand(Command cmd, Statement* stmt, Node* value) {
Node* token = NewPathTokenForDeferredCommand();
deferred_.push_back({cmd, stmt, token});
return token;
}
// Returns the dispatch token to be used to identify the implicit fall-through
// path at the end of a try-block into the corresponding finally-block.
Node* GetFallThroughToken() { return NewPathTokenForImplicitFallThrough(); }
// Applies all recorded control-flow commands after the finally-block again.
// This generates a dynamic dispatch on the token from the entry point.
void ApplyDeferredCommands(Node* token, Node* value) {
SwitchBuilder dispatch(owner_, static_cast<int>(deferred_.size()));
dispatch.BeginSwitch();
for (size_t i = 0; i < deferred_.size(); ++i) {
Node* condition = NewPathDispatchCondition(token, deferred_[i].token);
dispatch.BeginLabel(static_cast<int>(i), condition);
dispatch.EndLabel();
}
for (size_t i = 0; i < deferred_.size(); ++i) {
dispatch.BeginCase(static_cast<int>(i));
owner_->execution_control()->PerformCommand(
deferred_[i].command, deferred_[i].statement, value);
dispatch.EndCase();
}
dispatch.EndSwitch();
}
protected:
Node* NewPathTokenForDeferredCommand() {
return owner_->jsgraph()->Constant(static_cast<int>(deferred_.size()));
}
Node* NewPathTokenForImplicitFallThrough() {
return owner_->jsgraph()->Constant(-1);
}
Node* NewPathDispatchCondition(Node* t1, Node* t2) {
// TODO(mstarzinger): This should be machine()->WordEqual(), but our Phi
// nodes all have kRepTagged|kTypeAny, which causes representation mismatch.
return owner_->NewNode(owner_->javascript()->StrictEqual(), t1, t2);
}
private:
AstGraphBuilder* owner_;
ZoneVector<Entry> deferred_;
};
// Control scope implementation for a BreakableStatement.
class AstGraphBuilder::ControlScopeForBreakable : public ControlScope {
public:
ControlScopeForBreakable(AstGraphBuilder* owner, BreakableStatement* target,
ControlBuilder* control)
: ControlScope(owner), target_(target), control_(control) {}
protected:
virtual bool Execute(Command cmd, Statement* target, Node* value) override {
if (target != target_) return false; // We are not the command target.
switch (cmd) {
case CMD_BREAK:
control_->Break();
return true;
case CMD_CONTINUE:
case CMD_THROW:
case CMD_RETURN:
break;
}
return false;
}
private:
BreakableStatement* target_;
ControlBuilder* control_;
};
// Control scope implementation for an IterationStatement.
class AstGraphBuilder::ControlScopeForIteration : public ControlScope {
public:
ControlScopeForIteration(AstGraphBuilder* owner, IterationStatement* target,
LoopBuilder* control)
: ControlScope(owner), target_(target), control_(control) {}
protected:
virtual bool Execute(Command cmd, Statement* target, Node* value) override {
if (target != target_) return false; // We are not the command target.
switch (cmd) {
case CMD_BREAK:
control_->Break();
return true;
case CMD_CONTINUE:
control_->Continue();
return true;
case CMD_THROW:
case CMD_RETURN:
break;
}
return false;
}
private:
BreakableStatement* target_;
LoopBuilder* control_;
};
// Control scope implementation for a TryCatchStatement.
class AstGraphBuilder::ControlScopeForCatch : public ControlScope {
public:
ControlScopeForCatch(AstGraphBuilder* owner, TryCatchBuilder* control)
: ControlScope(owner), control_(control) {
builder()->try_nesting_level_++; // Increment nesting.
builder()->try_catch_nesting_level_++;
}
~ControlScopeForCatch() {
builder()->try_nesting_level_--; // Decrement nesting.
builder()->try_catch_nesting_level_--;
}
protected:
virtual bool Execute(Command cmd, Statement* target, Node* value) override {
switch (cmd) {
case CMD_THROW:
control_->Throw(value);
return true;
case CMD_BREAK:
case CMD_CONTINUE:
case CMD_RETURN:
break;
}
return false;
}
private:
TryCatchBuilder* control_;
};
// Control scope implementation for a TryFinallyStatement.
class AstGraphBuilder::ControlScopeForFinally : public ControlScope {
public:
ControlScopeForFinally(AstGraphBuilder* owner, DeferredCommands* commands,
TryFinallyBuilder* control)
: ControlScope(owner), commands_(commands), control_(control) {
builder()->try_nesting_level_++; // Increment nesting.
}
~ControlScopeForFinally() {
builder()->try_nesting_level_--; // Decrement nesting.
}
protected:
virtual bool Execute(Command cmd, Statement* target, Node* value) override {
Node* token = commands_->RecordCommand(cmd, target, value);
control_->LeaveTry(token, value);
return true;
}
private:
DeferredCommands* commands_;
TryFinallyBuilder* control_;
};
// Helper for generating before and after frame states.
class AstGraphBuilder::FrameStateBeforeAndAfter {
public:
FrameStateBeforeAndAfter(AstGraphBuilder* builder, BailoutId id_before)
: builder_(builder), frame_state_before_(nullptr) {
frame_state_before_ = id_before == BailoutId::None()
? builder_->jsgraph()->EmptyFrameState()
: builder_->environment()->Checkpoint(id_before);
}
void AddToNode(Node* node, BailoutId id_after,
OutputFrameStateCombine combine) {
int count = OperatorProperties::GetFrameStateInputCount(node->op());
DCHECK_LE(count, 2);
if (count >= 1) {
// Add the frame state for after the operation.
DCHECK_EQ(IrOpcode::kDead,
NodeProperties::GetFrameStateInput(node, 0)->opcode());
Node* frame_state_after =
id_after == BailoutId::None()
? builder_->jsgraph()->EmptyFrameState()
: builder_->environment()->Checkpoint(id_after, combine);
NodeProperties::ReplaceFrameStateInput(node, 0, frame_state_after);
}
if (count >= 2) {
// Add the frame state for before the operation.
DCHECK_EQ(IrOpcode::kDead,
NodeProperties::GetFrameStateInput(node, 1)->opcode());
NodeProperties::ReplaceFrameStateInput(node, 1, frame_state_before_);
}
}
private:
AstGraphBuilder* builder_;
Node* frame_state_before_;
};
AstGraphBuilder::AstGraphBuilder(Zone* local_zone, CompilationInfo* info,
JSGraph* jsgraph, LoopAssignmentAnalysis* loop,
JSTypeFeedbackTable* js_type_feedback)
: local_zone_(local_zone),
info_(info),
jsgraph_(jsgraph),
environment_(nullptr),
ast_context_(nullptr),
globals_(0, local_zone),
execution_control_(nullptr),
execution_context_(nullptr),
try_catch_nesting_level_(0),
try_nesting_level_(0),
input_buffer_size_(0),
input_buffer_(nullptr),
exit_controls_(local_zone),
loop_assignment_analysis_(loop),
state_values_cache_(jsgraph),
liveness_analyzer_(static_cast<size_t>(info->scope()->num_stack_slots()),
local_zone),
frame_state_function_info_(common()->CreateFrameStateFunctionInfo(
FrameStateType::kJavaScriptFunction, info->num_parameters() + 1,
info->scope()->num_stack_slots(), info->shared_info(),
CALL_MAINTAINS_NATIVE_CONTEXT)),
js_type_feedback_(js_type_feedback) {
InitializeAstVisitor(info->isolate(), local_zone);
}
Node* AstGraphBuilder::GetFunctionClosureForContext() {
Scope* closure_scope = current_scope()->ClosureScope();
if (closure_scope->is_script_scope() ||
closure_scope->is_module_scope()) {
// Contexts nested in the native context have a canonical empty function as
// their closure, not the anonymous closure containing the global code.
// Pass a SMI sentinel and let the runtime look up the empty function.
return jsgraph()->SmiConstant(0);
} else {
DCHECK(closure_scope->is_function_scope());
return GetFunctionClosure();
}
}
Node* AstGraphBuilder::GetFunctionClosure() {
if (!function_closure_.is_set()) {
const Operator* op = common()->Parameter(
Linkage::kJSFunctionCallClosureParamIndex, "%closure");
Node* node = NewNode(op, graph()->start());
function_closure_.set(node);
}
return function_closure_.get();
}
Node* AstGraphBuilder::GetFunctionContext() {
if (!function_context_.is_set()) {
// Parameter (arity + 1) is special for the outer context of the function
const Operator* op = common()->Parameter(
info()->num_parameters_including_this(), "%context");
Node* node = NewNode(op, graph()->start());
function_context_.set(node);
}
return function_context_.get();
}
bool AstGraphBuilder::CreateGraph(bool stack_check) {
Scope* scope = info()->scope();
DCHECK(graph() != NULL);
// Set up the basic structure of the graph. Outputs for {Start} are the formal
// parameters (including the receiver) plus context and closure.
int actual_parameter_count = info()->num_parameters_including_this() + 2;
graph()->SetStart(graph()->NewNode(common()->Start(actual_parameter_count)));
// Initialize the top-level environment.
Environment env(this, scope, graph()->start());
set_environment(&env);
if (info()->is_osr()) {
// Use OSR normal entry as the start of the top-level environment.
// It will be replaced with {Dead} after typing and optimizations.
NewNode(common()->OsrNormalEntry());
}
// Initialize the incoming context.
ContextScope incoming(this, scope, GetFunctionContext());
// Initialize control scope.
ControlScope control(this);
// TODO(mstarzinger): For now we cannot assume that the {this} parameter is
// not {the_hole}, because for derived classes {this} has a TDZ and the
// JSConstructStubForDerived magically passes {the_hole} as a receiver.
if (scope->has_this_declaration() && scope->receiver()->is_const_mode()) {
env.RawParameterBind(0, jsgraph()->TheHoleConstant());
}
// Build receiver check for sloppy mode if necessary.
// TODO(mstarzinger/verwaest): Should this be moved back into the CallIC?
if (scope->has_this_declaration()) {
Node* original_receiver = env.RawParameterLookup(0);
Node* patched_receiver = BuildPatchReceiverToGlobalProxy(original_receiver);
env.RawParameterBind(0, patched_receiver);
}
// Build function context only if there are context allocated variables.
if (info()->num_heap_slots() > 0) {
// Push a new inner context scope for the function.
Node* inner_context = BuildLocalFunctionContext(GetFunctionContext());
ContextScope top_context(this, scope, inner_context);
CreateGraphBody(stack_check);
} else {
// Simply use the outer function context in building the graph.
CreateGraphBody(stack_check);
}
// Finish the basic structure of the graph.
DCHECK_NE(0u, exit_controls_.size());
int const input_count = static_cast<int>(exit_controls_.size());
Node** const inputs = &exit_controls_.front();
Node* end = graph()->NewNode(common()->End(input_count), input_count, inputs);
graph()->SetEnd(end);
// Compute local variable liveness information and use it to relax
// frame states.
ClearNonLiveSlotsInFrameStates();
// Failures indicated by stack overflow.
return !HasStackOverflow();
}
void AstGraphBuilder::CreateGraphBody(bool stack_check) {
Scope* scope = info()->scope();
// Build the arguments object if it is used.
BuildArgumentsObject(scope->arguments());
// Build rest arguments array if it is used.
int rest_index;
Variable* rest_parameter = scope->rest_parameter(&rest_index);
BuildRestArgumentsArray(rest_parameter, rest_index);
// Build assignment to {.this_function} variable if it is used.
BuildThisFunctionVariable(scope->this_function_var());
// Build assignment to {new.target} variable if it is used.
BuildNewTargetVariable(scope->new_target_var());
// Emit tracing call if requested to do so.
if (FLAG_trace) {
NewNode(javascript()->CallRuntime(Runtime::kTraceEnter, 0));
}
// Visit illegal re-declaration and bail out if it exists.
if (scope->HasIllegalRedeclaration()) {
VisitForEffect(scope->GetIllegalRedeclaration());
return;
}
// Visit declarations within the function scope.
VisitDeclarations(scope->declarations());
// Build a stack-check before the body.
if (stack_check) {
Node* node = NewNode(javascript()->StackCheck());
PrepareFrameState(node, BailoutId::FunctionEntry());
}
// Visit statements in the function body.
VisitStatements(info()->literal()->body());
// Emit tracing call if requested to do so.
if (FLAG_trace) {
// TODO(mstarzinger): Only traces implicit return.
Node* return_value = jsgraph()->UndefinedConstant();
NewNode(javascript()->CallRuntime(Runtime::kTraceExit, 1), return_value);
}
// Return 'undefined' in case we can fall off the end.
BuildReturn(jsgraph()->UndefinedConstant());
}
void AstGraphBuilder::ClearNonLiveSlotsInFrameStates() {
if (!FLAG_analyze_environment_liveness ||
!info()->is_deoptimization_enabled()) {
return;
}
NonLiveFrameStateSlotReplacer replacer(
&state_values_cache_, jsgraph()->UndefinedConstant(),
liveness_analyzer()->local_count(), local_zone());
Variable* arguments = info()->scope()->arguments();
if (arguments != nullptr && arguments->IsStackAllocated()) {
replacer.MarkPermanentlyLive(arguments->index());
}
liveness_analyzer()->Run(&replacer);
if (FLAG_trace_environment_liveness) {
OFStream os(stdout);
liveness_analyzer()->Print(os);
}
}
// Gets the bailout id just before reading a variable proxy, but only for
// unallocated variables.
static BailoutId BeforeId(VariableProxy* proxy) {
return proxy->var()->IsUnallocatedOrGlobalSlot() ? proxy->BeforeId()
: BailoutId::None();
}
static const char* GetDebugParameterName(Zone* zone, Scope* scope, int index) {
#if DEBUG
const AstRawString* name = scope->parameter(index)->raw_name();
if (name && name->length() > 0) {
char* data = zone->NewArray<char>(name->length() + 1);
data[name->length()] = 0;
memcpy(data, name->raw_data(), name->length());
return data;
}
#endif
return nullptr;
}
AstGraphBuilder::Environment::Environment(AstGraphBuilder* builder,
Scope* scope,
Node* control_dependency)
: builder_(builder),
parameters_count_(scope->num_parameters() + 1),
locals_count_(scope->num_stack_slots()),
liveness_block_(IsLivenessAnalysisEnabled()
? builder_->liveness_analyzer()->NewBlock()
: nullptr),
values_(builder_->local_zone()),
contexts_(builder_->local_zone()),
control_dependency_(control_dependency),
effect_dependency_(control_dependency),
parameters_node_(nullptr),
locals_node_(nullptr),
stack_node_(nullptr) {
DCHECK_EQ(scope->num_parameters() + 1, parameters_count());
// Bind the receiver variable.
int param_num = 0;
if (builder->info()->is_this_defined()) {
const Operator* op = common()->Parameter(param_num++, "%this");
Node* receiver = builder->graph()->NewNode(op, builder->graph()->start());
values()->push_back(receiver);
} else {
values()->push_back(builder->jsgraph()->UndefinedConstant());
}
// Bind all parameter variables. The parameter indices are shifted by 1
// (receiver is parameter index -1 but environment index 0).
for (int i = 0; i < scope->num_parameters(); ++i) {
const char* debug_name = GetDebugParameterName(graph()->zone(), scope, i);
const Operator* op = common()->Parameter(param_num++, debug_name);
Node* parameter = builder->graph()->NewNode(op, builder->graph()->start());
values()->push_back(parameter);
}
// Bind all local variables to undefined.
Node* undefined_constant = builder->jsgraph()->UndefinedConstant();
values()->insert(values()->end(), locals_count(), undefined_constant);
}
AstGraphBuilder::Environment::Environment(AstGraphBuilder::Environment* copy,
LivenessAnalyzerBlock* liveness_block)
: builder_(copy->builder_),
parameters_count_(copy->parameters_count_),
locals_count_(copy->locals_count_),
liveness_block_(liveness_block),
values_(copy->zone()),
contexts_(copy->zone()),
control_dependency_(copy->control_dependency_),
effect_dependency_(copy->effect_dependency_),
parameters_node_(copy->parameters_node_),
locals_node_(copy->locals_node_),
stack_node_(copy->stack_node_) {
const size_t kStackEstimate = 7; // optimum from experimentation!
values_.reserve(copy->values_.size() + kStackEstimate);
values_.insert(values_.begin(), copy->values_.begin(), copy->values_.end());
contexts_.reserve(copy->contexts_.size());
contexts_.insert(contexts_.begin(), copy->contexts_.begin(),
copy->contexts_.end());
}
void AstGraphBuilder::Environment::Bind(Variable* variable, Node* node) {
DCHECK(variable->IsStackAllocated());
if (variable->IsParameter()) {
// The parameter indices are shifted by 1 (receiver is parameter
// index -1 but environment index 0).
values()->at(variable->index() + 1) = node;
} else {
DCHECK(variable->IsStackLocal());
values()->at(variable->index() + parameters_count_) = node;
DCHECK(IsLivenessBlockConsistent());
if (liveness_block() != nullptr) {
liveness_block()->Bind(variable->index());
}
}
}
Node* AstGraphBuilder::Environment::Lookup(Variable* variable) {
DCHECK(variable->IsStackAllocated());
if (variable->IsParameter()) {
// The parameter indices are shifted by 1 (receiver is parameter
// index -1 but environment index 0).
return values()->at(variable->index() + 1);
} else {
DCHECK(variable->IsStackLocal());
DCHECK(IsLivenessBlockConsistent());
if (liveness_block() != nullptr) {
liveness_block()->Lookup(variable->index());
}
return values()->at(variable->index() + parameters_count_);
}
}
void AstGraphBuilder::Environment::MarkAllLocalsLive() {
DCHECK(IsLivenessBlockConsistent());
if (liveness_block() != nullptr) {
for (int i = 0; i < locals_count_; i++) {
liveness_block()->Lookup(i);
}
}
}
void AstGraphBuilder::Environment::RawParameterBind(int index, Node* node) {
DCHECK_LT(index, parameters_count());
values()->at(index) = node;
}
Node* AstGraphBuilder::Environment::RawParameterLookup(int index) {
DCHECK_LT(index, parameters_count());
return values()->at(index);
}
AstGraphBuilder::Environment*
AstGraphBuilder::Environment::CopyForConditional() {
LivenessAnalyzerBlock* copy_liveness_block = nullptr;
if (liveness_block() != nullptr) {
copy_liveness_block =
builder_->liveness_analyzer()->NewBlock(liveness_block());
liveness_block_ = builder_->liveness_analyzer()->NewBlock(liveness_block());
}
return new (zone()) Environment(this, copy_liveness_block);
}
AstGraphBuilder::Environment*
AstGraphBuilder::Environment::CopyAsUnreachable() {
Environment* env = new (zone()) Environment(this, nullptr);
env->MarkAsUnreachable();
return env;
}
AstGraphBuilder::Environment*
AstGraphBuilder::Environment::CopyAndShareLiveness() {
if (liveness_block() != nullptr) {
// Finish the current liveness block before copying.
liveness_block_ = builder_->liveness_analyzer()->NewBlock(liveness_block());
}
Environment* env = new (zone()) Environment(this, liveness_block());
return env;
}
AstGraphBuilder::Environment* AstGraphBuilder::Environment::CopyForLoop(
BitVector* assigned, bool is_osr) {
PrepareForLoop(assigned, is_osr);
return CopyAndShareLiveness();
}
void AstGraphBuilder::Environment::UpdateStateValues(Node** state_values,
int offset, int count) {
bool should_update = false;
Node** env_values = (count == 0) ? nullptr : &values()->at(offset);
if (*state_values == NULL || (*state_values)->InputCount() != count) {
should_update = true;
} else {
DCHECK(static_cast<size_t>(offset + count) <= values()->size());
for (int i = 0; i < count; i++) {
if ((*state_values)->InputAt(i) != env_values[i]) {
should_update = true;
break;
}
}
}
if (should_update) {
const Operator* op = common()->StateValues(count);
(*state_values) = graph()->NewNode(op, count, env_values);
}
}
void AstGraphBuilder::Environment::UpdateStateValuesWithCache(
Node** state_values, int offset, int count) {
Node** env_values = (count == 0) ? nullptr : &values()->at(offset);
*state_values = builder_->state_values_cache_.GetNodeForValues(
env_values, static_cast<size_t>(count));
}
Node* AstGraphBuilder::Environment::Checkpoint(
BailoutId ast_id, OutputFrameStateCombine combine) {
if (!builder()->info()->is_deoptimization_enabled()) {
return builder()->jsgraph()->EmptyFrameState();
}
UpdateStateValues(¶meters_node_, 0, parameters_count());
UpdateStateValuesWithCache(&locals_node_, parameters_count(), locals_count());
UpdateStateValues(&stack_node_, parameters_count() + locals_count(),
stack_height());
const Operator* op = common()->FrameState(
ast_id, combine, builder()->frame_state_function_info());
Node* result = graph()->NewNode(op, parameters_node_, locals_node_,
stack_node_, builder()->current_context(),
builder()->GetFunctionClosure(),
builder()->graph()->start());
DCHECK(IsLivenessBlockConsistent());
if (liveness_block() != nullptr) {
liveness_block()->Checkpoint(result);
}
return result;
}
bool AstGraphBuilder::Environment::IsLivenessAnalysisEnabled() {
return FLAG_analyze_environment_liveness &&
builder()->info()->is_deoptimization_enabled();
}
bool AstGraphBuilder::Environment::IsLivenessBlockConsistent() {
return (!IsLivenessAnalysisEnabled() || IsMarkedAsUnreachable()) ==
(liveness_block() == nullptr);
}
AstGraphBuilder::AstContext::AstContext(AstGraphBuilder* own,
Expression::Context kind)
: kind_(kind), owner_(own), outer_(own->ast_context()) {
owner()->set_ast_context(this); // Push.
#ifdef DEBUG
original_height_ = environment()->stack_height();
#endif
}
AstGraphBuilder::AstContext::~AstContext() {
owner()->set_ast_context(outer_); // Pop.
}
AstGraphBuilder::AstEffectContext::~AstEffectContext() {
DCHECK(environment()->stack_height() == original_height_);
}
AstGraphBuilder::AstValueContext::~AstValueContext() {
DCHECK(environment()->stack_height() == original_height_ + 1);
}
AstGraphBuilder::AstTestContext::~AstTestContext() {
DCHECK(environment()->stack_height() == original_height_ + 1);
}
void AstGraphBuilder::AstEffectContext::ProduceValue(Node* value) {
// The value is ignored.
}
void AstGraphBuilder::AstValueContext::ProduceValue(Node* value) {
environment()->Push(value);
}
void AstGraphBuilder::AstTestContext::ProduceValue(Node* value) {
environment()->Push(owner()->BuildToBoolean(value));
}
Node* AstGraphBuilder::AstEffectContext::ConsumeValue() { return NULL; }
Node* AstGraphBuilder::AstValueContext::ConsumeValue() {
return environment()->Pop();
}
Node* AstGraphBuilder::AstTestContext::ConsumeValue() {
return environment()->Pop();
}
Scope* AstGraphBuilder::current_scope() const {
return execution_context_->scope();
}
Node* AstGraphBuilder::current_context() const {
return environment()->Context();
}
void AstGraphBuilder::ControlScope::PerformCommand(Command command,
Statement* target,
Node* value) {
Environment* env = environment()->CopyAsUnreachable();
ControlScope* current = this;
while (current != NULL) {
environment()->TrimStack(current->stack_height());
environment()->TrimContextChain(current->context_length());
if (current->Execute(command, target, value)) break;
current = current->outer_;
}
builder()->set_environment(env);
DCHECK(current != NULL); // Always handled (unless stack is malformed).
}
void AstGraphBuilder::ControlScope::BreakTo(BreakableStatement* stmt) {
PerformCommand(CMD_BREAK, stmt, builder()->jsgraph()->TheHoleConstant());
}
void AstGraphBuilder::ControlScope::ContinueTo(BreakableStatement* stmt) {
PerformCommand(CMD_CONTINUE, stmt, builder()->jsgraph()->TheHoleConstant());
}
void AstGraphBuilder::ControlScope::ReturnValue(Node* return_value) {
PerformCommand(CMD_RETURN, nullptr, return_value);
}
void AstGraphBuilder::ControlScope::ThrowValue(Node* exception_value) {
PerformCommand(CMD_THROW, nullptr, exception_value);
}
void AstGraphBuilder::VisitForValueOrNull(Expression* expr) {
if (expr == NULL) {
return environment()->Push(jsgraph()->NullConstant());
}
VisitForValue(expr);
}
void AstGraphBuilder::VisitForValueOrTheHole(Expression* expr) {