/
ByteCodeEmitter.cpp
11964 lines (10443 loc) · 471 KB
/
ByteCodeEmitter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeByteCodePch.h"
#include "FormalsUtil.h"
#include "Language/AsmJs.h"
#include "ConfigFlagsList.h"
void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
void EmitAssignment(ParseNode *asgnNode, ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
void EmitLoad(ParseNode *rhs, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
void EmitCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fEvaluateComponents, Js::RegSlot overrideThisLocation = Js::Constants::NoRegister, Js::RegSlot newTargetLocation = Js::Constants::NoRegister);
void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot yieldStarIterator = Js::Constants::NoRegister);
void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator *byteCodeGenerator, Js::RegSlot location);
void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo);
bool CallTargetIsArray(ParseNode *pnode)
{
return pnode->nop == knopName && pnode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::Array;
}
#define STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
if ((isTopLevel)) \
{ \
byteCodeGenerator->StartStatement(pnode); \
}
#define ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
if ((isTopLevel)) \
{ \
byteCodeGenerator->EndStatement(pnode); \
}
BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE, ByteCodeGenerator *byteCodeGenerator)
{
// Try to determine whether pnodeSE (SE = side effect) may kill the named var represented by pnode.
if (pnode->nop == knopComputedName)
{
pnode = pnode->AsParseNodeUni()->pnode1;
}
if (pnode->nop != knopName)
{
// Only investigating named vars here.
return false;
}
ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
SList<ParseNode*> pNodeSEStack(alloc);
pNodeSEStack.Push(pnodeSE);
// A pnodeSE can have children that can cause a side effect on pnode. A stack is used to check
// pnodeSE and all potential pnodeSE children that could cause a side effect on pnode. When a
// child pnodeSE can cause a side effect on pnode, immediately return true. Otherwise continue
// checking children of pnodeSE until none exist
while (!pNodeSEStack.Empty())
{
ParseNode *currPnodeSE = pNodeSEStack.Pop();
uint fnop = ParseNode::Grfnop(currPnodeSE->nop);
if (fnop & fnopLeaf)
{
// pnodeSE is a leaf and can't kill anything.
continue;
}
else if (fnop & fnopAsg)
{
// pnodeSE is an assignment (=, ++, +=, etc.)
// Trying to examine the LHS of pnodeSE caused small perf regressions,
// maybe because of code layout or some other subtle effect.
return true;
}
else if (fnop & fnopUni)
{
// pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
if (currPnodeSE->nop == knopTempRef)
{
continue;
}
else if (currPnodeSE->AsParseNodeUni()->pnode1)
{
pNodeSEStack.Push(currPnodeSE->AsParseNodeUni()->pnode1);
}
}
else if (fnop & fnopBin)
{
// currPnodeSE is a binary (or ternary) op, so check sources (if present).
pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode1);
if (currPnodeSE->AsParseNodeBin()->pnode2)
{
pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode2);
}
}
else if (currPnodeSE->nop == knopQmark)
{
ParseNodeTri * pnodeTriSE = currPnodeSE->AsParseNodeTri();
pNodeSEStack.Push(pnodeTriSE->pnode1);
pNodeSEStack.Push(pnodeTriSE->pnode2);
pNodeSEStack.Push(pnodeTriSE->pnode3);
}
else if (currPnodeSE->nop == knopCall || currPnodeSE->nop == knopNew)
{
pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeTarget);
if (currPnodeSE->AsParseNodeCall()->pnodeArgs)
{
pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeArgs);
}
}
else if (currPnodeSE->nop == knopList)
{
return true;
}
}
return false;
}
bool IsCallOfConstants(ParseNode *pnode);
bool BlockHasOwnScope(ParseNodeBlock * pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
bool IsArguments(ParseNode *pnode)
{
for (;;)
{
switch (pnode->nop)
{
case knopName:
return pnode->AsParseNodeName()->sym && pnode->AsParseNodeName()->sym->IsArguments();
case knopCall:
case knopNew:
if (IsArguments(pnode->AsParseNodeCall()->pnodeTarget))
{
return true;
}
if (pnode->AsParseNodeCall()->pnodeArgs)
{
ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
while (pnodeArg->nop == knopList)
{
if (IsArguments(pnodeArg->AsParseNodeBin()->pnode1))
return true;
pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
}
pnode = pnodeArg;
break;
}
return false;
case knopArray:
if (pnode->AsParseNodeArrLit()->arrayOfNumbers || pnode->AsParseNodeArrLit()->count == 0)
{
return false;
}
pnode = pnode->AsParseNodeUni()->pnode1;
break;
case knopQmark:
if (IsArguments(pnode->AsParseNodeTri()->pnode1) || IsArguments(pnode->AsParseNodeTri()->pnode2))
{
return true;
}
pnode = pnode->AsParseNodeTri()->pnode3;
break;
//
// Cases where we don't check for "arguments" yet.
// Assume that they might have it. Disable the optimization is such scenarios
//
case knopList:
case knopObject:
case knopVarDecl:
case knopConstDecl:
case knopLetDecl:
case knopFncDecl:
case knopClassDecl:
case knopFor:
case knopIf:
case knopDoWhile:
case knopWhile:
case knopForIn:
case knopForOf:
case knopReturn:
case knopBlock:
case knopBreak:
case knopContinue:
case knopTypeof:
case knopThrow:
case knopWith:
case knopFinally:
case knopTry:
case knopTryCatch:
case knopTryFinally:
case knopArrayPattern:
case knopObjectPattern:
case knopParamPattern:
return true;
default:
{
uint flags = ParseNode::Grfnop(pnode->nop);
if (flags&fnopUni)
{
ParseNodeUni * pnodeUni = pnode->AsParseNodeUni();
Assert(pnodeUni->pnode1);
pnode = pnodeUni->pnode1;
break;
}
else if (flags&fnopBin)
{
ParseNodeBin * pnodeBin = pnode->AsParseNodeBin();
Assert(pnodeBin->pnode1 && pnodeBin->pnode2);
if (IsArguments(pnodeBin->pnode1))
{
return true;
}
pnode = pnodeBin->pnode2;
break;
}
return false;
}
}
}
}
bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall = false, ParseNode *bindPnode = nullptr, bool isTopLevel = false);
void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
static const Js::OpCode nopToOp[knopLim] =
{
#define OP(x) Br##x##_A
#define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
#include "ptlist.h"
};
static const Js::OpCode nopToCMOp[knopLim] =
{
#define OP(x) Cm##x##_A
#define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
#include "ptlist.h"
};
Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
{
switch (op)
{
case Js::OpCode::StLocalSlot:
return Js::OpCode::StLocalSlotChkUndecl;
case Js::OpCode::StParamSlot:
return Js::OpCode::StParamSlotChkUndecl;
case Js::OpCode::StInnerSlot:
return Js::OpCode::StInnerSlotChkUndecl;
case Js::OpCode::StEnvSlot:
return Js::OpCode::StEnvSlotChkUndecl;
case Js::OpCode::StObjSlot:
return Js::OpCode::StObjSlotChkUndecl;
case Js::OpCode::StLocalObjSlot:
return Js::OpCode::StLocalObjSlotChkUndecl;
case Js::OpCode::StParamObjSlot:
return Js::OpCode::StParamObjSlotChkUndecl;
case Js::OpCode::StInnerObjSlot:
return Js::OpCode::StInnerObjSlotChkUndecl;
case Js::OpCode::StEnvObjSlot:
return Js::OpCode::StEnvObjSlotChkUndecl;
default:
AssertMsg(false, "Unknown opcode for chk undecl mapping");
return Js::OpCode::InvalidOpCode;
}
}
// Tracks a register slot let/const property for the passed in debugger block/catch scope.
// debuggerScope - The scope to add the variable to.
// symbol - The symbol that represents the register property.
// funcInfo - The function info used to store the property into the tracked debugger register slot list.
// flags - The flags to assign to the property.
// isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
Js::DebuggerScope *debuggerScope,
Symbol *symbol,
FuncInfo *funcInfo,
Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
bool isFunctionDeclaration /*= false*/)
{
Assert(debuggerScope);
Assert(symbol);
Assert(funcInfo);
Js::RegSlot location = symbol->GetLocation();
Js::DebuggerScope *correctDebuggerScope = debuggerScope;
if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
{
// We have to get the appropriate scope and add property over there.
// Make sure the scope is created whether we're in debug mode or not, because we
// need the empty scopes present during reparsing for debug mode.
correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
}
if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
{
// Only track the property if we're in debug mode since it's only needed by the debugger.
Js::PropertyId propertyId = symbol->EnsurePosition(this);
this->Writer()->AddPropertyToDebuggerScope(
correctDebuggerScope,
location,
propertyId,
/*shouldConsumeRegister*/ true,
flags,
isFunctionDeclaration);
Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
symbol->SetIsTrackedForDebugger(true);
}
}
void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
Js::DebuggerScope *debuggerScope,
Symbol *symbol,
Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
bool isFunctionDeclaration /*= false*/)
{
Assert(debuggerScope);
Assert(symbol);
// Only need to track activation object properties in debug mode.
if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
{
Js::RegSlot location = symbol->GetLocation();
Js::PropertyId propertyId = symbol->EnsurePosition(this);
this->Writer()->AddPropertyToDebuggerScope(
debuggerScope,
location,
propertyId,
/*shouldConsumeRegister*/ false,
flags,
isFunctionDeclaration);
symbol->SetIsTrackedForDebugger(true);
}
}
void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
Js::DebuggerScope *debuggerScope,
Symbol* symbol,
Js::PropertyId propertyId,
Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
bool isFunctionDeclaration /*= false*/)
{
// Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
// of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
// after a debugger attach or for WWA apps). They are also needed for heap enumeration.
Assert(debuggerScope);
Assert(symbol);
if (!symbol->GetIsTrackedForDebugger())
{
Js::RegSlot location = symbol->GetScopeSlot();
Assert(location != Js::Constants::NoRegister);
Assert(propertyId != Js::Constants::NoProperty);
this->Writer()->AddPropertyToDebuggerScope(
debuggerScope,
location,
propertyId,
/*shouldConsumeRegister*/ false,
flags,
isFunctionDeclaration);
symbol->SetIsTrackedForDebugger(true);
}
}
// Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
{
Assert(functionDeclarationSymbol);
Assert(funcInfoParent);
AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
// Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
// which is done in other Track* functions that we call.
if (functionDeclarationSymbol->IsInSlot(this, funcInfoParent))
{
if (functionDeclarationSymbol->GetScope()->GetIsObject())
{
this->TrackActivationObjectPropertyForDebugger(
this->Writer()->GetCurrentDebuggerScope(),
functionDeclarationSymbol,
Js::DebuggerScopePropertyFlags_None,
true /*isFunctionDeclaration*/);
}
else
{
// Make sure the property has a slot. This will bump up the size of the slot array if necessary.
// Note that slot array inner function bindings are tracked even in non-debug mode in order
// to keep the lifetime of the closure binding that could escape around for heap enumeration.
functionDeclarationSymbol->EnsureScopeSlot(this, funcInfoParent);
functionDeclarationSymbol->EnsurePosition(this);
this->TrackSlotArrayPropertyForDebugger(
this->Writer()->GetCurrentDebuggerScope(),
functionDeclarationSymbol,
functionDeclarationSymbol->GetPosition(),
Js::DebuggerScopePropertyFlags_None,
true /*isFunctionDeclaration*/);
}
}
else
{
this->TrackRegisterPropertyForDebugger(
this->Writer()->GetCurrentDebuggerScope(),
functionDeclarationSymbol,
funcInfoParent,
Js::DebuggerScopePropertyFlags_None,
true /*isFunctionDeclaration*/);
}
}
// Updates the byte code offset of the property with the passed in location and ID.
// Used to track let/const variables that are in the dead zone debugger side.
// location - The activation object, scope slot index, or register location for the property.
// propertyId - The ID of the property to update.
// shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
{
Assert(this->Writer());
Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
Assert(currentDebuggerScope);
if (currentDebuggerScope != nullptr)
{
this->Writer()->UpdateDebuggerPropertyInitializationOffset(
currentDebuggerScope,
location,
propertyId,
shouldConsumeRegister);
}
}
void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
{
if (funcInfo->GetHasCachedScope())
{
this->LoadCachedHeapArguments(funcInfo);
}
else
{
this->LoadUncachedHeapArguments(funcInfo);
}
}
void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
{
Assert(funcInfo);
Assert(propIds);
Assert(byteCodeGenerator);
bool hadDuplicates = false;
Js::ArgSlot i = 0;
auto processArg = [&](ParseNode *pnode)
{
if (pnode->IsVarLetOrConst())
{
Assert(i < propIds->count);
Symbol *sym = pnode->AsParseNodeVar()->sym;
Assert(sym);
Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
//
// Check if the function has any same name parameters
// For the same name param, only the last one will be passed the correct propertyid
// For remaining dup param names, pass Constants::NoProperty
//
for (Js::ArgSlot j = 0; j < i; j++)
{
if (propIds->elements[j] == symPos)
{
// Found a dup parameter name
propIds->elements[j] = Js::Constants::NoProperty;
hadDuplicates = true;
break;
}
}
propIds->elements[i] = symPos;
}
else
{
propIds->elements[i] = Js::Constants::NoProperty;
}
++i;
};
MapFormals(funcInfo->root, processArg);
propIds->hadDuplicates = hadDuplicates;
}
void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
{
Assert(funcInfo->GetHasHeapArguments());
Scope *scope = funcInfo->GetBodyScope();
Assert(scope);
Symbol *argSym = funcInfo->GetArgumentsSymbol();
Assert(argSym && argSym->IsArguments());
Js::RegSlot argumentsLoc = argSym->GetLocation();
Js::OpCode opcode = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
bool hasRest = funcInfo->root->pnodeRest != nullptr;
uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
if (count == 0)
{
// If no formals to function (only "this"), then no need to create the scope object.
// Leave both the arguments location and the propertyIds location as null.
Assert(funcInfo->root->pnodeParams == nullptr && !hasRest);
}
else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
{
// We may not need a scope object for arguments, e.g. strict mode with no eval.
}
else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
{
// Pass the frame object and ID array to the runtime, and put the resulting Arguments object
// at the expected location.
Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(UInt32Math::Mul(count, sizeof(Js::PropertyId)), count, 0);
GetFormalArgsArray(this, funcInfo, propIds);
}
this->m_writer.Reg1(opcode, argumentsLoc);
EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
}
void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
{
Assert(funcInfo->GetHasHeapArguments());
Scope *scope = funcInfo->GetBodyScope();
Assert(scope);
Symbol *argSym = funcInfo->GetArgumentsSymbol();
Assert(argSym && argSym->IsArguments());
Js::RegSlot argumentsLoc = argSym->GetLocation();
Js::OpCode op = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
this->m_writer.Reg1(op, argumentsLoc);
EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
}
Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
{
Assert(stringNodeList);
uint index = 0;
Js::Var str;
IdentPtr pid;
Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
while (stringNodeList->nop == knopList)
{
Assert(stringNodeList->AsParseNodeBin()->pnode1->nop == knopStr);
pid = stringNodeList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid;
str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
index++;
}
Assert(stringNodeList->nop == knopStr);
pid = stringNodeList->AsParseNodeStr()->pid;
str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
return pArr;
}
// For now, this just assigns field ids for the current script.
// Later, we will combine this information with the global field id map.
// This temporary code will not work if a global member is accessed both with and without a LHS.
void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
{
globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
{
this->AssignPropertyId(sym, functionInfo);
});
}
void ByteCodeGenerator::InitBlockScopedContent(ParseNodeBlock *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
{
Assert(pnodeBlock->nop == knopBlock);
auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
{
// Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
// the debugger scope will not be created.
AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
FuncInfo *funcInfo = this->TopFuncInfo();
Symbol *sym = pnode->AsParseNodeVar()->sym;
Scope *scope = sym->GetScope();
if (sym->GetIsGlobal())
{
Js::PropertyId propertyId = sym->EnsurePosition(this);
if (this->flags & fscrEval)
{
AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
}
else
{
Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
}
}
else if (sym->IsInSlot(this, funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(this, funcInfo)))
{
if (scope->GetIsObject())
{
Js::RegSlot scopeLocation = scope->GetLocation();
Js::PropertyId propertyId = sym->EnsurePosition(this);
if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
{
uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
}
else
{
uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
}
TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
}
else
{
Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
this->EmitLocalPropInit(tmpReg, sym, funcInfo);
funcInfo->ReleaseTmpRegister(tmpReg);
// Slot array properties are tracked in non-debug mode as well because they need to stay
// around for heap enumeration and escaping during attach/detach.
TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
}
}
else if (!sym->GetIsModuleExportStorage())
{
if (sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl)
{
// let/const declared in a switch is the only case of a variable that must be checked for
// use-before-declaration dynamically within its own function.
this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
}
// Syms that begin in register may be delay-captured. In debugger mode, such syms
// will live only in slots, so tell the debugger to find them there.
if (sym->NeedsSlotAlloc(this, funcInfo))
{
TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
}
else
{
TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
}
}
};
IterateBlockScopedVariables(pnodeBlock, genBlockInit);
}
// Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
// If it has no let/const variables, nullptr will be returned as no scope will be created.
Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode * pnode, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
{
Assert(pnode);
if (pnode->nop == knopBlock && !pnode->AsParseNodeBlock()->HasBlockScopedContent())
{
// In order to reduce allocations now that we track debugger scopes in non-debug mode,
// don't add a block to the chain if it has no let/const variables at all.
return nullptr;
}
return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
}
// Records the end of the current scope, but only if the current block has block scoped content.
// Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
{
Assert(pnodeBlock);
if (pnodeBlock->nop == knopBlock && !pnodeBlock->AsParseNodeBlock()->HasBlockScopedContent())
{
return;
}
this->Writer()->RecordEndScopeObject();
}
void BeginEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
{
Js::DebuggerScope* debuggerScope = nullptr;
if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
{
Scope *scope = pnodeBlock->scope;
byteCodeGenerator->PushScope(scope);
Js::RegSlot scopeLocation = scope->GetLocation();
if (scope->GetMustInstantiate())
{
Assert(scopeLocation == Js::Constants::NoRegister);
scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
if (scope->GetIsObject())
{
debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
}
else
{
int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
// TODO: Handle heap enumeration
int scopeSlotCount = scope->GetScopeSlotCount();
byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
}
}
else
{
// In the direct register access case, there is no block scope emitted but we can still track
// the start and end offset of the block. The location registers for let/const variables will still be
// captured along with this range in InitBlockScopedContent().
debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
}
bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
ParseNodePtr pnodeScope;
for (pnodeScope = pnodeBlock->pnodeScopes; pnodeScope;)
{
switch (pnodeScope->nop)
{
case knopFncDecl:
if (pnodeScope->AsParseNodeFnc()->IsDeclaration())
{
// The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
// it be released by DefineOneFunction, because further iterations of this loop can allocate
// temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
// So we'll supply a temp that we allocate and release here.
if (frameDisplayLoc == Js::Constants::NoRegister)
{
if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
{
frameDisplayLoc = funcInfo->frameDisplayRegister;
}
else
{
frameDisplayLoc = funcInfo->GetEnvRegister();
}
tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
}
byteCodeGenerator->DefineOneFunction(pnodeScope->AsParseNodeFnc(), funcInfo, true, frameDisplayLoc);
}
// If this is the global eval block scope, the function is actually assigned to the global
// so we don't need to keep the registers.
if (isGlobalEvalBlockScope)
{
funcInfo->ReleaseLoc(pnodeScope);
pnodeScope->location = Js::Constants::NoRegister;
}
pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
break;
case knopBlock:
pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
break;
case knopCatch:
pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
break;
case knopWith:
pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
break;
}
}
if (tmpInnerEnvReg != Js::Constants::NoRegister)
{
funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
}
}
else
{
Scope *scope = pnodeBlock->scope;
if (scope)
{
if (scope->GetMustInstantiate())
{
debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
}
else
{
debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
}
}
else
{
debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
}
}
byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
}
void EndEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
{
if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
{
Scope *scope = pnodeBlock->scope;
Assert(scope);
Assert(scope == byteCodeGenerator->GetCurrentScope());
byteCodeGenerator->PopScope();
}
byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
}
void CloneEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
{
if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
{
// Only let variables have observable behavior when there are per iteration
// bindings. const variables do not since they are immutable. Therefore,
// (and the spec agrees), only create new scope clones if the loop variable
// is a let declaration.
bool isConst = false;
pnodeBlock->scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
// Exploit the fact that a for loop sxBlock can only have let and const
// declarations, and can only have one or the other, regardless of how
// many syms there might be. Thus only check the first sym.
isConst = sym->GetDecl()->nop == knopConstDecl;
return true;
});
if (!isConst)
{
Scope *scope = pnodeBlock->scope;
Assert(scope == byteCodeGenerator->GetCurrentScope());
if (scope->GetMustInstantiate())
{
Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
}
}
}
}
void EmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
{
Assert(pnodeBlock->nop == knopBlock);
ParseNode *pnode = pnodeBlock->pnodeStmt;
if (pnode == nullptr)
{
return;
}
BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
ParseNode *pnodeLastValStmt = pnodeBlock->pnodeLastValStmt;
while (pnode->nop == knopList)
{
ParseNode* stmt = pnode->AsParseNodeBin()->pnode1;
if (stmt == pnodeLastValStmt)
{
// This is the last guaranteed return value, so any potential return values have to be
// copied to the return register from this point forward.
pnodeLastValStmt = nullptr;
}
byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
pnode = pnode->AsParseNodeBin()->pnode2;
}
if (pnode == pnodeLastValStmt)
{
pnodeLastValStmt = nullptr;
}
byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
}
void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
{
if (emitFunc->IsTmpReg(pnode->location))
{
pnode->location = Js::Constants::NoRegister;
}
}
void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
{
if (stmt->nop == knopFncDecl && stmt->AsParseNodeFnc()->IsDeclaration())
{
// Function declarations (not function-declaration RHS's) are already fully processed.
// Skip them here so the temp registers don't get messed up.
return;
}
if (stmt->nop == knopName || stmt->nop == knopDot)
{
// Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
// But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
// At this time we need to throw proper line number and offset. so recording on all modes will be useful.
StartStatement(stmt);
Writer()->Empty(Js::OpCode::Nop);
EndStatement(stmt);
}
Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, nullptr/*bindPnode*/, true/*isTopLevel*/);
if (funcInfo->IsTmpReg(stmt->location))
{
if (!stmt->isUsed && !fReturnValue)
{
m_writer.Reg1(Js::OpCode::Unused, stmt->location);
}
funcInfo->ReleaseLoc(stmt);
}
}
// ByteCodeGenerator::DefineFunctions
//
// Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
// order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
// to make sure that sources of the stores have been defined.
void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
{
// DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
// we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
if (funcInfoParent->GetHasCachedScope())
{
this->DefineCachedFunctions(funcInfoParent);