forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjectalloc.cpp
3201 lines (2815 loc) · 116 KB
/
objectalloc.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX ObjectAllocator XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "gentree.h"
#include "jitstd/algorithm.h"
//------------------------------------------------------------------------
// DoPhase: Run analysis (if object stack allocation is enabled) and then
// morph each GT_ALLOCOBJ node either into an allocation helper
// call or stack allocation.
//
// Returns:
// PhaseStatus indicating, what, if anything, was modified
//
// Notes:
// Runs only if Compiler::optMethodFlags has flag OMF_HAS_NEWOBJ set.
//
PhaseStatus ObjectAllocator::DoPhase()
{
if ((comp->optMethodFlags & OMF_HAS_NEWOBJ) == 0 && (comp->optMethodFlags & OMF_HAS_NEWARRAY) == 0)
{
JITDUMP("no newobjs or newarr in this method; punting\n");
comp->fgInvalidateDfsTree();
return PhaseStatus::MODIFIED_NOTHING;
}
// If optimizations are disabled and there are no newobjs, we don't need to morph anything.
if (comp->opts.OptimizationDisabled() && (comp->optMethodFlags & OMF_HAS_NEWOBJ) == 0)
{
JITDUMP("optimizations are disabled and there are no newobjs; punting\n");
comp->fgInvalidateDfsTree();
return PhaseStatus::MODIFIED_NOTHING;
}
bool enabled = IsObjectStackAllocationEnabled();
const char* disableReason = ": global config";
#ifdef DEBUG
// Allow disabling based on method hash
//
if (enabled)
{
static ConfigMethodRange JitObjectStackAllocationRange;
JitObjectStackAllocationRange.EnsureInit(JitConfig.JitObjectStackAllocationRange());
const unsigned hash = comp->info.compMethodHash();
enabled &= JitObjectStackAllocationRange.Contains(hash);
disableReason = ": range config";
}
#endif
if (enabled)
{
JITDUMP("enabled, analyzing...\n");
DoAnalysis();
// If we have to clone some code to guarantee non-escape, do it now.
//
CloneAndSpecialize();
}
else
{
JITDUMP("disabled%s, punting\n", IsObjectStackAllocationEnabled() ? disableReason : "");
m_IsObjectStackAllocationEnabled = false;
}
const bool didStackAllocate = MorphAllocObjNodes();
if (didStackAllocate)
{
assert(enabled);
ComputeStackObjectPointers(&m_bitVecTraits);
RewriteUses();
}
// This phase always changes the IR. It may also modify the flow graph.
//
comp->fgInvalidateDfsTree();
return PhaseStatus::MODIFIED_EVERYTHING;
}
//------------------------------------------------------------------------------
// MarkLclVarAsEscaping : Mark local variable as escaping.
//
//
// Arguments:
// lclNum - Escaping pointing local variable number
void ObjectAllocator::MarkLclVarAsEscaping(unsigned int lclNum)
{
BitVecOps::AddElemD(&m_bitVecTraits, m_EscapingPointers, lclNum);
}
//------------------------------------------------------------------------------
// MarkLclVarAsPossiblyStackPointing : Mark local variable as possibly pointing
// to a stack-allocated object.
//
//
// Arguments:
// lclNum - Possibly stack-object-pointing local variable number
void ObjectAllocator::MarkLclVarAsPossiblyStackPointing(unsigned int lclNum)
{
BitVecOps::AddElemD(&m_bitVecTraits, m_PossiblyStackPointingPointers, lclNum);
}
//------------------------------------------------------------------------------
// MarkLclVarAsDefinitelyStackPointing : Mark local variable as definitely pointing
// to a stack-allocated object.
//
//
// Arguments:
// lclNum - Definitely stack-object-pointing local variable number
void ObjectAllocator::MarkLclVarAsDefinitelyStackPointing(unsigned int lclNum)
{
BitVecOps::AddElemD(&m_bitVecTraits, m_DefinitelyStackPointingPointers, lclNum);
}
//------------------------------------------------------------------------------
// AddConnGraphEdge : Record that the source local variable may point to the same set of objects
// as the set pointed to by target local variable.
//
// Arguments:
// sourceLclNum - Local variable number of the edge source
// targetLclNum - Local variable number of the edge target
void ObjectAllocator::AddConnGraphEdge(unsigned int sourceLclNum, unsigned int targetLclNum)
{
BitVecOps::AddElemD(&m_bitVecTraits, m_ConnGraphAdjacencyMatrix[sourceLclNum], targetLclNum);
}
//------------------------------------------------------------------------
// DoAnalysis: Walk over basic blocks of the method and detect all local
// variables that can be allocated on the stack.
void ObjectAllocator::DoAnalysis()
{
assert(m_IsObjectStackAllocationEnabled);
assert(!m_AnalysisDone);
if (comp->lvaCount > 0)
{
m_EscapingPointers = BitVecOps::MakeEmpty(&m_bitVecTraits);
m_ConnGraphAdjacencyMatrix =
new (comp->getAllocator(CMK_ObjectAllocator)) BitSetShortLongRep[comp->lvaCount + m_maxPseudoLocals + 1];
// If we are doing conditional escape analysis, we also need to compute dominance.
//
if (CanHavePseudoLocals())
{
assert(comp->m_dfsTree != nullptr);
assert(comp->m_domTree == nullptr);
comp->m_domTree = FlowGraphDominatorTree::Build(comp->m_dfsTree);
}
MarkEscapingVarsAndBuildConnGraph();
ComputeEscapingNodes(&m_bitVecTraits, m_EscapingPointers);
}
m_AnalysisDone = true;
}
//------------------------------------------------------------------------------
// MarkEscapingVarsAndBuildConnGraph : Walk the trees of the method and mark any ref/byref/i_impl
// local variables that may escape. Build a connection graph
// for ref/by_ref/i_impl local variables.
//
// Arguments:
// sourceLclNum - Local variable number of the edge source
// targetLclNum - Local variable number of the edge target
//
// Notes:
// The connection graph has an edge from local variable s to local variable t if s may point
// to the objects t points to at some point in the method. It's a simplified version
// of the graph described in this paper:
// https://www.cc.gatech.edu/~harrold/6340/cs6340_fall2009/Readings/choi99escape.pdf
// We currently don't have field edges and the edges we do have are called "deferred" in the paper.
void ObjectAllocator::MarkEscapingVarsAndBuildConnGraph()
{
class BuildConnGraphVisitor final : public GenTreeVisitor<BuildConnGraphVisitor>
{
ObjectAllocator* m_allocator;
BasicBlock* m_block;
Statement* m_stmt;
public:
enum
{
DoPreOrder = true,
DoLclVarsOnly = true,
ComputeStack = true,
};
BuildConnGraphVisitor(ObjectAllocator* allocator, BasicBlock* block, Statement* stmt)
: GenTreeVisitor<BuildConnGraphVisitor>(allocator->comp)
, m_allocator(allocator)
, m_block(block)
, m_stmt(stmt)
{
}
Compiler::fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
{
GenTree* const tree = *use;
unsigned const lclNum = tree->AsLclVarCommon()->GetLclNum();
// If this local already escapes, no need to look further.
//
if (m_allocator->CanLclVarEscape(lclNum))
{
return Compiler::fgWalkResult::WALK_CONTINUE;
}
bool lclEscapes = true;
if (tree->OperIsLocalStore())
{
lclEscapes = false;
m_allocator->CheckForGuardedAllocationOrCopy(m_block, m_stmt, use, lclNum);
}
else if (tree->OperIs(GT_LCL_VAR) && tree->TypeIs(TYP_REF, TYP_BYREF, TYP_I_IMPL))
{
assert(tree == m_ancestors.Top());
if (!m_allocator->CanLclVarEscapeViaParentStack(&m_ancestors, lclNum, m_block))
{
lclEscapes = false;
}
}
if (lclEscapes)
{
if (!m_allocator->CanLclVarEscape(lclNum))
{
JITDUMP("V%02u first escapes via [%06u]\n", lclNum, m_compiler->dspTreeID(tree));
}
m_allocator->MarkLclVarAsEscaping(lclNum);
}
else if (!tree->OperIsLocalStore())
{
// Note uses of variables of interest to conditional escape analysis.
//
m_allocator->RecordAppearance(lclNum, m_block, m_stmt, use);
}
return Compiler::fgWalkResult::WALK_CONTINUE;
}
};
for (unsigned int lclNum = 0; lclNum < comp->lvaCount; ++lclNum)
{
var_types type = comp->lvaTable[lclNum].TypeGet();
if (type == TYP_REF || genActualType(type) == TYP_I_IMPL || type == TYP_BYREF)
{
m_ConnGraphAdjacencyMatrix[lclNum] = BitVecOps::MakeEmpty(&m_bitVecTraits);
if (comp->lvaTable[lclNum].IsAddressExposed())
{
JITDUMP(" V%02u is address exposed\n", lclNum);
MarkLclVarAsEscaping(lclNum);
}
}
else
{
// Variable that may not point to objects will not participate in our analysis.
m_ConnGraphAdjacencyMatrix[lclNum] = BitVecOps::UninitVal();
}
}
for (unsigned int p = 0; p < m_maxPseudoLocals; p++)
{
m_ConnGraphAdjacencyMatrix[p + comp->lvaCount] = BitVecOps::MakeEmpty(&m_bitVecTraits);
}
// We should have computed the DFS tree already.
//
FlowGraphDfsTree* const dfs = comp->m_dfsTree;
assert(dfs != nullptr);
// Walk in RPO
//
for (unsigned i = dfs->GetPostOrderCount(); i != 0; i--)
{
BasicBlock* const block = dfs->GetPostOrder(i - 1);
for (Statement* const stmt : block->Statements())
{
BuildConnGraphVisitor buildConnGraphVisitor(this, block, stmt);
buildConnGraphVisitor.WalkTree(stmt->GetRootNodePointer(), nullptr);
}
}
}
//------------------------------------------------------------------------------
// ComputeEscapingNodes : Given an initial set of escaping nodes, update it to contain the full set
// of escaping nodes by computing nodes reachable from the given set.
//
// Arguments:
// bitVecTraits - Bit vector traits
// escapingNodes [in/out] - Initial set of escaping nodes
void ObjectAllocator::ComputeEscapingNodes(BitVecTraits* bitVecTraits, BitVec& escapingNodes)
{
BitVec escapingNodesToProcess = BitVecOps::MakeCopy(bitVecTraits, escapingNodes);
auto computeClosure = [&]() {
JITDUMP("\nComputing escape closure\n\n");
bool doOneMoreIteration = true;
BitSetShortLongRep newEscapingNodes = BitVecOps::UninitVal();
unsigned int lclNum;
while (doOneMoreIteration)
{
BitVecOps::Iter iterator(bitVecTraits, escapingNodesToProcess);
doOneMoreIteration = false;
while (iterator.NextElem(&lclNum))
{
if (m_ConnGraphAdjacencyMatrix[lclNum] != nullptr)
{
doOneMoreIteration = true;
// newEscapingNodes = adjacentNodes[lclNum]
BitVecOps::Assign(bitVecTraits, newEscapingNodes, m_ConnGraphAdjacencyMatrix[lclNum]);
// newEscapingNodes = newEscapingNodes \ escapingNodes
BitVecOps::DiffD(bitVecTraits, newEscapingNodes, escapingNodes);
// escapingNodesToProcess = escapingNodesToProcess U newEscapingNodes
BitVecOps::UnionD(bitVecTraits, escapingNodesToProcess, newEscapingNodes);
// escapingNodes = escapingNodes U newEscapingNodes
BitVecOps::UnionD(bitVecTraits, escapingNodes, newEscapingNodes);
// escapingNodesToProcess = escapingNodesToProcess \ { lclNum }
BitVecOps::RemoveElemD(bitVecTraits, escapingNodesToProcess, lclNum);
#ifdef DEBUG
// Print the first witness to new escapes.
//
if (!BitVecOps::IsEmpty(bitVecTraits, newEscapingNodes))
{
BitVecOps::Iter iterator(bitVecTraits, newEscapingNodes);
unsigned int newLclNum;
while (iterator.NextElem(&newLclNum))
{
// Note P's never are sources of assignments...
JITDUMP("%c%02u causes V%02u to escape\n", lclNum >= comp->lvaCount ? 'P' : 'V', lclNum,
newLclNum);
}
}
#endif
}
}
}
};
computeClosure();
if (m_numPseudoLocals > 0)
{
bool newEscapes = AnalyzeIfCloningCanPreventEscape(bitVecTraits, escapingNodes, escapingNodesToProcess);
if (newEscapes)
{
computeClosure();
}
}
}
//------------------------------------------------------------------------------
// ComputeStackObjectPointers : Given an initial set of possibly stack-pointing nodes,
// and an initial set of definitely stack-pointing nodes,
// update both sets by computing nodes reachable from the
// given set in the reverse connection graph.
//
// Arguments:
// bitVecTraits - Bit vector traits
void ObjectAllocator::ComputeStackObjectPointers(BitVecTraits* bitVecTraits)
{
bool changed = true;
while (changed)
{
changed = false;
for (unsigned int lclNum = 0; lclNum < comp->lvaCount; ++lclNum)
{
LclVarDsc* lclVarDsc = comp->lvaGetDesc(lclNum);
var_types type = lclVarDsc->TypeGet();
if (type == TYP_REF || type == TYP_I_IMPL || type == TYP_BYREF)
{
if (!MayLclVarPointToStack(lclNum) &&
!BitVecOps::IsEmptyIntersection(bitVecTraits, m_PossiblyStackPointingPointers,
m_ConnGraphAdjacencyMatrix[lclNum]))
{
// We discovered a new pointer that may point to the stack.
MarkLclVarAsPossiblyStackPointing(lclNum);
// Check if this pointer always points to the stack.
// For OSR the reference may be pointing at the heap-allocated Tier0 version.
//
if ((lclVarDsc->lvSingleDef == 1) && !comp->opts.IsOSR())
{
// Check if we know what is assigned to this pointer.
unsigned bitCount = BitVecOps::Count(bitVecTraits, m_ConnGraphAdjacencyMatrix[lclNum]);
assert(bitCount <= 1);
if (bitCount == 1)
{
BitVecOps::Iter iter(bitVecTraits, m_ConnGraphAdjacencyMatrix[lclNum]);
unsigned rhsLclNum = 0;
iter.NextElem(&rhsLclNum);
if (DoesLclVarPointToStack(rhsLclNum))
{
// The only store to lclNum local is the definitely-stack-pointing
// rhsLclNum local so lclNum local is also definitely-stack-pointing.
MarkLclVarAsDefinitelyStackPointing(lclNum);
}
}
}
changed = true;
}
}
}
}
JITDUMP("Definitely stack-pointing locals:");
{
BitVecOps::Iter iter(bitVecTraits, m_DefinitelyStackPointingPointers);
unsigned lclNum = 0;
while (iter.NextElem(&lclNum))
{
JITDUMP(" V%02u", lclNum);
}
JITDUMP("\n");
}
JITDUMP("Possibly stack-pointing locals:");
{
BitVecOps::Iter iter(bitVecTraits, m_PossiblyStackPointingPointers);
unsigned lclNum = 0;
while (iter.NextElem(&lclNum))
{
if (!BitVecOps::IsMember(bitVecTraits, m_DefinitelyStackPointingPointers, lclNum))
{
JITDUMP(" V%02u", lclNum);
}
}
JITDUMP("\n");
}
}
//------------------------------------------------------------------------
// MorphAllocObjNodes: Morph each GT_ALLOCOBJ node either into an
// allocation helper call or stack allocation.
//
// Returns:
// true if any allocation was done as a stack allocation.
//
// Notes:
// Runs only over the blocks having bbFlags BBF_HAS_NEWOBJ set.
bool ObjectAllocator::MorphAllocObjNodes()
{
bool didStackAllocate = false;
m_PossiblyStackPointingPointers = BitVecOps::MakeEmpty(&m_bitVecTraits);
m_DefinitelyStackPointingPointers = BitVecOps::MakeEmpty(&m_bitVecTraits);
const bool isReadyToRun = comp->opts.IsReadyToRun() && !comp->IsTargetAbi(CORINFO_NATIVEAOT_ABI);
for (BasicBlock* const block : comp->Blocks())
{
const bool basicBlockHasNewObj = block->HasFlag(BBF_HAS_NEWOBJ);
const bool basicBlockHasNewArr = block->HasFlag(BBF_HAS_NEWARR);
const bool basicBlockHasBackwardJump = block->HasFlag(BBF_BACKWARD_JUMP);
if (!basicBlockHasNewObj && !basicBlockHasNewArr)
{
continue;
}
for (Statement* const stmt : block->Statements())
{
GenTree* stmtExpr = stmt->GetRootNode();
GenTree* data = nullptr;
ObjectAllocationType allocType = OAT_NONE;
if (stmtExpr->OperIs(GT_STORE_LCL_VAR) && stmtExpr->TypeIs(TYP_REF))
{
data = stmtExpr->AsLclVar()->Data();
if (data->OperGet() == GT_ALLOCOBJ)
{
allocType = OAT_NEWOBJ;
}
else if (!isReadyToRun && data->IsHelperCall())
{
switch (data->AsCall()->GetHelperNum())
{
case CORINFO_HELP_NEWARR_1_VC:
case CORINFO_HELP_NEWARR_1_OBJ:
case CORINFO_HELP_NEWARR_1_DIRECT:
case CORINFO_HELP_NEWARR_1_ALIGN8:
{
if ((data->AsCall()->gtArgs.CountUserArgs() == 2) &&
data->AsCall()->gtArgs.GetUserArgByIndex(1)->GetNode()->IsCnsIntOrI())
{
allocType = OAT_NEWARR;
}
break;
}
default:
{
break;
}
}
}
}
if (allocType != OAT_NONE)
{
bool canStack = false;
bool bashCall = false;
const char* onHeapReason = nullptr;
unsigned int lclNum = stmtExpr->AsLclVar()->GetLclNum();
// Don't attempt to do stack allocations inside basic blocks that may be in a loop.
//
if (!IsObjectStackAllocationEnabled())
{
onHeapReason = "[object stack allocation disabled]";
canStack = false;
}
else if (basicBlockHasBackwardJump)
{
onHeapReason = "[alloc in loop]";
canStack = false;
}
else
{
if (allocType == OAT_NEWARR)
{
assert(basicBlockHasNewArr);
// R2R not yet supported
//
assert(!isReadyToRun);
//------------------------------------------------------------------------
// We expect the following expression tree at this point
// For non-ReadyToRun:
// STMTx (IL 0x... ???)
// * STORE_LCL_VAR ref
// \--* CALL help ref
// +--* CNS_INT(h) long
// \--* CNS_INT long
// For ReadyToRun:
// STMTx (IL 0x... ???)
// * STORE_LCL_VAR ref
// \--* CALL help ref
// \--* CNS_INT long
//------------------------------------------------------------------------
bool isExact = false;
bool isNonNull = false;
CORINFO_CLASS_HANDLE clsHnd =
comp->gtGetHelperCallClassHandle(data->AsCall(), &isExact, &isNonNull);
GenTree* const len = data->AsCall()->gtArgs.GetUserArgByIndex(1)->GetNode();
assert(len != nullptr);
unsigned int blockSize = 0;
comp->Metrics.NewArrayHelperCalls++;
if (!isExact || !isNonNull)
{
onHeapReason = "[array type is either non-exact or null]";
canStack = false;
}
else if (!len->IsCnsIntOrI())
{
onHeapReason = "[non-constant size]";
canStack = false;
}
else if (!CanAllocateLclVarOnStack(lclNum, clsHnd, allocType, len->AsIntCon()->IconValue(),
&blockSize, &onHeapReason))
{
// reason set by the call
canStack = false;
}
else
{
JITDUMP("Allocating V%02u on the stack\n", lclNum);
canStack = true;
const unsigned int stackLclNum =
MorphNewArrNodeIntoStackAlloc(data->AsCall(), clsHnd,
(unsigned int)len->AsIntCon()->IconValue(), blockSize,
block, stmt);
// Note we do not want to rewrite uses of the array temp, so we
// do not update m_HeapLocalToStackLocalMap.
//
comp->Metrics.StackAllocatedArrays++;
}
}
else if (allocType == OAT_NEWOBJ)
{
assert(basicBlockHasNewObj);
//------------------------------------------------------------------------
// We expect the following expression tree at this point
// STMTx (IL 0x... ???)
// * STORE_LCL_VAR ref
// \--* ALLOCOBJ ref
// \--* CNS_INT(h) long
//------------------------------------------------------------------------
CORINFO_CLASS_HANDLE clsHnd = data->AsAllocObj()->gtAllocObjClsHnd;
CORINFO_CLASS_HANDLE stackClsHnd = clsHnd;
const bool isValueClass = comp->info.compCompHnd->isValueClass(clsHnd);
if (isValueClass)
{
comp->Metrics.NewBoxedValueClassHelperCalls++;
stackClsHnd = comp->info.compCompHnd->getTypeForBoxOnStack(clsHnd);
}
else
{
comp->Metrics.NewRefClassHelperCalls++;
}
if (!CanAllocateLclVarOnStack(lclNum, clsHnd, allocType, 0, nullptr, &onHeapReason))
{
// reason set by the call
canStack = false;
}
else if (stackClsHnd == NO_CLASS_HANDLE)
{
assert(isValueClass);
onHeapReason = "[no class handle for this boxed value class]";
canStack = false;
}
else
{
JITDUMP("Allocating V%02u on the stack\n", lclNum);
canStack = true;
const unsigned int stackLclNum =
MorphAllocObjNodeIntoStackAlloc(data->AsAllocObj(), stackClsHnd, isValueClass, block,
stmt);
m_HeapLocalToStackLocalMap.AddOrUpdate(lclNum, stackLclNum);
if (isValueClass)
{
comp->Metrics.StackAllocatedBoxedValueClasses++;
}
else
{
comp->Metrics.StackAllocatedRefClasses++;
}
bashCall = true;
}
}
}
if (canStack)
{
// We keep the set of possibly-stack-pointing pointers as a superset of the set of
// definitely-stack-pointing pointers. All definitely-stack-pointing pointers are in both
// sets.
MarkLclVarAsDefinitelyStackPointing(lclNum);
MarkLclVarAsPossiblyStackPointing(lclNum);
// If this was conditionally escaping enumerator, establish a connection between this local
// and the enumeratorLocal we already allocated. This is needed because we do early rewriting
// in the conditional clone.
//
unsigned pseudoLocal = BAD_VAR_NUM;
if (m_EnumeratorLocalToPseudoLocalMap.TryGetValue(lclNum, &pseudoLocal))
{
CloneInfo* info = nullptr;
if (m_CloneMap.Lookup(pseudoLocal, &info))
{
if (info->m_willClone)
{
JITDUMP("Connecting stack allocated enumerator V%02u to its address var V%02u\n",
lclNum, info->m_enumeratorLocal);
AddConnGraphEdge(lclNum, info->m_enumeratorLocal);
MarkLclVarAsPossiblyStackPointing(info->m_enumeratorLocal);
MarkLclVarAsDefinitelyStackPointing(info->m_enumeratorLocal);
}
}
}
if (bashCall)
{
stmt->GetRootNode()->gtBashToNOP();
}
comp->optMethodFlags |= OMF_HAS_OBJSTACKALLOC;
didStackAllocate = true;
}
else
{
assert(onHeapReason != nullptr);
JITDUMP("Allocating V%02u on the heap: %s\n", lclNum, onHeapReason);
if (allocType == OAT_NEWOBJ)
{
data = MorphAllocObjNodeIntoHelperCall(data->AsAllocObj());
stmtExpr->AsLclVar()->Data() = data;
stmtExpr->AddAllEffectsFlags(data);
}
}
}
#ifdef DEBUG
else
{
// We assume that GT_ALLOCOBJ nodes are always present in the canonical form.
assert(!comp->gtTreeContainsOper(stmt->GetRootNode(), GT_ALLOCOBJ));
}
#endif // DEBUG
}
}
return didStackAllocate;
}
//------------------------------------------------------------------------
// MorphAllocObjNodeIntoHelperCall: Morph a GT_ALLOCOBJ node into an
// allocation helper call.
//
// Arguments:
// allocObj - GT_ALLOCOBJ that will be replaced by helper call.
//
// Return Value:
// Address of helper call node (can be the same as allocObj).
//
// Notes:
// Must update parents flags after this.
GenTree* ObjectAllocator::MorphAllocObjNodeIntoHelperCall(GenTreeAllocObj* allocObj)
{
assert(allocObj != nullptr);
GenTree* arg = allocObj->gtGetOp1();
unsigned int helper = allocObj->gtNewHelper;
bool helperHasSideEffects = allocObj->gtHelperHasSideEffects;
#ifdef FEATURE_READYTORUN
CORINFO_CONST_LOOKUP entryPoint = allocObj->gtEntryPoint;
if (helper == CORINFO_HELP_READYTORUN_NEW)
{
arg = nullptr;
}
#endif
const bool morphArgs = false;
GenTree* helperCall = comp->fgMorphIntoHelperCall(allocObj, allocObj->gtNewHelper, morphArgs, arg);
if (helperHasSideEffects)
{
helperCall->AsCall()->gtCallMoreFlags |= GTF_CALL_M_ALLOC_SIDE_EFFECTS;
}
#ifdef FEATURE_READYTORUN
if (entryPoint.addr != nullptr)
{
assert(comp->opts.IsReadyToRun());
helperCall->AsCall()->setEntryPoint(entryPoint);
}
else
{
assert(helper != CORINFO_HELP_READYTORUN_NEW); // If this is true, then we should have collected a non-null
// entrypoint above
}
#endif
return helperCall;
}
//------------------------------------------------------------------------
// MorphNewArrNodeIntoStackAlloc: Morph a newarray helper call node into stack allocation.
//
// Arguments:
// newArr - GT_CALL that will be replaced by helper call.
// clsHnd - class representing the type of the array
// length - length of the array
// blockSize - size of the layout
// block - a basic block where newArr is
// stmt - a statement where newArr is
//
// Return Value:
// local num for the new stack allocated local
//
// Notes:
// This function can insert additional statements before stmt.
//
unsigned int ObjectAllocator::MorphNewArrNodeIntoStackAlloc(GenTreeCall* newArr,
CORINFO_CLASS_HANDLE clsHnd,
unsigned int length,
unsigned int blockSize,
BasicBlock* block,
Statement* stmt)
{
assert(newArr != nullptr);
assert(m_AnalysisDone);
assert(clsHnd != NO_CLASS_HANDLE);
assert(newArr->IsHelperCall());
assert(newArr->GetHelperNum() != CORINFO_HELP_NEWARR_1_MAYBEFROZEN);
const bool shortLifetime = false;
const bool alignTo8 = newArr->GetHelperNum() == CORINFO_HELP_NEWARR_1_ALIGN8;
const unsigned int lclNum = comp->lvaGrabTemp(shortLifetime DEBUGARG("stack allocated array temp"));
LclVarDsc* const lclDsc = comp->lvaGetDesc(lclNum);
if (alignTo8)
{
blockSize = AlignUp(blockSize, 8);
}
comp->lvaSetStruct(lclNum, comp->typGetArrayLayout(clsHnd, length), /* unsafe */ false);
lclDsc->lvStackAllocatedObject = true;
// Initialize the object memory if necessary.
bool bbInALoop = block->HasFlag(BBF_BACKWARD_JUMP);
bool bbIsReturn = block->KindIs(BBJ_RETURN);
if (comp->fgVarNeedsExplicitZeroInit(lclNum, bbInALoop, bbIsReturn))
{
//------------------------------------------------------------------------
// STMTx (IL 0x... ???)
// * STORE_LCL_VAR struct
// \--* CNS_INT int 0
//------------------------------------------------------------------------
GenTree* init = comp->gtNewStoreLclVarNode(lclNum, comp->gtNewIconNode(0));
Statement* initStmt = comp->gtNewStmt(init);
comp->fgInsertStmtBefore(block, stmt, initStmt);
}
else
{
JITDUMP("\nSuppressing zero-init for V%02u -- expect to zero in prolog\n", lclNum);
lclDsc->lvSuppressedZeroInit = 1;
comp->compSuppressedZeroInit = true;
}
#ifndef TARGET_64BIT
lclDsc->lvStructDoubleAlign = alignTo8;
#endif
// Mark the newarr call as being "on stack", and add the address
// of the stack local as an argument
//
GenTree* const stackLocalAddr = comp->gtNewLclAddrNode(lclNum, 0);
newArr->gtArgs.PushBack(comp, NewCallArg::Primitive(stackLocalAddr).WellKnown(WellKnownArg::StackArrayLocal));
newArr->gtCallMoreFlags |= GTF_CALL_M_STACK_ARRAY;
// Retype the call result as an unmanaged pointer
//
newArr->ChangeType(TYP_I_IMPL);
newArr->gtReturnType = TYP_I_IMPL;
// Note that we have stack allocated arrays in this method
//
comp->setMethodHasStackAllocatedArray();
return lclNum;
}
//------------------------------------------------------------------------
// MorphAllocObjNodeIntoStackAlloc: Morph a GT_ALLOCOBJ node into stack
// allocation.
// Arguments:
// allocObj - GT_ALLOCOBJ that will be replaced by a stack allocation
// clsHnd - class representing the stack allocated object
// isValueClass - we are stack allocating a boxed value class
// block - a basic block where allocObj is
// stmt - a statement where allocObj is
//
// Return Value:
// local num for the new stack allocated local
//
// Notes:
// This function can insert additional statements before stmt.
//
unsigned int ObjectAllocator::MorphAllocObjNodeIntoStackAlloc(
GenTreeAllocObj* allocObj, CORINFO_CLASS_HANDLE clsHnd, bool isValueClass, BasicBlock* block, Statement* stmt)
{
assert(allocObj != nullptr);
assert(m_AnalysisDone);
assert(clsHnd != NO_CLASS_HANDLE);
const bool shortLifetime = false;
const unsigned int lclNum = comp->lvaGrabTemp(shortLifetime DEBUGARG(
isValueClass ? "stack allocated boxed value class temp" : "stack allocated ref class temp"));
comp->lvaSetStruct(lclNum, clsHnd, /* unsafeValueClsCheck */ false);
// Initialize the object memory if necessary.
bool bbInALoop = block->HasFlag(BBF_BACKWARD_JUMP);
bool bbIsReturn = block->KindIs(BBJ_RETURN);
LclVarDsc* const lclDsc = comp->lvaGetDesc(lclNum);
lclDsc->lvStackAllocatedObject = true;
if (comp->fgVarNeedsExplicitZeroInit(lclNum, bbInALoop, bbIsReturn))
{
//------------------------------------------------------------------------
// STMTx (IL 0x... ???)
// * STORE_LCL_VAR struct
// \--* CNS_INT int 0
//------------------------------------------------------------------------
GenTree* init = comp->gtNewStoreLclVarNode(lclNum, comp->gtNewIconNode(0));
Statement* initStmt = comp->gtNewStmt(init);
comp->fgInsertStmtBefore(block, stmt, initStmt);
}
else
{
JITDUMP("\nSuppressing zero-init for V%02u -- expect to zero in prolog\n", lclNum);
lclDsc->lvSuppressedZeroInit = 1;
comp->compSuppressedZeroInit = true;
}
// Initialize the vtable slot.
//
//------------------------------------------------------------------------
// STMTx (IL 0x... ???)
// * STORE_LCL_FLD long
// \--* CNS_INT(h) long
//------------------------------------------------------------------------
// Initialize the method table pointer.
GenTree* init = comp->gtNewStoreLclFldNode(lclNum, TYP_I_IMPL, 0, allocObj->gtGetOp1());
Statement* initStmt = comp->gtNewStmt(init);
comp->fgInsertStmtBefore(block, stmt, initStmt);
// If this allocation is part the special empty static pattern, find the controlling
// branch and force control to always flow to the new instance side.
//
if ((allocObj->gtFlags & GTF_ALLOCOBJ_EMPTY_STATIC) != 0)
{
BasicBlock* const predBlock = block->GetUniquePred(comp);
assert(predBlock != nullptr);
assert(predBlock->KindIs(BBJ_COND));
JITDUMP("Empty static pattern controlled by " FMT_BB ", optimizing to always use stack allocated instance\n",
predBlock->bbNum);
Statement* const controllingStmt = predBlock->lastStmt();
GenTree* const controllingNode = controllingStmt->GetRootNode();
assert(controllingNode->OperIs(GT_JTRUE));
FlowEdge* const trueEdge = predBlock->GetTrueEdge();
FlowEdge* const falseEdge = predBlock->GetFalseEdge();
FlowEdge* keptEdge = nullptr;
FlowEdge* removedEdge = nullptr;
if (trueEdge->getDestinationBlock() == block)
{
keptEdge = trueEdge;
removedEdge = falseEdge;
}
else
{
assert(falseEdge->getDestinationBlock() == block);
keptEdge = falseEdge;
removedEdge = trueEdge;
}
BasicBlock* removedBlock = removedEdge->getDestinationBlock();
comp->fgRemoveRefPred(removedEdge);
predBlock->SetKindAndTargetEdge(BBJ_ALWAYS, keptEdge);
comp->fgRepairProfileCondToUncond(predBlock, keptEdge, removedEdge);
// Just lop off the JTRUE, the rest can clean up later
// (eg may have side effects)
//
controllingStmt->SetRootNode(controllingNode->gtGetOp1());
// We must remove the empty static block now too.
assert(removedBlock->bbRefs == 0);
assert(removedBlock->KindIs(BBJ_ALWAYS));
comp->fgRemoveBlock(removedBlock, /* unreachable */ true);
}
else
{
JITDUMP("ALLOCOBJ [%06u] is not part of an empty static\n", comp->dspTreeID(allocObj));
}
return lclNum;