-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathFunc.cpp
2246 lines (1961 loc) · 65.7 KB
/
Func.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.
// Copyright (c) 2021 ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "Backend.h"
#include "Base/EtwTrace.h"
#include "Base/ScriptContextProfiler.h"
#ifdef VTUNE_PROFILING
#include "Base/VTuneChakraProfile.h"
#endif
#include "Library/ForInObjectEnumerator.h"
Func::Func(JitArenaAllocator *alloc, JITTimeWorkItem * workItem,
ThreadContextInfo * threadContextInfo,
ScriptContextInfo * scriptContextInfo,
JITOutputIDL * outputData,
Js::EntryPointInfo* epInfo,
const FunctionJITRuntimeInfo *const runtimeInfo,
JITTimePolymorphicInlineCacheInfo * const polymorphicInlineCacheInfo, void * const codeGenAllocators,
#if !FLOATVAR
CodeGenNumberAllocator * numberAllocator,
#endif
Js::ScriptContextProfiler *const codeGenProfiler, const bool isBackgroundJIT, Func * parentFunc,
uint postCallByteCodeOffset, Js::RegSlot returnValueRegSlot, const bool isInlinedConstructor,
Js::ProfileId callSiteIdInParentFunc, bool isGetterSetter) :
m_alloc(alloc),
m_workItem(workItem),
m_output(outputData),
m_entryPointInfo(epInfo),
m_threadContextInfo(threadContextInfo),
m_scriptContextInfo(scriptContextInfo),
m_runtimeInfo(runtimeInfo),
m_polymorphicInlineCacheInfo(polymorphicInlineCacheInfo),
m_codeGenAllocators(codeGenAllocators),
m_inlineeId(0),
pinnedTypeRefs(nullptr),
singleTypeGuards(nullptr),
equivalentTypeGuards(nullptr),
propertyGuardsByPropertyId(nullptr),
ctorCachesByPropertyId(nullptr),
callSiteToArgumentsOffsetFixupMap(nullptr),
indexedPropertyGuardCount(0),
propertiesWrittenTo(nullptr),
lazyBailoutProperties(alloc),
anyPropertyMayBeWrittenTo(false),
#ifdef PROFILE_EXEC
m_codeGenProfiler(codeGenProfiler),
#endif
m_isBackgroundJIT(isBackgroundJIT),
m_cloner(nullptr),
m_cloneMap(nullptr),
m_loopParamSym(nullptr),
m_localClosureSym(nullptr),
m_paramClosureSym(nullptr),
m_localFrameDisplaySym(nullptr),
m_bailoutReturnValueSym(nullptr),
m_hasBailedOutSym(nullptr),
m_inlineeFrameStartSym(nullptr),
inlineeStart(nullptr),
m_regsUsed(0),
m_fg(nullptr),
m_labelCount(0),
m_argSlotsForFunctionsCalled(0),
m_hasCalls(false),
m_hasInlineArgsOpt(false),
m_hasInlineOverheadRemoved(false),
m_canDoInlineArgsOpt(true),
unoptimizableArgumentsObjReference(0),
unoptimizableArgumentsObjReferenceInInlinees(0),
m_doFastPaths(false),
hasBailout(false),
firstIRTemp(0),
hasBailoutInEHRegion(false),
hasInstrNumber(false),
maintainByteCodeOffset(true),
frameSize(0),
topFunc(parentFunc ? parentFunc->topFunc : this),
parentFunc(parentFunc),
argObjSyms(nullptr),
m_nonTempLocalVars(nullptr),
hasAnyStackNestedFunc(false),
hasMarkTempObjects(false),
postCallByteCodeOffset(postCallByteCodeOffset),
maxInlineeArgOutSize(0),
returnValueRegSlot(returnValueRegSlot),
firstActualStackOffset(-1),
m_localVarSlotsOffset(Js::Constants::InvalidOffset),
m_hasLocalVarChangedOffset(Js::Constants::InvalidOffset),
actualCount((Js::ArgSlot) - 1),
tryCatchNestingLevel(0),
m_localStackHeight(0),
tempSymDouble(nullptr),
tempSymBool(nullptr),
hasInlinee(false),
thisOrParentInlinerHasArguments(false),
hasStackArgs(false),
hasArgLenAndConstOpt(false),
hasImplicitParamLoad(false),
hasThrow(false),
hasNonSimpleParams(false),
hasUnoptimizedArgumentsAccess(false),
applyTargetInliningRemovedArgumentsAccess(false),
hasImplicitCalls(false),
hasTempObjectProducingInstr(false),
isInlinedConstructor(isInlinedConstructor),
#if !FLOATVAR
numberAllocator(numberAllocator),
#endif
loopCount(0),
callSiteIdInParentFunc(callSiteIdInParentFunc),
isGetterSetter(isGetterSetter),
cachedInlineeFrameInfo(nullptr),
frameInfo(nullptr),
isTJLoopBody(false),
m_nativeCodeDataSym(nullptr),
isFlowGraphValid(false),
legalizePostRegAlloc(false),
#if DBG
m_callSiteCount(0),
#endif
stackNestedFunc(false),
stackClosure(false)
#if defined(_M_ARM32_OR_ARM64)
, m_ArgumentsOffset(0)
, m_epilogLabel(nullptr)
#endif
, m_funcStartLabel(nullptr)
, m_funcEndLabel(nullptr)
#if DBG
, hasCalledSetDoFastPaths(false)
, allowRemoveBailOutArgInstr(false)
, currentPhases(alloc)
, isPostLower(false)
, isPostRegAlloc(false)
, isPostPeeps(false)
, isPostLayout(false)
, isPostFinalLower(false)
, vtableMap(nullptr)
#endif
, m_yieldOffsetResumeLabelList(nullptr)
, m_bailOutForElidedYieldInsertionPoint(nullptr)
, constantAddressRegOpnd(alloc)
, lastConstantAddressRegLoadInstr(nullptr)
, m_totalJumpTableSizeInBytesForSwitchStatements(0)
, frameDisplayCheckTable(nullptr)
, stackArgWithFormalsTracker(nullptr)
, m_forInLoopBaseDepth(0)
, m_forInEnumeratorArrayOffset(-1)
, argInsCount(0)
, m_globalObjTypeSpecFldInfoArray(nullptr)
, m_generatorFrameSym(nullptr)
#if LOWER_SPLIT_INT64
, m_int64SymPairMap(nullptr)
#endif
#ifdef RECYCLER_WRITE_BARRIER_JIT
, m_lowerer(nullptr)
#endif
, m_lazyBailOutRecordSlot(nullptr)
, hasLazyBailOut(false)
{
Assert(this->IsInlined() == !!runtimeInfo);
AssertOrFailFast(!HasProfileInfo() || GetReadOnlyProfileInfo()->GetLoopCount() == GetJITFunctionBody()->GetLoopCount());
Js::RegSlot tmpResult;
AssertOrFailFast(!UInt32Math::Add(GetJITFunctionBody()->GetConstCount(), GetJITFunctionBody()->GetVarCount(), &tmpResult));
AssertOrFailFast(GetJITFunctionBody()->IsAsmJsMode() || GetJITFunctionBody()->GetFirstTmpReg() <= GetJITFunctionBody()->GetLocalsCount());
AssertOrFailFast(!IsLoopBody() || m_workItem->GetLoopNumber() < GetJITFunctionBody()->GetLoopCount());
AssertOrFailFast(CONFIG_FLAG(Prejit) || CONFIG_ISENABLED(Js::ForceNativeFlag) || GetJITFunctionBody()->GetByteCodeLength() < (uint)CONFIG_FLAG(MaxJITFunctionBytecodeByteLength));
GetJITFunctionBody()->EnsureConsistentConstCount();
if (this->IsTopFunc())
{
outputData->hasJittedStackClosure = false;
outputData->localVarSlotsOffset = m_localVarSlotsOffset;
outputData->localVarChangedOffset = m_hasLocalVarChangedOffset;
}
if (this->IsInlined())
{
m_inlineeId = ++(GetTopFunc()->m_inlineeId);
}
bool doStackNestedFunc = GetJITFunctionBody()->DoStackNestedFunc();
bool doStackClosure = GetJITFunctionBody()->DoStackClosure() && !PHASE_OFF(Js::FrameDisplayFastPathPhase, this) && !PHASE_OFF(Js::StackClosurePhase, this);
Assert(!doStackClosure || doStackNestedFunc);
this->stackClosure = doStackClosure && this->IsTopFunc();
if (this->stackClosure)
{
// TODO: calculate on runtime side?
m_output.SetHasJITStackClosure();
}
if (m_workItem->Type() == JsFunctionType &&
GetJITFunctionBody()->DoBackendArgumentsOptimization() &&
(!GetJITFunctionBody()->HasTry() || this->DoOptimizeTry()))
{
// doBackendArgumentsOptimization bit is set when there is no eval inside a function
// as determined by the bytecode generator.
SetHasStackArgs(true);
}
if (doStackNestedFunc && GetJITFunctionBody()->GetNestedCount() != 0 &&
(this->IsTopFunc() || this->GetTopFunc()->m_workItem->Type() != JsLoopBodyWorkItemType)) // make sure none of the functions inlined in a jitted loop body allocate nested functions on the stack
{
Assert(!(this->IsJitInDebugMode() && !GetJITFunctionBody()->IsLibraryCode()));
stackNestedFunc = true;
this->GetTopFunc()->hasAnyStackNestedFunc = true;
}
if (GetJITFunctionBody()->HasOrParentHasArguments() || (parentFunc && parentFunc->thisOrParentInlinerHasArguments))
{
thisOrParentInlinerHasArguments = true;
}
if (parentFunc == nullptr)
{
inlineDepth = 0;
m_symTable = JitAnew(alloc, SymTable);
m_symTable->Init(this);
m_symTable->SetStartingID(static_cast<SymID>(workItem->GetJITFunctionBody()->GetLocalsCount() + 1));
Assert(Js::Constants::NoByteCodeOffset == postCallByteCodeOffset);
Assert(Js::Constants::NoRegister == returnValueRegSlot);
#if defined(_M_IX86) || defined(_M_X64)
if (HasArgumentSlot())
{
// Pre-allocate the single argument slot we'll reserve for the arguments object.
// For ARM, the argument slot is not part of the local but part of the register saves
m_localStackHeight = MachArgsSlotOffset;
}
#endif
}
else
{
inlineDepth = parentFunc->inlineDepth + 1;
Assert(Js::Constants::NoByteCodeOffset != postCallByteCodeOffset);
}
this->constructorCacheCount = 0;
this->constructorCaches = AnewArrayZ(this->m_alloc, JITTimeConstructorCache*, GetJITFunctionBody()->GetProfiledCallSiteCount());
#if DBG_DUMP
m_codeSize = -1;
#endif
#if defined(_M_X64)
m_spillSize = -1;
m_argsSize = -1;
m_savedRegSize = -1;
#endif
if (this->IsJitInDebugMode())
{
m_nonTempLocalVars = Anew(this->m_alloc, BVSparse<JitArenaAllocator>, this->m_alloc);
}
if (GetJITFunctionBody()->IsCoroutine())
{
m_yieldOffsetResumeLabelList = YieldOffsetResumeLabelList::New(this->m_alloc);
}
if (this->IsTopFunc())
{
m_globalObjTypeSpecFldInfoArray = JitAnewArrayZ(this->m_alloc, ObjTypeSpecFldInfo*, GetWorkItem()->GetJITTimeInfo()->GetGlobalObjTypeSpecFldInfoCount());
}
for (uint i = 0; i < GetJITFunctionBody()->GetInlineCacheCount(); ++i)
{
ObjTypeSpecFldInfo * info = GetWorkItem()->GetJITTimeInfo()->GetObjTypeSpecFldInfo(i);
if (info != nullptr)
{
AssertOrFailFast(info->GetObjTypeSpecFldId() < GetTopFunc()->GetWorkItem()->GetJITTimeInfo()->GetGlobalObjTypeSpecFldInfoCount());
GetTopFunc()->m_globalObjTypeSpecFldInfoArray[info->GetObjTypeSpecFldId()] = info;
}
}
canHoistConstantAddressLoad = !PHASE_OFF(Js::HoistConstAddrPhase, this);
m_forInLoopMaxDepth = this->GetJITFunctionBody()->GetForInLoopDepth();
}
bool
Func::IsLoopBodyInTry() const
{
return IsLoopBody() && m_workItem->GetLoopHeader()->isInTry;
}
bool
Func::IsLoopBodyInTryFinally() const
{
return IsLoopBody() && m_workItem->GetLoopHeader()->isInTryFinally;
}
/* static */
void
Func::Codegen(JitArenaAllocator *alloc, JITTimeWorkItem * workItem,
ThreadContextInfo * threadContextInfo,
ScriptContextInfo * scriptContextInfo,
JITOutputIDL * outputData,
Js::EntryPointInfo* epInfo, // for in-proc jit only
const FunctionJITRuntimeInfo *const runtimeInfo,
JITTimePolymorphicInlineCacheInfo * const polymorphicInlineCacheInfo, void * const codeGenAllocators,
#if !FLOATVAR
CodeGenNumberAllocator * numberAllocator,
#endif
Js::ScriptContextProfiler *const codeGenProfiler, const bool isBackgroundJIT)
{
bool rejit;
int rejitCounter = 0;
do
{
Assert(rejitCounter < 25);
Func func(alloc, workItem, threadContextInfo,
scriptContextInfo, outputData, epInfo, runtimeInfo,
polymorphicInlineCacheInfo, codeGenAllocators,
#if !FLOATVAR
numberAllocator,
#endif
codeGenProfiler, isBackgroundJIT);
try
{
func.TryCodegen();
rejit = false;
}
catch (Js::RejitException ex)
{
// The work item needs to be rejitted, likely due to some optimization that was too aggressive
switch (ex.Reason())
{
case RejitReason::AggressiveIntTypeSpecDisabled:
outputData->disableAggressiveIntTypeSpec = TRUE;
break;
case RejitReason::InlineApplyDisabled:
workItem->GetJITFunctionBody()->DisableInlineApply();
outputData->disableInlineApply = TRUE;
break;
case RejitReason::InlineSpreadDisabled:
workItem->GetJITFunctionBody()->DisableInlineSpread();
outputData->disableInlineSpread = TRUE;
break;
case RejitReason::DisableStackArgOpt:
outputData->disableStackArgOpt = TRUE;
break;
case RejitReason::DisableStackArgLenAndConstOpt:
break;
case RejitReason::DisableSwitchOptExpectingInteger:
case RejitReason::DisableSwitchOptExpectingString:
outputData->disableSwitchOpt = TRUE;
break;
case RejitReason::ArrayCheckHoistDisabled:
case RejitReason::ArrayAccessHelperCallEliminationDisabled:
outputData->disableArrayCheckHoist = TRUE;
break;
case RejitReason::TrackIntOverflowDisabled:
outputData->disableTrackCompoundedIntOverflow = TRUE;
break;
case RejitReason::MemOpDisabled:
outputData->disableMemOp = TRUE;
break;
case RejitReason::FailedEquivalentTypeCheck:
// No disable flag. The thrower of the re-jit exception must guarantee that objtypespec is disabled where appropriate.
break;
default:
Assume(UNREACHED);
}
if (PHASE_TRACE(Js::ReJITPhase, &func))
{
char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
Output::Print(
_u("Rejit (compile-time): function: %s (%s) reason: %S\n"),
workItem->GetJITFunctionBody()->GetDisplayName(),
workItem->GetJITTimeInfo()->GetDebugNumberSet(debugStringBuffer),
ex.ReasonName());
}
rejit = true;
rejitCounter++;
}
// Either the entry point has a reference to the number now, or we failed to code gen and we
// don't need to numbers, we can flush the completed page now.
//
// If the number allocator is NULL then we are shutting down the thread context and so too the
// code generator. The number allocator must be freed before the recycler (and thus before the
// code generator) so we can't and don't need to flush it.
// TODO: OOP JIT, allocator cleanup
} while (rejit);
}
///----------------------------------------------------------------------------
///
/// Func::TryCodegen
///
/// Attempt to Codegen this function.
///
///----------------------------------------------------------------------------
void
Func::TryCodegen()
{
Assert(!IsJitInDebugMode() || !GetJITFunctionBody()->HasTry());
BEGIN_CODEGEN_PHASE(this, Js::BackEndPhase);
{
// IRBuilder
BEGIN_CODEGEN_PHASE(this, Js::IRBuilderPhase);
#ifdef ASMJS_PLAT
if (GetJITFunctionBody()->IsAsmJsMode())
{
IRBuilderAsmJs asmIrBuilder(this);
asmIrBuilder.Build();
}
else
#endif
{
IRBuilder irBuilder(this);
irBuilder.Build();
}
END_CODEGEN_PHASE(this, Js::IRBuilderPhase);
#ifdef IR_VIEWER
IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::IRBuilderPhase);
#endif /* IR_VIEWER */
BEGIN_CODEGEN_PHASE(this, Js::InlinePhase);
InliningHeuristics heuristics(GetWorkItem()->GetJITTimeInfo(), this->IsLoopBody());
Inline inliner(this, heuristics);
inliner.Optimize();
END_CODEGEN_PHASE(this, Js::InlinePhase);
ThrowIfScriptClosed();
// FlowGraph
{
// Scope for FlowGraph arena
NoRecoverMemoryJitArenaAllocator fgAlloc(_u("BE-FlowGraph"), m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
BEGIN_CODEGEN_PHASE(this, Js::FGBuildPhase);
this->m_fg = FlowGraph::New(this, &fgAlloc);
this->m_fg->Build();
END_CODEGEN_PHASE(this, Js::FGBuildPhase);
// Global Optimization and Type Specialization
BEGIN_CODEGEN_PHASE(this, Js::GlobOptPhase);
GlobOpt globOpt(this);
globOpt.Optimize();
END_CODEGEN_PHASE(this, Js::GlobOptPhase);
// Delete flowGraph now
this->m_fg->Destroy();
this->m_fg = nullptr;
}
#ifdef IR_VIEWER
IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::GlobOptPhase);
#endif /* IR_VIEWER */
ThrowIfScriptClosed();
// Lowering
Lowerer lowerer(this);
BEGIN_CODEGEN_PHASE(this, Js::LowererPhase);
lowerer.Lower();
END_CODEGEN_PHASE(this, Js::LowererPhase);
#ifdef IR_VIEWER
IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::LowererPhase);
#endif /* IR_VIEWER */
// Encode constants
Security security(this);
BEGIN_CODEGEN_PHASE(this, Js::EncodeConstantsPhase)
security.EncodeLargeConstants();
END_CODEGEN_PHASE(this, Js::EncodeConstantsPhase);
if (GetJITFunctionBody()->DoInterruptProbe())
{
BEGIN_CODEGEN_PHASE(this, Js::InterruptProbePhase)
lowerer.DoInterruptProbes();
END_CODEGEN_PHASE(this, Js::InterruptProbePhase)
}
// Register Allocation
BEGIN_CODEGEN_PHASE(this, Js::RegAllocPhase);
LinearScan linearScan(this);
linearScan.RegAlloc();
END_CODEGEN_PHASE(this, Js::RegAllocPhase);
#ifdef IR_VIEWER
IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::RegAllocPhase);
#endif /* IR_VIEWER */
ThrowIfScriptClosed();
// Peephole optimizations
BEGIN_CODEGEN_PHASE(this, Js::PeepsPhase);
Peeps peeps(this);
peeps.PeepFunc();
END_CODEGEN_PHASE(this, Js::PeepsPhase);
// Layout
BEGIN_CODEGEN_PHASE(this, Js::LayoutPhase);
SimpleLayout layout(this);
layout.Layout();
END_CODEGEN_PHASE(this, Js::LayoutPhase);
if (this->HasTry() && this->hasBailoutInEHRegion)
{
BEGIN_CODEGEN_PHASE(this, Js::EHBailoutPatchUpPhase);
lowerer.EHBailoutPatchUp();
END_CODEGEN_PHASE(this, Js::EHBailoutPatchUpPhase);
}
// Insert NOPs (moving this before prolog/epilog for AMD64 and possibly ARM).
BEGIN_CODEGEN_PHASE(this, Js::InsertNOPsPhase);
security.InsertNOPs();
END_CODEGEN_PHASE(this, Js::InsertNOPsPhase);
// Prolog/Epilog
BEGIN_CODEGEN_PHASE(this, Js::PrologEpilogPhase);
if (GetJITFunctionBody()->IsAsmJsMode())
{
lowerer.LowerPrologEpilogAsmJs();
}
else
{
lowerer.LowerPrologEpilog();
}
END_CODEGEN_PHASE(this, Js::PrologEpilogPhase);
BEGIN_CODEGEN_PHASE(this, Js::FinalLowerPhase);
lowerer.FinalLower();
END_CODEGEN_PHASE(this, Js::FinalLowerPhase);
// Encoder
BEGIN_CODEGEN_PHASE(this, Js::EncoderPhase);
Encoder encoder(this);
encoder.Encode();
END_CODEGEN_PHASE_NO_DUMP(this, Js::EncoderPhase);
#ifdef IR_VIEWER
IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::EncoderPhase);
#endif /* IR_VIEWER */
}
#if DBG_DUMP
if (Js::Configuration::Global.flags.IsEnabled(Js::AsmDumpModeFlag))
{
FILE * oldFile = 0;
FILE * asmFile = GetScriptContext()->GetNativeCodeGenerator()->asmFile;
if (asmFile)
{
oldFile = Output::SetFile(asmFile);
}
this->Dump(IRDumpFlags_AsmDumpMode);
Output::Flush();
if (asmFile)
{
FILE *openedFile = Output::SetFile(oldFile);
Assert(openedFile == asmFile);
}
}
#endif
if (this->IsOOPJIT())
{
BEGIN_CODEGEN_PHASE(this, Js::NativeCodeDataPhase);
auto dataAllocator = this->GetNativeCodeDataAllocator();
if (dataAllocator->allocCount > 0)
{
NativeCodeData::DataChunk *chunk = (NativeCodeData::DataChunk*)dataAllocator->chunkList;
NativeCodeData::DataChunk *next1 = chunk;
while (next1)
{
if (next1->fixupFunc)
{
next1->fixupFunc(next1->data, chunk);
}
#if DBG
if (CONFIG_FLAG(OOPJITFixupValidate))
{
// Scan memory to see if there's missing pointer needs to be fixed up
// This can hit false positive if some data field happens to have value
// falls into the NativeCodeData memory range.
NativeCodeData::DataChunk *next2 = chunk;
while (next2)
{
for (unsigned int i = 0; i < next1->len / sizeof(void*); i++)
{
if (((void**)next1->data)[i] == (void*)next2->data)
{
NativeCodeData::VerifyExistFixupEntry((void*)next2->data, &((void**)next1->data)[i], next1->data);
}
}
next2 = next2->next;
}
}
#endif
next1 = next1->next;
}
JITOutputIDL* jitOutputData = m_output.GetOutputData();
size_t allocSize = offsetof(NativeDataFixupTable, fixupRecords) + sizeof(NativeDataFixupRecord)* (dataAllocator->allocCount);
jitOutputData->nativeDataFixupTable = (NativeDataFixupTable*)midl_user_allocate(allocSize);
if (!jitOutputData->nativeDataFixupTable)
{
Js::Throw::OutOfMemory();
}
__analysis_assume(jitOutputData->nativeDataFixupTable);
jitOutputData->nativeDataFixupTable->count = dataAllocator->allocCount;
jitOutputData->buffer = (NativeDataBuffer*)midl_user_allocate(offsetof(NativeDataBuffer, data) + dataAllocator->totalSize);
if (!jitOutputData->buffer)
{
Js::Throw::OutOfMemory();
}
__analysis_assume(jitOutputData->buffer);
jitOutputData->buffer->len = dataAllocator->totalSize;
unsigned int len = 0;
unsigned int count = 0;
next1 = chunk;
while (next1)
{
memcpy(jitOutputData->buffer->data + len, next1->data, next1->len);
len += next1->len;
jitOutputData->nativeDataFixupTable->fixupRecords[count].index = next1->allocIndex;
jitOutputData->nativeDataFixupTable->fixupRecords[count].length = next1->len;
jitOutputData->nativeDataFixupTable->fixupRecords[count].startOffset = next1->offset;
jitOutputData->nativeDataFixupTable->fixupRecords[count].updateList = next1->fixupList;
count++;
next1 = next1->next;
}
#if DBG
if (PHASE_TRACE1(Js::NativeCodeDataPhase))
{
Output::Print(_u("NativeCodeData Server Buffer: %p, len: %x, chunk head: %p\n"), jitOutputData->buffer->data, jitOutputData->buffer->len, chunk);
}
#endif
}
END_CODEGEN_PHASE(this, Js::NativeCodeDataPhase);
}
END_CODEGEN_PHASE(this, Js::BackEndPhase);
}
///----------------------------------------------------------------------------
/// Func::StackAllocate
/// Allocate stack space of given size.
///----------------------------------------------------------------------------
int32
Func::StackAllocate(int size)
{
Assert(this->IsTopFunc());
int32 offset;
#ifdef MD_GROW_LOCALS_AREA_UP
// Locals have positive offsets and are allocated from bottom to top.
m_localStackHeight = Math::Align(m_localStackHeight, min(size, MachStackAlignment));
offset = m_localStackHeight;
m_localStackHeight += size;
#else
// Locals have negative offsets and are allocated from top to bottom.
m_localStackHeight += size;
m_localStackHeight = Math::Align(m_localStackHeight, min(size, MachStackAlignment));
offset = -m_localStackHeight;
#endif
return offset;
}
///----------------------------------------------------------------------------
///
/// Func::StackAllocate
///
/// Allocate stack space for this symbol.
///
///----------------------------------------------------------------------------
int32
Func::StackAllocate(StackSym *stackSym, int size)
{
Assert(size > 0);
if (stackSym->IsArgSlotSym() || stackSym->IsParamSlotSym() || stackSym->IsAllocated())
{
return stackSym->m_offset;
}
Assert(stackSym->m_offset == 0);
stackSym->m_allocated = true;
stackSym->m_offset = StackAllocate(size);
return stackSym->m_offset;
}
void
Func::SetArgOffset(StackSym *stackSym, int32 offset)
{
AssertMsg(offset >= 0, "Why is the offset, negative?");
stackSym->m_offset = offset;
stackSym->m_allocated = true;
}
///
/// Ensures that local var slots are created, if the function has locals.
/// Allocate stack space for locals used for debugging
/// (for local non-temp vars we write-through memory so that locals inspection can make use of that.).
// On stack, after local slots we allocate space for metadata (in particular, whether any the locals was changed in debugger).
///
void
Func::EnsureLocalVarSlots()
{
Assert(IsJitInDebugMode());
if (!this->HasLocalVarSlotCreated())
{
uint32 localSlotCount = GetJITFunctionBody()->GetNonTempLocalVarCount();
if (localSlotCount && m_localVarSlotsOffset == Js::Constants::InvalidOffset)
{
// Allocate the slots.
int32 size = localSlotCount * GetDiagLocalSlotSize();
m_localVarSlotsOffset = StackAllocate(size);
m_hasLocalVarChangedOffset = StackAllocate(max(1, MachStackAlignment)); // Can't alloc less than StackAlignment bytes.
Assert(m_workItem->Type() == JsFunctionType);
m_output.SetVarSlotsOffset(AdjustOffsetValue(m_localVarSlotsOffset));
m_output.SetVarChangedOffset(AdjustOffsetValue(m_hasLocalVarChangedOffset));
}
}
}
void Func::SetFirstArgOffset(IR::Instr* inlineeStart)
{
Assert(inlineeStart->m_func == this);
Assert(!IsTopFunc());
int32 lastOffset;
IR::Instr* arg = inlineeStart->GetNextArg();
if (arg)
{
const auto lastArgOutStackSym = arg->GetDst()->AsSymOpnd()->m_sym->AsStackSym();
lastOffset = lastArgOutStackSym->m_offset;
Assert(lastArgOutStackSym->m_isSingleDef);
const auto secondLastArgOutOpnd = lastArgOutStackSym->m_instrDef->GetSrc2();
if (secondLastArgOutOpnd->IsSymOpnd())
{
const auto secondLastOffset = secondLastArgOutOpnd->AsSymOpnd()->m_sym->AsStackSym()->m_offset;
if (secondLastOffset > lastOffset)
{
lastOffset = secondLastOffset;
}
}
lastOffset += MachPtr;
}
else
{
Assert(this->GetTopFunc()->GetJITFunctionBody()->IsAsmJsMode());
lastOffset = MachPtr;
}
int32 firstActualStackOffset = lastOffset - ((this->actualCount + Js::Constants::InlineeMetaArgCount) * MachPtr);
Assert((this->firstActualStackOffset == -1) || (this->firstActualStackOffset == firstActualStackOffset));
this->firstActualStackOffset = firstActualStackOffset;
}
int32
Func::GetLocalVarSlotOffset(int32 slotId)
{
this->EnsureLocalVarSlots();
Assert(m_localVarSlotsOffset != Js::Constants::InvalidOffset);
int32 slotOffset = slotId * GetDiagLocalSlotSize();
return m_localVarSlotsOffset + slotOffset;
}
void Func::OnAddSym(Sym* sym)
{
Assert(sym);
if (this->IsJitInDebugMode() && this->IsNonTempLocalVar(sym->m_id))
{
Assert(m_nonTempLocalVars);
m_nonTempLocalVars->Set(sym->m_id);
}
}
///
/// Returns offset of the flag (1 byte) whether any local was changed (in debugger).
/// If the function does not have any locals, returns -1.
///
int32
Func::GetHasLocalVarChangedOffset()
{
this->EnsureLocalVarSlots();
return m_hasLocalVarChangedOffset;
}
bool
Func::IsJitInDebugMode() const
{
return m_workItem->IsJitInDebugMode();
}
bool
Func::IsNonTempLocalVar(uint32 slotIndex)
{
return GetJITFunctionBody()->IsNonTempLocalVar(slotIndex);
}
int32
Func::AdjustOffsetValue(int32 offset)
{
#ifdef MD_GROW_LOCALS_AREA_UP
return -(offset + BailOutInfo::StackSymBias);
#else
// Stack offset are negative, includes the PUSH EBP and return address
return offset - (2 * MachPtr);
#endif
}
#ifdef MD_GROW_LOCALS_AREA_UP
// Note: this is called during jit-compile when we finalize bail out record.
void
Func::AjustLocalVarSlotOffset()
{
if (GetJITFunctionBody()->GetNonTempLocalVarCount())
{
// Turn positive SP-relative base locals offset into negative frame-pointer-relative offset
// This is changing value for restoring the locals when read due to locals inspection.
int localsOffset = m_localVarSlotsOffset - (m_localStackHeight + m_ArgumentsOffset);
int valueChangeOffset = m_hasLocalVarChangedOffset - (m_localStackHeight + m_ArgumentsOffset);
m_output.SetVarSlotsOffset(localsOffset);
m_output.SetVarChangedOffset(valueChangeOffset);
}
}
#endif
bool
Func::DoSimpleJitDynamicProfile() const
{
return IsSimpleJit() && !PHASE_OFF(Js::SimpleJitDynamicProfilePhase, GetTopFunc()) && !CONFIG_FLAG(NewSimpleJit);
}
void
Func::SetDoFastPaths()
{
// Make sure we only call this once!
Assert(!this->hasCalledSetDoFastPaths);
bool doFastPaths = false;
if(!PHASE_OFF(Js::FastPathPhase, this) && (!IsSimpleJit() || CONFIG_FLAG(NewSimpleJit)))
{
doFastPaths = true;
}
this->m_doFastPaths = doFastPaths;
#ifdef DBG
this->hasCalledSetDoFastPaths = true;
#endif
}
#if LOWER_SPLIT_INT64
Int64RegPair Func::FindOrCreateInt64Pair(IR::Opnd* opnd)
{
if (!this->IsTopFunc())
{
return GetTopFunc()->FindOrCreateInt64Pair(opnd);
}
AssertMsg(currentPhases.Top() == Js::LowererPhase, "New Int64 sym map is only allowed during lower");
Int64RegPair pair;
IRType pairType = opnd->GetType();
if (opnd->IsInt64())
{
pairType = IRType_IsSignedInt(pairType) ? TyInt32 : TyUint32;
}
if (opnd->IsIndirOpnd())
{
IR::IndirOpnd* indir = opnd->AsIndirOpnd();
indir->SetType(pairType);
pair.low = indir;
pair.high = indir->Copy(this)->AsIndirOpnd();
pair.high->AsIndirOpnd()->SetOffset(indir->GetOffset() + 4);
return pair;
}
// Only indir opnd can have a type other than int64
Assert(opnd->IsInt64());
if (opnd->IsImmediateOpnd())
{
int64 value = opnd->GetImmediateValue(this);
pair.low = IR::IntConstOpnd::New((int32)value, pairType, this);
pair.high = IR::IntConstOpnd::New((int32)(value >> 32), pairType, this);
return pair;
}
Int64SymPair symPair;
if (!m_int64SymPairMap)
{
m_int64SymPairMap = Anew(m_alloc, Int64SymPairMap, m_alloc);
}
StackSym* stackSym = opnd->GetStackSym();
AssertOrFailFastMsg(stackSym, "Invalid int64 operand type");
SymID symId = stackSym->m_id;
if (!m_int64SymPairMap->TryGetValue(symId, &symPair))
{
if (stackSym->IsArgSlotSym() || stackSym->IsParamSlotSym())
{
const bool isArg = stackSym->IsArgSlotSym();
if (isArg)
{
Js::ArgSlot slotNumber = stackSym->GetArgSlotNum();
symPair.low = StackSym::NewArgSlotSym(slotNumber, this, pairType);
symPair.high = StackSym::NewArgSlotSym(slotNumber, this, pairType);
}
else
{
Js::ArgSlot slotNumber = stackSym->GetParamSlotNum();
symPair.low = StackSym::NewParamSlotSym(slotNumber, this, pairType);
symPair.high = StackSym::NewParamSlotSym(slotNumber + 1, this, pairType);
}
symPair.low->m_allocated = true;
symPair.low->m_offset = stackSym->m_offset;
symPair.high->m_allocated = true;
symPair.high->m_offset = stackSym->m_offset + 4;
}
else
{
symPair.low = StackSym::New(pairType, this);
symPair.high = StackSym::New(pairType, this);
}
m_int64SymPairMap->Add(symId, symPair);
}
if (opnd->IsSymOpnd())
{
pair.low = IR::SymOpnd::New(symPair.low, opnd->AsSymOpnd()->m_offset, pairType, this);
pair.high = IR::SymOpnd::New(symPair.high, opnd->AsSymOpnd()->m_offset, pairType, this);
}
else
{
pair.low = IR::RegOpnd::New(symPair.low, pairType, this);
pair.high = IR::RegOpnd::New(symPair.high, pairType, this);
}
return pair;
}
void Func::Int64SplitExtendLoopLifetime(Loop* loop)
{
if (!this->IsTopFunc())
{
GetTopFunc()->Int64SplitExtendLoopLifetime(loop);
return;
}
if (m_int64SymPairMap)
{
BVSparse<JitArenaAllocator> *liveOnBackEdgeSyms = loop->regAlloc.liveOnBackEdgeSyms;
FOREACH_BITSET_IN_SPARSEBV(symId, liveOnBackEdgeSyms)
{
Int64SymPair pair;
if (m_int64SymPairMap->TryGetValue(symId, &pair))