-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
optcse.cpp
3876 lines (3369 loc) · 142 KB
/
optcse.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 OptCSE XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#include "jitstd/algorithm.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
/* static */
const size_t Compiler::s_optCSEhashSizeInitial = EXPSET_SZ * 2;
const size_t Compiler::s_optCSEhashGrowthFactor = 2;
const size_t Compiler::s_optCSEhashBucketSize = 4;
/*****************************************************************************
*
* We've found all the candidates, build the index for easy access.
*/
void Compiler::optCSEstop()
{
if (optCSECandidateCount == 0)
{
return;
}
CSEdsc* dsc;
CSEdsc** ptr;
size_t cnt;
optCSEtab = new (this, CMK_CSE) CSEdsc*[optCSECandidateCount]();
for (cnt = optCSEhashSize, ptr = optCSEhash; cnt; cnt--, ptr++)
{
for (dsc = *ptr; dsc; dsc = dsc->csdNextInBucket)
{
if (dsc->csdIndex)
{
noway_assert((unsigned)dsc->csdIndex <= optCSECandidateCount);
if (optCSEtab[dsc->csdIndex - 1] == nullptr)
{
optCSEtab[dsc->csdIndex - 1] = dsc;
}
}
}
}
#ifdef DEBUG
for (cnt = 0; cnt < optCSECandidateCount; cnt++)
{
noway_assert(optCSEtab[cnt] != nullptr);
}
#endif
}
/*****************************************************************************
*
* Return the descriptor for the CSE with the given index.
*/
inline Compiler::CSEdsc* Compiler::optCSEfindDsc(unsigned index)
{
noway_assert(index);
noway_assert(index <= optCSECandidateCount);
noway_assert(optCSEtab[index - 1]);
return optCSEtab[index - 1];
}
//------------------------------------------------------------------------
// Compiler::optUnmarkCSE
//
// Arguments:
// tree - A sub tree that originally was part of a CSE use
// that we are currently in the process of removing.
//
// Return Value:
// Returns true if we can safely remove the 'tree' node.
// Returns false if the node is a CSE def that the caller
// needs to extract and preserve.
//
// Notes:
// If 'tree' is a CSE use then we perform an unmark CSE operation
// so that the CSE used counts and weight are updated properly.
// The only caller for this method is optUnmarkCSEs which is a
// tree walker visitor function. When we return false this method
// returns WALK_SKIP_SUBTREES so that we don't visit the remaining
// nodes of the CSE def.
//
bool Compiler::optUnmarkCSE(GenTree* tree)
{
if (!IS_CSE_INDEX(tree->gtCSEnum))
{
// If this node isn't a CSE use or def we can safely remove this node.
//
return true;
}
// make sure it's been initialized
noway_assert(optCSEweight >= 0);
// Is this a CSE use?
if (IS_CSE_USE(tree->gtCSEnum))
{
unsigned CSEnum = GET_CSE_INDEX(tree->gtCSEnum);
CSEdsc* desc = optCSEfindDsc(CSEnum);
#ifdef DEBUG
if (verbose)
{
printf("Unmark CSE use #%02d at ", CSEnum);
printTreeID(tree);
printf(": %3d -> %3d\n", desc->csdUseCount, desc->csdUseCount - 1);
}
#endif // DEBUG
// Perform an unmark CSE operation
// 1. Reduce the nested CSE's 'use' count
noway_assert(desc->csdUseCount > 0);
if (desc->csdUseCount > 0)
{
desc->csdUseCount -= 1;
if (desc->csdUseWtCnt < optCSEweight)
{
desc->csdUseWtCnt = 0;
}
else
{
desc->csdUseWtCnt -= optCSEweight;
}
}
// 2. Unmark the CSE information in the node
tree->gtCSEnum = NO_CSE;
return true;
}
else
{
// It is not safe to remove this node, so we will return false
// and the caller must add this node to the side effect list
//
return false;
}
}
Compiler::fgWalkResult Compiler::optCSE_MaskHelper(GenTree** pTree, fgWalkData* walkData)
{
GenTree* tree = *pTree;
Compiler* comp = walkData->compiler;
optCSE_MaskData* pUserData = (optCSE_MaskData*)(walkData->pCallbackData);
return WALK_CONTINUE;
}
// This functions walks all the node for an given tree
// and return the mask of CSE defs and uses for the tree
//
void Compiler::optCSE_GetMaskData(GenTree* tree, optCSE_MaskData* pMaskData)
{
class MaskDataWalker : public GenTreeVisitor<MaskDataWalker>
{
optCSE_MaskData* m_maskData;
public:
enum
{
DoPreOrder = true,
};
MaskDataWalker(Compiler* comp, optCSE_MaskData* maskData) : GenTreeVisitor(comp), m_maskData(maskData)
{
}
fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
{
GenTree* tree = *use;
if (IS_CSE_INDEX(tree->gtCSEnum))
{
unsigned cseIndex = GET_CSE_INDEX(tree->gtCSEnum);
// Note that we DO NOT use getCSEAvailBit() here, for the CSE_defMask/CSE_useMask
unsigned cseBit = genCSEnum2bit(cseIndex);
if (IS_CSE_DEF(tree->gtCSEnum))
{
BitVecOps::AddElemD(m_compiler->cseMaskTraits, m_maskData->CSE_defMask, cseBit);
}
else
{
BitVecOps::AddElemD(m_compiler->cseMaskTraits, m_maskData->CSE_useMask, cseBit);
}
}
return fgWalkResult::WALK_CONTINUE;
}
};
pMaskData->CSE_defMask = BitVecOps::MakeEmpty(cseMaskTraits);
pMaskData->CSE_useMask = BitVecOps::MakeEmpty(cseMaskTraits);
MaskDataWalker walker(this, pMaskData);
walker.WalkTree(&tree, nullptr);
}
//------------------------------------------------------------------------
// optCSE_canSwap: Determine if the execution order of two nodes can be swapped.
//
// Arguments:
// op1 - The first node
// op2 - The second node
//
// Return Value:
// Return true iff it safe to swap the execution order of 'op1' and 'op2',
// considering only the locations of the CSE defs and uses.
//
// Assumptions:
// 'op1' currently occurse before 'op2' in the execution order.
//
bool Compiler::optCSE_canSwap(GenTree* op1, GenTree* op2)
{
// op1 and op2 must be non-null.
assert(op1 != nullptr);
assert(op2 != nullptr);
bool canSwap = true; // the default result unless proven otherwise.
// If we haven't setup cseMaskTraits, do it now
if (cseMaskTraits == nullptr)
{
cseMaskTraits = new (getAllocator(CMK_CSE)) BitVecTraits(optCSECandidateCount, this);
}
optCSE_MaskData op1MaskData;
optCSE_MaskData op2MaskData;
optCSE_GetMaskData(op1, &op1MaskData);
optCSE_GetMaskData(op2, &op2MaskData);
// We cannot swap if op1 contains a CSE def that is used by op2
if (!BitVecOps::IsEmptyIntersection(cseMaskTraits, op1MaskData.CSE_defMask, op2MaskData.CSE_useMask))
{
canSwap = false;
}
else
{
// We also cannot swap if op2 contains a CSE def that is used by op1.
if (!BitVecOps::IsEmptyIntersection(cseMaskTraits, op2MaskData.CSE_defMask, op1MaskData.CSE_useMask))
{
canSwap = false;
}
}
return canSwap;
}
/*****************************************************************************
*
* Compare function passed to jitstd::sort() by CSE_Heuristic::SortCandidates
* when (CodeOptKind() != Compiler::SMALL_CODE)
*/
/* static */
bool Compiler::optCSEcostCmpEx::operator()(const CSEdsc* dsc1, const CSEdsc* dsc2)
{
GenTree* exp1 = dsc1->csdTree;
GenTree* exp2 = dsc2->csdTree;
auto expCost1 = exp1->GetCostEx();
auto expCost2 = exp2->GetCostEx();
if (expCost2 != expCost1)
{
return expCost2 < expCost1;
}
// Sort the higher Use Counts toward the top
if (dsc2->csdUseWtCnt != dsc1->csdUseWtCnt)
{
return dsc2->csdUseWtCnt < dsc1->csdUseWtCnt;
}
// With the same use count, Sort the lower Def Counts toward the top
if (dsc1->csdDefWtCnt != dsc2->csdDefWtCnt)
{
return dsc1->csdDefWtCnt < dsc2->csdDefWtCnt;
}
// In order to ensure that we have a stable sort, we break ties using the csdIndex
return dsc1->csdIndex < dsc2->csdIndex;
}
/*****************************************************************************
*
* Compare function passed to jitstd::sort() by CSE_Heuristic::SortCandidates
* when (CodeOptKind() == Compiler::SMALL_CODE)
*/
/* static */
bool Compiler::optCSEcostCmpSz::operator()(const CSEdsc* dsc1, const CSEdsc* dsc2)
{
GenTree* exp1 = dsc1->csdTree;
GenTree* exp2 = dsc2->csdTree;
auto expCost1 = exp1->GetCostSz();
auto expCost2 = exp2->GetCostSz();
if (expCost2 != expCost1)
{
return expCost2 < expCost1;
}
// Sort the higher Use Counts toward the top
if (dsc2->csdUseCount != dsc1->csdUseCount)
{
return dsc2->csdUseCount < dsc1->csdUseCount;
}
// With the same use count, Sort the lower Def Counts toward the top
if (dsc1->csdDefCount != dsc2->csdDefCount)
{
return dsc1->csdDefCount < dsc2->csdDefCount;
}
// In order to ensure that we have a stable sort, we break ties using the csdIndex
return dsc1->csdIndex < dsc2->csdIndex;
}
/*****************************************************************************
*
* Initialize the Value Number CSE tracking logic.
*/
void Compiler::optValnumCSE_Init()
{
#ifdef DEBUG
optCSEtab = nullptr;
#endif
// This gets set in optValnumCSE_InitDataFlow
cseLivenessTraits = nullptr;
// Initialize when used by optCSE_canSwap()
cseMaskTraits = nullptr;
// Allocate and clear the hash bucket table
optCSEhash = new (this, CMK_CSE) CSEdsc*[s_optCSEhashSizeInitial]();
optCSEhashSize = s_optCSEhashSizeInitial;
optCSEhashMaxCountBeforeResize = optCSEhashSize * s_optCSEhashBucketSize;
optCSEhashCount = 0;
optCSECandidateCount = 0;
optDoCSE = false; // Stays false until we find duplicate CSE tree
// optCseCheckedBoundMap is unused in most functions, allocated only when used
optCseCheckedBoundMap = nullptr;
}
unsigned optCSEKeyToHashIndex(size_t key, size_t optCSEhashSize)
{
unsigned hash;
hash = (unsigned)key;
#ifdef TARGET_64BIT
hash ^= (unsigned)(key >> 32);
#endif
hash *= (unsigned)(optCSEhashSize + 1);
hash >>= 7;
return hash % optCSEhashSize;
}
//---------------------------------------------------------------------------
// optValnumCSE_Index:
// - Returns the CSE index to use for this tree,
// or zero if this expression is not currently a CSE.
//
// Arguments:
// tree - The current candidate CSE expression
// stmt - The current statement that contains tree
//
//
// Notes: We build a hash table that contains all of the expressions that
// are presented to this method. Whenever we see a duplicate expression
// we have a CSE candidate. If it is the first time seeing the duplicate
// we allocate a new CSE index. If we have already allocated a CSE index
// we return that index. There currently is a limit on the number of CSEs
// that we can have of MAX_CSE_CNT (64)
//
unsigned Compiler::optValnumCSE_Index(GenTree* tree, Statement* stmt)
{
size_t key;
unsigned hval;
CSEdsc* hashDsc;
bool enableSharedConstCSE = false;
bool isSharedConst = false;
int configValue = JitConfig.JitConstCSE();
#if defined(TARGET_ARMARCH)
// ARMARCH - allow to combine with nearby offsets, when config is not 2 or 4
if ((configValue != CONST_CSE_ENABLE_ARM_NO_SHARING) && (configValue != CONST_CSE_ENABLE_ALL_NO_SHARING))
{
enableSharedConstCSE = true;
}
#endif // TARGET_ARMARCH
// All Platforms - also allow to combine with nearby offsets, when config is 3
if (configValue == CONST_CSE_ENABLE_ALL)
{
enableSharedConstCSE = true;
}
// We use the liberal Value numbers when building the set of CSE
ValueNum vnLib = tree->GetVN(VNK_Liberal);
ValueNum vnLibNorm = vnStore->VNNormalValue(vnLib);
// We use the normal value number because we want the CSE candidate to
// represent all expressions that produce the same normal value number.
// We will handle the case where we have different exception sets when
// promoting the candidates.
//
// We do this because a GT_IND will usually have a NullPtrExc entry in its
// exc set, but we may have cleared the GTF_EXCEPT flag and if so, it won't
// have an NullPtrExc, or we may have assigned the value of an GT_IND
// into a LCL_VAR and then read it back later.
//
// When we are promoting the CSE candidates we ensure that any CSE
// uses that we promote have an exc set that is the same as the CSE defs
// or have an empty set. And that all of the CSE defs produced the required
// set of exceptions for the CSE uses.
//
// We assign either vnLib or vnLibNorm as the hash key
//
// The only exception to using the normal value is for the GT_COMMA nodes.
// Here we check to see if we have a GT_COMMA with a different value number
// than the one from its op2. For this case we want to create two different
// CSE candidates. This allows us to CSE the GT_COMMA separately from its value.
//
if (tree->OperGet() == GT_COMMA)
{
// op2 is the value produced by a GT_COMMA
GenTree* op2 = tree->AsOp()->gtOp2;
ValueNum vnOp2Lib = op2->GetVN(VNK_Liberal);
// If the value number for op2 and tree are different, then some new
// exceptions were produced by op1. For that case we will NOT use the
// normal value. This allows us to CSE commas with an op1 that is
// an BOUNDS_CHECK.
//
if (vnOp2Lib != vnLib)
{
key = vnLib; // include the exc set in the hash key
}
else
{
key = vnLibNorm;
}
// If we didn't do the above we would have op1 as the CSE def
// and the parent comma as the CSE use (but with a different exc set)
// This would prevent us from making any CSE with the comma
//
assert(vnLibNorm == vnStore->VNNormalValue(vnOp2Lib));
}
else if (enableSharedConstCSE && tree->IsIntegralConst())
{
assert(vnStore->IsVNConstant(vnLibNorm));
// We don't share small offset constants when they require a reloc
// Also, we don't share non-null const gc handles
//
if (!tree->AsIntConCommon()->ImmedValNeedsReloc(this) && ((tree->IsIntegralConst(0)) || !varTypeIsGC(tree)))
{
// Here we make constants that have the same upper bits use the same key
//
// We create a key that encodes just the upper bits of the constant by
// shifting out some of the low bits, (12 or 16 bits)
//
// This is the only case where the hash key is not a ValueNumber
//
size_t constVal = vnStore->CoercedConstantValue<size_t>(vnLibNorm);
key = Encode_Shared_Const_CSE_Value(constVal);
isSharedConst = true;
}
else
{
// Use the vnLibNorm value as the key
key = vnLibNorm;
}
}
else // Not a GT_COMMA or a GT_CNS_INT
{
key = vnLibNorm;
}
// Make sure that the result of Is_Shared_Const_CSE(key) matches isSharedConst.
// Note that when isSharedConst is true then we require that the TARGET_SIGN_BIT is set in the key
// and otherwise we require that we never create a ValueNumber with the TARGET_SIGN_BIT set.
//
assert(isSharedConst == Is_Shared_Const_CSE(key));
// Compute the hash value for the expression
hval = optCSEKeyToHashIndex(key, optCSEhashSize);
/* Look for a matching index in the hash table */
bool newCSE = false;
for (hashDsc = optCSEhash[hval]; hashDsc; hashDsc = hashDsc->csdNextInBucket)
{
if (hashDsc->csdHashKey == key)
{
// Check for mismatched types on GT_CNS_INT nodes
if ((tree->OperGet() == GT_CNS_INT) && (tree->TypeGet() != hashDsc->csdTree->TypeGet()))
{
continue;
}
treeStmtLst* newElem;
/* Have we started the list of matching nodes? */
if (hashDsc->csdTreeList == nullptr)
{
// Create the new element based upon the matching hashDsc element.
newElem = new (this, CMK_TreeStatementList) treeStmtLst;
newElem->tslTree = hashDsc->csdTree;
newElem->tslStmt = hashDsc->csdStmt;
newElem->tslBlock = hashDsc->csdBlock;
newElem->tslNext = nullptr;
/* Start the list with the first CSE candidate recorded */
hashDsc->csdTreeList = newElem;
hashDsc->csdTreeLast = newElem;
hashDsc->csdIsSharedConst = isSharedConst;
}
noway_assert(hashDsc->csdTreeList);
/* Append this expression to the end of the list */
newElem = new (this, CMK_TreeStatementList) treeStmtLst;
newElem->tslTree = tree;
newElem->tslStmt = stmt;
newElem->tslBlock = compCurBB;
newElem->tslNext = nullptr;
hashDsc->csdTreeLast->tslNext = newElem;
hashDsc->csdTreeLast = newElem;
optDoCSE = true; // Found a duplicate CSE tree
/* Have we assigned a CSE index? */
if (hashDsc->csdIndex == 0)
{
newCSE = true;
break;
}
assert(FitsIn<signed char>(hashDsc->csdIndex));
tree->gtCSEnum = ((signed char)hashDsc->csdIndex);
return hashDsc->csdIndex;
}
}
if (!newCSE)
{
/* Not found, create a new entry (unless we have too many already) */
if (optCSECandidateCount < MAX_CSE_CNT)
{
if (optCSEhashCount == optCSEhashMaxCountBeforeResize)
{
size_t newOptCSEhashSize = optCSEhashSize * s_optCSEhashGrowthFactor;
CSEdsc** newOptCSEhash = new (this, CMK_CSE) CSEdsc*[newOptCSEhashSize]();
// Iterate through each existing entry, moving to the new table
CSEdsc** ptr;
CSEdsc* dsc;
size_t cnt;
for (cnt = optCSEhashSize, ptr = optCSEhash; cnt; cnt--, ptr++)
{
for (dsc = *ptr; dsc;)
{
CSEdsc* nextDsc = dsc->csdNextInBucket;
size_t newHval = optCSEKeyToHashIndex(dsc->csdHashKey, newOptCSEhashSize);
// Move CSEdsc to bucket in enlarged table
dsc->csdNextInBucket = newOptCSEhash[newHval];
newOptCSEhash[newHval] = dsc;
dsc = nextDsc;
}
}
hval = optCSEKeyToHashIndex(key, newOptCSEhashSize);
optCSEhash = newOptCSEhash;
optCSEhashSize = newOptCSEhashSize;
optCSEhashMaxCountBeforeResize = optCSEhashMaxCountBeforeResize * s_optCSEhashGrowthFactor;
}
++optCSEhashCount;
hashDsc = new (this, CMK_CSE) CSEdsc;
hashDsc->csdHashKey = key;
hashDsc->csdConstDefValue = 0;
hashDsc->csdConstDefVN = vnStore->VNForNull(); // uninit value
hashDsc->csdIndex = 0;
hashDsc->csdIsSharedConst = false;
hashDsc->csdLiveAcrossCall = false;
hashDsc->csdDefCount = 0;
hashDsc->csdUseCount = 0;
hashDsc->csdDefWtCnt = 0;
hashDsc->csdUseWtCnt = 0;
hashDsc->defExcSetPromise = vnStore->VNForEmptyExcSet();
hashDsc->defExcSetCurrent = vnStore->VNForNull(); // uninit value
hashDsc->defConservNormVN = vnStore->VNForNull(); // uninit value
hashDsc->csdTree = tree;
hashDsc->csdStmt = stmt;
hashDsc->csdBlock = compCurBB;
hashDsc->csdTreeList = nullptr;
/* Append the entry to the hash bucket */
hashDsc->csdNextInBucket = optCSEhash[hval];
optCSEhash[hval] = hashDsc;
}
return 0;
}
else // newCSE is true
{
/* We get here only after finding a matching CSE */
/* Create a new CSE (unless we have the maximum already) */
if (optCSECandidateCount == MAX_CSE_CNT)
{
#ifdef DEBUG
if (verbose)
{
printf("Exceeded the MAX_CSE_CNT, not using tree:\n");
gtDispTree(tree);
}
#endif // DEBUG
return 0;
}
C_ASSERT((signed char)MAX_CSE_CNT == MAX_CSE_CNT);
unsigned CSEindex = ++optCSECandidateCount;
/* Record the new CSE index in the hashDsc */
hashDsc->csdIndex = CSEindex;
/* Update the gtCSEnum field in the original tree */
noway_assert(hashDsc->csdTreeList->tslTree->gtCSEnum == 0);
assert(FitsIn<signed char>(CSEindex));
hashDsc->csdTreeList->tslTree->gtCSEnum = ((signed char)CSEindex);
noway_assert(((unsigned)hashDsc->csdTreeList->tslTree->gtCSEnum) == CSEindex);
tree->gtCSEnum = ((signed char)CSEindex);
#ifdef DEBUG
if (verbose)
{
printf("\nCandidate " FMT_CSE ", key=", CSEindex);
if (!Compiler::Is_Shared_Const_CSE(key))
{
vnPrint((unsigned)key, 0);
}
else
{
size_t kVal = Compiler::Decode_Shared_Const_CSE_Value(key);
printf("K_%p", dspPtr(kVal));
}
printf(" in " FMT_BB ", [cost=%2u, size=%2u]: \n", compCurBB->bbNum, tree->GetCostEx(), tree->GetCostSz());
gtDispTree(tree);
}
#endif // DEBUG
return CSEindex;
}
}
//------------------------------------------------------------------------
// optValnumCSE_Locate: Locate CSE candidates and assign them indices.
//
// Returns:
// true if there are any CSE candidates, false otherwise
//
bool Compiler::optValnumCSE_Locate()
{
bool enableConstCSE = true;
int configValue = JitConfig.JitConstCSE();
// all platforms - disable CSE of constant values when config is 1
if (configValue == CONST_CSE_DISABLE_ALL)
{
enableConstCSE = false;
}
#if !defined(TARGET_ARM64)
// non-ARM64 platforms - disable by default
//
enableConstCSE = false;
// Check for the two enable cases for all platforms
//
if ((configValue == CONST_CSE_ENABLE_ALL) || (configValue == CONST_CSE_ENABLE_ALL_NO_SHARING))
{
enableConstCSE = true;
}
#endif
for (BasicBlock* const block : Blocks())
{
/* Make the block publicly available */
compCurBB = block;
// Ensure that the BBF_MARKED flag is clear.
// Everyone who uses this flag is required to clear it afterwards.
noway_assert((block->bbFlags & BBF_MARKED) == 0);
/* Walk the statement trees in this basic block */
for (Statement* const stmt : block->NonPhiStatements())
{
const bool isReturn = stmt->GetRootNode()->OperIs(GT_RETURN);
/* We walk the tree in the forwards direction (bottom up) */
bool stmtHasArrLenCandidate = false;
for (GenTree* const tree : stmt->TreeList())
{
if (tree->OperIsCompare() && stmtHasArrLenCandidate)
{
// Check if this compare is a function of (one of) the checked
// bound candidate(s); we may want to update its value number.
// if the array length gets CSEd
optCseUpdateCheckedBoundMap(tree);
}
// Don't allow CSE of constants if it is disabled
if (tree->IsIntegralConst())
{
if (!enableConstCSE &&
// Unconditionally allow these constant handles to be CSE'd
!tree->IsIconHandle(GTF_ICON_STATIC_HDL) && !tree->IsIconHandle(GTF_ICON_CLASS_HDL) &&
!tree->IsIconHandle(GTF_ICON_STR_HDL) && !tree->IsIconHandle(GTF_ICON_OBJ_HDL))
{
continue;
}
}
// Don't allow non-SIMD struct CSEs under a return; we don't fully
// re-morph these if we introduce a CSE assignment, and so may create
// IR that lower is not yet prepared to handle.
//
if (isReturn && varTypeIsStruct(tree->gtType) && !varTypeIsSIMD(tree->gtType))
{
continue;
}
if (!optIsCSEcandidate(tree))
{
continue;
}
ValueNum valueVN = vnStore->VNNormalValue(tree->GetVN(VNK_Liberal));
if (ValueNumStore::isReservedVN(valueVN) && (valueVN != ValueNumStore::VNForNull()))
{
continue;
}
// We want to CSE simple constant leaf nodes, but we don't want to
// CSE non-leaf trees that compute CSE constant values.
// Instead we let the Value Number based Assertion Prop phase handle them.
//
// Here, unlike the rest of optCSE, we use the conservative value number
// rather than the liberal one, since the conservative one
// is what the Value Number based Assertion Prop will use
// and the point is to avoid optimizing cases that it will
// handle.
//
if (!tree->OperIsLeaf() && vnStore->IsVNConstant(vnStore->VNConservativeNormalValue(tree->gtVNPair)))
{
continue;
}
/* Assign an index to this expression */
unsigned CSEindex = optValnumCSE_Index(tree, stmt);
if (CSEindex != 0)
{
noway_assert(((unsigned)tree->gtCSEnum) == CSEindex);
}
if (IS_CSE_INDEX(CSEindex) && tree->OperIsArrLength())
{
stmtHasArrLenCandidate = true;
}
}
}
}
/* We're done if there were no interesting expressions */
if (!optDoCSE)
{
return false;
}
/* We're finished building the expression lookup table */
optCSEstop();
return true;
}
//------------------------------------------------------------------------
// optCseUpdateCheckedBoundMap: Check if this compare is a tractable function of
// a checked bound that is a CSE candidate, and insert
// an entry in the optCseCheckedBoundMap if so. This facilitates
// subsequently updating the compare's value number if
// the bound gets CSEd.
//
// Arguments:
// compare - The compare node to check
//
void Compiler::optCseUpdateCheckedBoundMap(GenTree* compare)
{
assert(compare->OperIsCompare());
ValueNum compareVN = compare->gtVNPair.GetConservative();
VNFuncApp cmpVNFuncApp;
if (!vnStore->GetVNFunc(compareVN, &cmpVNFuncApp) || (cmpVNFuncApp.m_func != GetVNFuncForNode(compare)))
{
// Value numbering inferred this compare as something other
// than its own operator; leave its value number alone.
return;
}
// Now look for a checked bound feeding the compare
ValueNumStore::CompareCheckedBoundArithInfo info;
GenTree* boundParent = nullptr;
if (vnStore->IsVNCompareCheckedBound(compareVN))
{
// Simple compare of an bound against something else.
vnStore->GetCompareCheckedBound(compareVN, &info);
boundParent = compare;
}
else if (vnStore->IsVNCompareCheckedBoundArith(compareVN))
{
// Compare of a bound +/- some offset to something else.
GenTree* op1 = compare->gtGetOp1();
GenTree* op2 = compare->gtGetOp2();
vnStore->GetCompareCheckedBoundArithInfo(compareVN, &info);
if (GetVNFuncForNode(op1) == (VNFunc)info.arrOper)
{
// The arithmetic node is the bound's parent.
boundParent = op1;
}
else if (GetVNFuncForNode(op2) == (VNFunc)info.arrOper)
{
// The arithmetic node is the bound's parent.
boundParent = op2;
}
}
if (boundParent != nullptr)
{
GenTree* bound = nullptr;
// Find which child of boundParent is the bound. Abort if neither
// conservative value number matches the one from the compare VN.
GenTree* child1 = boundParent->gtGetOp1();
if ((info.vnBound == child1->gtVNPair.GetConservative()) && IS_CSE_INDEX(child1->gtCSEnum))
{
bound = child1;
}
else
{
GenTree* child2 = boundParent->gtGetOp2();
if ((info.vnBound == child2->gtVNPair.GetConservative()) && IS_CSE_INDEX(child2->gtCSEnum))
{
bound = child2;
}
}
if (bound != nullptr)
{
// Found a checked bound feeding a compare that is a tractable function of it;
// record this in the map so we can update the compare VN if the bound
// node gets CSEd.
if (optCseCheckedBoundMap == nullptr)
{
// Allocate map on first use.
optCseCheckedBoundMap = new (getAllocator(CMK_CSE)) NodeToNodeMap(getAllocator());
}
optCseCheckedBoundMap->Set(bound, compare);
}
}
}
/*****************************************************************************
*
* Compute each blocks bbCseGen
* This is the bitset that represents the CSEs that are generated within the block
* Also initialize bbCseIn, bbCseOut and bbCseGen sets for all blocks
*/
void Compiler::optValnumCSE_InitDataFlow()
{
// BitVec trait information for computing CSE availability using the CSE_DataFlow algorithm.
// Two bits are allocated per CSE candidate to compute CSE availability
// plus an extra bit to handle the initial unvisited case.
// (See CSE_DataFlow::EndMerge for an explanation of why this is necessary)
//
// The two bits per CSE candidate have the following meanings:
// 11 - The CSE is available, and is also available when considering calls as killing availability.
// 10 - The CSE is available, but is not available when considering calls as killing availability.
// 00 - The CSE is not available
// 01 - An illegal combination
//
const unsigned bitCount = (optCSECandidateCount * 2) + 1;
// Init traits and cseCallKillsMask bitvectors.
cseLivenessTraits = new (getAllocator(CMK_CSE)) BitVecTraits(bitCount, this);
cseCallKillsMask = BitVecOps::MakeEmpty(cseLivenessTraits);
for (unsigned inx = 1; inx <= optCSECandidateCount; inx++)
{
unsigned cseAvailBit = getCSEAvailBit(inx);
// a one preserves availability and a zero kills the availability
// we generate this kind of bit pattern: 101010101010
//
BitVecOps::AddElemD(cseLivenessTraits, cseCallKillsMask, cseAvailBit);
}
for (BasicBlock* const block : Blocks())
{
/* Initialize the blocks's bbCseIn set */
bool init_to_zero = false;
if (block == fgFirstBB)
{
/* Clear bbCseIn for the entry block */
init_to_zero = true;
}
#if !CSE_INTO_HANDLERS
else
{
if (bbIsHandlerBeg(block))
{
/* Clear everything on entry to filters or handlers */
init_to_zero = true;
}
}
#endif
if (init_to_zero)
{
/* Initialize to {ZERO} prior to dataflow */
block->bbCseIn = BitVecOps::MakeEmpty(cseLivenessTraits);
}
else
{
/* Initialize to {ALL} prior to dataflow */
block->bbCseIn = BitVecOps::MakeFull(cseLivenessTraits);
}