-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathrangecheck.cpp
More file actions
2556 lines (2302 loc) · 95.3 KB
/
Copy pathrangecheck.cpp
File metadata and controls
2556 lines (2302 loc) · 95.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
#include "jitpch.h"
#include "rangecheck.h"
//------------------------------------------------------------------------
// rangeCheckPhase: optimize bounds checks via range analysis
//
// Returns:
// Suitable phase status
//
PhaseStatus Compiler::rangeCheckPhase()
{
if (!doesMethodHaveBoundsChecks() || (fgSsaPassesCompleted == 0))
{
return PhaseStatus::MODIFIED_NOTHING;
}
const bool madeChanges = GetRangeCheck()->OptimizeRangeChecks();
return madeChanges ? PhaseStatus::MODIFIED_EVERYTHING : PhaseStatus::MODIFIED_NOTHING;
}
// Max stack depth (path length) in walking the UD chain.
static const int MAX_SEARCH_DEPTH = 100;
// Max nodes to visit in the UD chain for the current method being compiled.
static const int MAX_VISIT_BUDGET = 8192;
//------------------------------------------------------------------------
// GetRangeCheck: get the RangeCheck instance
//
// Returns:
// The range check object
//
RangeCheck* Compiler::GetRangeCheck(int customBudget)
{
if (optRangeCheck == nullptr)
{
optRangeCheck = new (this, CMK_Generic) RangeCheck(this);
}
optRangeCheck->SetBudget(customBudget > 0 ? customBudget : MAX_VISIT_BUDGET);
return optRangeCheck;
}
// RangeCheck constructor.
RangeCheck::RangeCheck(Compiler* pCompiler)
: m_preferredBound(ValueNumStore::NoVN)
, m_pRangeMap(nullptr)
, m_pSearchPath(nullptr)
, m_compiler(pCompiler)
, m_alloc(pCompiler->getAllocator(CMK_RangeCheck))
, m_nVisitBudget(MAX_VISIT_BUDGET)
, m_updateStmt(false)
{
}
bool RangeCheck::IsOverBudget()
{
return (m_nVisitBudget <= 0);
}
// Get the range map in which computed ranges are cached.
RangeCheck::RangeMap* RangeCheck::GetRangeMap()
{
if (m_pRangeMap == nullptr)
{
m_pRangeMap = new (m_alloc) RangeMap(m_alloc);
}
return m_pRangeMap;
}
void RangeCheck::ClearRangeMap()
{
if (m_pRangeMap != nullptr)
{
m_pRangeMap->RemoveAll();
}
}
RangeCheck::SearchPath* RangeCheck::GetSearchPath()
{
if (m_pSearchPath == nullptr)
{
m_pSearchPath = new (m_alloc) SearchPath(m_alloc);
}
return m_pSearchPath;
}
void RangeCheck::ClearSearchPath()
{
if (m_pSearchPath != nullptr)
{
m_pSearchPath->RemoveAll();
}
}
// Get the length of the array vn, if it is new.
int RangeCheck::GetArrLength(ValueNum vn)
{
ValueNum arrRefVN = m_compiler->vnStore->GetArrForLenVn(vn);
int size;
return m_compiler->vnStore->TryGetNewArrSize(arrRefVN, &size) ? size : 0;
}
//------------------------------------------------------------------------
// BetweenBounds: Check if the computed range is within bounds
//
// Arguments:
// Range - the range to check if in bounds
// upper - the array length vn
// arrSize - the length of the array if known, or <= 0
//
// Return Value:
// True iff range is between [0 and vn - 1] or [0, arrSize - 1]
//
// notes:
// This function assumes that the lower range is resolved and upper range is symbolic as in an
// increasing loop.
//
// TODO-CQ: This is not general enough.
//
bool RangeCheck::BetweenBounds(Range& range, GenTree* upper, int arrSize)
{
#ifdef DEBUG
assert(range.IsValid());
if (m_compiler->verbose)
{
printf("%s BetweenBounds <%d, ", range.ToString(m_compiler), 0);
Compiler::printTreeID(upper);
printf(">\n");
}
#endif // DEBUG
ValueNumStore* vnStore = m_compiler->vnStore;
// Get the VN for the upper limit.
ValueNum uLimitVN = vnStore->VNConservativeNormalValue(upper->gtVNPair);
#ifdef DEBUG
JITDUMP(FMT_VN " upper bound is: ", uLimitVN);
if (m_compiler->verbose)
{
vnStore->vnDump(m_compiler, uLimitVN);
}
JITDUMP("\n");
#endif
if ((arrSize <= 0) && !vnStore->IsVNCheckedBound(uLimitVN))
{
// If we don't know the array size and the upper limit is not known, then bail.
return false;
}
JITDUMP("Array size is: %d\n", arrSize);
// Upper limit: len + ucns (upper limit constant).
if (range.UpperLimit().IsBinOpArray())
{
if (range.UpperLimit().vn != uLimitVN)
{
return false;
}
int ucns = range.UpperLimit().GetConstant();
// Upper limit: Len + [0..n]
if (ucns >= 0)
{
return false;
}
// Since upper limit is bounded by the array, return true if lower bound is good.
if (range.LowerLimit().IsConstant() && range.LowerLimit().GetConstant() >= 0)
{
return true;
}
// Check if we have the array size allocated by new.
if (arrSize <= 0)
{
return false;
}
// At this point,
// upper limit = len + ucns. ucns < 0
// lower limit = len + lcns.
if (range.LowerLimit().IsBinOpArray())
{
int lcns = range.LowerLimit().GetConstant();
// Use "lcns < -arrSize" rather than "-lcns > arrSize" to avoid signed
// overflow when lcns == INT_MIN.
assert(arrSize > 0);
if (lcns >= 0 || lcns < -arrSize)
{
return false;
}
return (range.LowerLimit().vn == uLimitVN && lcns <= ucns);
}
}
// If upper limit is constant
else if (range.UpperLimit().IsConstant())
{
if (arrSize <= 0)
{
return false;
}
int ucns = range.UpperLimit().GetConstant();
if (ucns >= arrSize)
{
return false;
}
if (range.LowerLimit().IsConstant())
{
int lcns = range.LowerLimit().GetConstant();
// Make sure lcns < ucns which is already less than arrSize.
return (lcns >= 0 && lcns <= ucns);
}
if (range.LowerLimit().IsBinOpArray())
{
int lcns = range.LowerLimit().GetConstant();
// len + lcns, make sure we don't subtract too much from len. Use
// "lcns < -arrSize" rather than "-lcns > arrSize" to avoid signed
// overflow when lcns == INT_MIN.
assert(arrSize > 0);
if (lcns >= 0 || lcns < -arrSize)
{
return false;
}
// Make sure a.len + lcns <= ucns.
return (range.LowerLimit().vn == uLimitVN && (arrSize + lcns) <= ucns);
}
}
return false;
}
void RangeCheck::OptimizeRangeCheck(BasicBlock* block, Statement* stmt, GenTree* treeParent)
{
// Check if we are dealing with a bounds check node.
bool isComma = treeParent->OperIs(GT_COMMA);
bool isTopLevelNode = treeParent == stmt->GetRootNode();
if (!(isComma || isTopLevelNode))
{
return;
}
// If we are not looking at array bounds check, bail.
GenTree* tree = isComma ? treeParent->AsOp()->gtOp1 : treeParent;
if (!tree->OperIs(GT_BOUNDS_CHECK))
{
return;
}
GenTree* comma = treeParent->OperIs(GT_COMMA) ? treeParent : nullptr;
GenTreeBoundsChk* bndsChk = tree->AsBoundsChk();
GenTree* treeIndex = bndsChk->GetIndex();
ValueNum arrLenVn = m_compiler->optConservativeNormalVN(bndsChk->GetArrayLength());
// Get the range for this index.
Range range = Range(Limit(Limit::keUndef));
if (!TryGetRange(block, treeIndex, &range, arrLenVn))
{
JITDUMP("Failed to get range\n");
return;
}
Range arrSizeRng = GetRangeFromAssertions(m_compiler, bndsChk->GetArrayLength(), block->bbAssertionIn);
if (arrSizeRng.IsConstantRange())
{
int arrSize = arrSizeRng.LowerLimit().GetConstant();
// Is the range between the lower and upper bound values.
if (BetweenBounds(range, bndsChk->GetArrayLength(), arrSize))
{
JITDUMP("[RangeCheck::OptimizeRangeCheck] Between bounds\n");
m_compiler->optRemoveRangeCheck(bndsChk, comma, stmt);
m_updateStmt = true;
}
}
}
void RangeCheck::Widen(BasicBlock* block, GenTree* tree, Range* pRange)
{
#ifdef DEBUG
if (m_compiler->verbose)
{
printf("[RangeCheck::Widen] " FMT_BB ", \n", block->bbNum);
Compiler::printTreeID(tree);
printf("\n");
}
#endif // DEBUG
Range& range = *pRange;
// Try to deduce the lower bound, if it is not known already.
if (range.LowerLimit().IsDependent() || range.LowerLimit().IsUnknown())
{
// To determine the lower bound, ask if the loop increases monotonically.
bool increasing = IsMonotonicallyIncreasing(tree, false);
if (increasing)
{
JITDUMP("[%06d] is monotonically increasing.\n", Compiler::dspTreeID(tree));
ClearRangeMap();
*pRange = GetRangeWorker(block, tree, true DEBUGARG(0));
}
}
}
bool RangeCheck::IsBinOpMonotonicallyIncreasing(GenTreeOp* binop)
{
assert(binop->OperIs(GT_ADD));
GenTree* op1 = binop->gtGetOp1();
GenTree* op2 = binop->gtGetOp2();
JITDUMP("[RangeCheck::IsBinOpMonotonicallyIncreasing] [%06d], [%06d]\n", Compiler::dspTreeID(op1),
Compiler::dspTreeID(op2));
// Canonicalize to (lclVar + {lclVar|const}).
if (op2->OperIs(GT_LCL_VAR))
{
std::swap(op1, op2);
}
if (!op1->OperIs(GT_LCL_VAR))
{
JITDUMP("Not monotonically increasing because op1 is not lclVar.\n");
return false;
}
switch (op2->OperGet())
{
case GT_LCL_VAR:
// When adding two local variables, we also must ensure that any constant is non-negative.
return IsMonotonicallyIncreasing(op1, true) && IsMonotonicallyIncreasing(op2, true);
case GT_CNS_INT:
if (op2->AsIntConCommon()->IconValue() < 0)
{
JITDUMP("Not monotonically increasing because of encountered negative constant\n");
return false;
}
return IsMonotonicallyIncreasing(op1, false);
default:
JITDUMP("Not monotonically increasing because expression is not recognized.\n");
return false;
}
}
// The parameter rejectNegativeConst is true when we are adding two local vars (see above)
bool RangeCheck::IsMonotonicallyIncreasing(GenTree* expr, bool rejectNegativeConst)
{
JITDUMP("[RangeCheck::IsMonotonicallyIncreasing] [%06d]\n", Compiler::dspTreeID(expr));
if (IsOverBudget())
{
return false;
}
m_nVisitBudget--;
// Add hashtable entry for expr.
bool alreadyPresent = GetSearchPath()->Set(expr, nullptr, SearchPath::Overwrite);
if (alreadyPresent)
{
return true;
}
// Remove hashtable entry for expr when we exit the present scope.
auto code = [this, expr] {
GetSearchPath()->Remove(expr);
};
jitstd::utility::scoped_code<decltype(code)> finally(code);
if (GetSearchPath()->GetCount() > MAX_SEARCH_DEPTH)
{
return false;
}
// If expr is constant, then it is not part of the dependency
// loop which has to increase monotonically.
ValueNum vn = expr->gtVNPair.GetConservative();
if (m_compiler->vnStore->IsVNInt32Constant(vn))
{
if (rejectNegativeConst)
{
int cons = m_compiler->vnStore->ConstantValue<int>(vn);
return (cons >= 0);
}
else
{
return true;
}
}
// If the expr is local, then try to find the def of the local.
else if (expr->IsLocal())
{
LclSsaVarDsc* ssaDef = GetSsaDefStore(expr->AsLclVarCommon());
return (ssaDef != nullptr) && IsMonotonicallyIncreasing(ssaDef->GetDefNode()->Data(), rejectNegativeConst);
}
else if (expr->OperIs(GT_ADD))
{
return IsBinOpMonotonicallyIncreasing(expr->AsOp());
}
else if (expr->OperIs(GT_PHI))
{
for (GenTreePhi::Use& use : expr->AsPhi()->Uses())
{
// If the arg is already in the path, skip.
if (GetSearchPath()->Lookup(use.GetNode()))
{
continue;
}
if (!IsMonotonicallyIncreasing(use.GetNode(), rejectNegativeConst))
{
JITDUMP("Phi argument not monotonically increasing\n");
return false;
}
}
return true;
}
else if (expr->OperIs(GT_COMMA))
{
return IsMonotonicallyIncreasing(expr->gtEffectiveVal(), rejectNegativeConst);
}
JITDUMP("Unknown tree type\n");
return false;
}
// Given a lclvar use, try to find the lclvar's defining store and its containing block.
LclSsaVarDsc* RangeCheck::GetSsaDefStore(GenTreeLclVarCommon* lclUse)
{
// RangeCheck does not understand reads through LCL_FLD nodes: a LCL_FLD use reads a
// sub-range of the local (a different offset and/or a narrower type), so the value
// produced by the (full-width) definition does not describe the value being read.
if (lclUse->OperIs(GT_LCL_FLD))
{
return nullptr;
}
unsigned ssaNum = lclUse->GetSsaNum();
if (ssaNum == SsaConfig::RESERVED_SSA_NUM)
{
return nullptr;
}
unsigned lclNum = lclUse->GetLclNum();
LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum);
LclSsaVarDsc* ssaDef = varDsc->GetPerSsaData(ssaNum);
// RangeCheck does not care about uninitialized variables.
if (ssaDef->GetDefNode() == nullptr)
{
// Parameters are expected to be defined in fgFirstBB if FIRST_SSA_NUM is set
if (varDsc->lvIsParam && (ssaNum == SsaConfig::FIRST_SSA_NUM))
{
assert(ssaDef->GetBlock() == m_compiler->fgFirstBB);
}
return nullptr;
}
// RangeCheck does not understand definitions generated by LCL_FLD nodes
// nor definitions generated by indirect stores to local variables, nor
// stores through parent structs.
GenTreeLclVarCommon* defStore = ssaDef->GetDefNode();
if (!defStore->OperIs(GT_STORE_LCL_VAR) || !defStore->HasSsaName())
{
return nullptr;
}
return ssaDef;
}
//------------------------------------------------------------------------
// MergeEdgeAssertions: Merge assertions on the edge flowing into the block about a variable
//
// Arguments:
// GenTreeLclVarCommon - the variable to look for assertions for
// assertions - the assertions to use
// pRange - the range to tighten with assertions
//
void RangeCheck::MergeEdgeAssertions(GenTreeLclVarCommon* lcl, ASSERT_VALARG_TP assertions, Range* pRange)
{
if (lcl->GetSsaNum() == SsaConfig::RESERVED_SSA_NUM)
{
return;
}
LclSsaVarDsc* ssaData = m_compiler->lvaGetDesc(lcl)->GetPerSsaData(lcl->GetSsaNum());
ValueNum normalLclVN = m_compiler->vnStore->VNConservativeNormalValue(ssaData->m_vnPair);
MergeEdgeAssertions(m_compiler, normalLclVN, m_preferredBound, assertions, pRange);
}
//------------------------------------------------------------------------
// GetRangeFromAssertions: Cheaper version of TryGetRange that is based purely on assertions
// and does not require a full range analysis based on SSA.
//
// Arguments:
// comp - the compiler instance
// tree - the tree to analyze range for
// assertions - the assertions to use
// budget - the remaining budget for recursive analysis
//
// Return Value:
// The computed range
//
Range RangeCheck::GetRangeFromAssertions(Compiler* comp, GenTree* tree, ASSERT_VALARG_TP assertions, int budget)
{
var_types type = tree->TypeGet();
if (!varTypeIsIntegral(type))
{
return Limit(Limit::keUnknown);
}
ValueNum num = comp->vnStore->VNConservativeNormalValue(tree->gtVNPair);
if (num == ValueNumStore::NoVN)
{
// Use the widest supported constant range for type
return GetRangeFromType(type);
}
ValueNumStore::SmallValueNumSet set;
return GetRangeFromAssertionsWorker(comp, num, assertions, budget, &set);
}
//------------------------------------------------------------------------
// GetRangeFromAssertions: Cheaper version of TryGetRange that is based purely on assertions
// and does not require a full range analysis based on SSA.
//
// Arguments:
// comp - the compiler instance
// vn - the value number to analyze range for
// assertions - the assertions to use
// budget - the remaining budget for recursive analysis
//
// Return Value:
// The computed range
//
Range RangeCheck::GetRangeFromAssertions(Compiler* comp, ValueNum vn, ASSERT_VALARG_TP assertions, int budget)
{
if (vn == ValueNumStore::NoVN)
{
return Limit(Limit::keUnknown);
}
ValueNumStore::SmallValueNumSet set;
return GetRangeFromAssertionsWorker(comp, vn, assertions, budget, &set);
}
//------------------------------------------------------------------------
// GetRangeFromAssertionsWorker: Cheaper version of TryGetRange that is based purely on assertions
// and does not require a full range analysis based on SSA.
//
// Arguments:
// comp - the compiler instance
// num - the value number to analyze range for
// assertions - the assertions to use
// budget - the remaining budget for recursive analysis
// visited - the set of value numbers already visited in the current search
// path to prevent infinite recursion
//
// Return Value:
// The computed range
//
Range RangeCheck::GetRangeFromAssertionsWorker(
Compiler* comp, ValueNum num, ASSERT_VALARG_TP assertions, int budget, ValueNumStore::SmallValueNumSet* visited)
{
assert(num != ValueNumStore::NoVN);
var_types vnType = comp->vnStore->TypeOfVN(num);
Range result = GetRangeFromType(vnType);
if (budget <= 0)
{
return result;
}
if (varTypeIsGC(vnType))
{
#if TARGET_64BIT
return Limit(Limit::keUnknown);
#else
// On 32-bit targets TYP_BYREF/TYP_REF and TYP_INT are all 4 bytes, so the JIT can
// legally store a byref-valued expression (e.g. LCL_ADDR) into an int-typed local.
// The local itself is TYP_INT, but its VN is a TYP_BYREF function like PtrToLoc.
// The PhiDef visitor below recurses into reaching VNs, so a BYREF VN can show up
// here even though our public callers only pass us int-typed trees.
// We have no useful integer range to derive from a pointer, so just give up.
return GetRangeFromType(TYP_INT);
#endif
}
//
// First, let's see if we can tighten the range based on VN information.
//
// If it's a constant, it's already as tight as it can get.
if (comp->vnStore->IsVNConstant(num))
{
int cns;
if (comp->vnStore->IsVNIntegralConstant(num, &cns))
{
return Range(Limit(Limit::keConstant, cns));
}
else
{
// TODO: We could return `0, keUnknown` if the constant is known positive
// but this would require more handling in other places to take advantage of.
return Limit(Limit::keUnknown);
}
}
VNFuncApp funcApp;
if (comp->vnStore->GetVNFunc(num, &funcApp))
{
#if defined(FEATURE_HW_INTRINSICS)
// Some HWIntrinsic functions have known result ranges that can be queried via flags.
NamedIntrinsic id;
unsigned simdSize;
var_types simdBaseType;
if (comp->vnStore->IsVNHWIntrinsicFunc(num, &funcApp, &id, &simdSize, &simdBaseType))
{
if (HWIntrinsicInfo::ReturnsBoolean(id))
{
// A boolean [0, 1]
result.lLimit = Limit(Limit::keConstant, 0);
result.uLimit = Limit(Limit::keConstant, 1);
}
else if (HWIntrinsicInfo::ReturnsScalarT(id) && varTypeIsSmall(simdBaseType))
{
// We are extracting a value of the base types width and sign
result = GetRangeFromType(simdBaseType);
}
}
#endif // FEATURE_HW_INTRINSICS
switch (funcApp.GetFunc())
{
case VNF_Cast:
{
var_types castToType;
bool srcIsUnsigned;
comp->vnStore->GetCastOperFromVN(funcApp.GetArg(1), &castToType, &srcIsUnsigned);
ValueNum arg0VN = funcApp.GetArg(0);
var_types arg0Typ = comp->vnStore->TypeOfVN(arg0VN);
var_types castFromType = srcIsUnsigned ? varTypeToUnsigned(arg0Typ) : arg0Typ;
// A zero-extending cast (srcIsUnsigned) of a signed sub-int source is unsound to bound by the
// small unsigned type: small signed types are held sign-extended in their int-width stack slot,
// so the zero-extension applies to that wider value. E.g. (uint)(sbyte)(-1) == 0xFFFFFFFF, which
// is far outside the [0..255] range of the unsigned small type. Use the unsigned form of the
// actual (int) source width so we fall back to an unknown range instead of an unsound one.
if (srcIsUnsigned && varTypeIsSigned(arg0Typ) && (genTypeSize(arg0Typ) < genTypeSize(TYP_INT)))
{
castFromType = varTypeToUnsigned(genActualType(arg0Typ));
}
// Widening preserves the source value (so we can reuse the source range) UNLESS we widen a
// signed source into a smaller-than-int unsigned type (e.g. (ushort)(sbyte)). There, negative
// source values are zero-extended into large positive values (e.g. (ushort)(-1) == 65535), so
// the source range no longer bounds the result.
bool widensToSmallUnsigned = varTypeIsUnsigned(castToType) &&
(genTypeSize(castToType) < genTypeSize(TYP_INT)) &&
varTypeIsSigned(castFromType);
if ((genTypeSize(castFromType) < genTypeSize(castToType)) && !widensToSmallUnsigned)
{
// We're going from a small type to a large type
// and so regardless of whether we zero or sign-extend
// the value is preserved within the confines of its
// original input for the destination, i.e. it always
// passes the FitsIn<fromType> check.
result = GetRangeFromType(castFromType);
}
else
{
// We're either going from a big type to a small type
// or between signed and unsigned types of the same size
// so we want to use toType as the range.
result = GetRangeFromType((castToType == TYP_UINT) ? TYP_INT : castToType);
}
// Now see if we can do better by looking at the cast source.
// if its range is within the castTo range, we can use that (and the cast is basically a no-op).
Range castOpRange = GetRangeFromAssertionsWorker(comp, arg0VN, assertions, --budget, visited);
if (castOpRange.IsConstantRange())
{
if (!result.IsConstantRange())
{
if (!srcIsUnsigned || (castOpRange.LowerLimit().GetConstant() >= 0))
{
result = castOpRange;
}
}
else if ((castOpRange.LowerLimit().GetConstant() >= result.LowerLimit().GetConstant()) &&
(castOpRange.UpperLimit().GetConstant() <= result.UpperLimit().GetConstant()))
{
result = castOpRange;
}
}
}
break;
case VNF_NEG:
{
Range r1 = GetRangeFromAssertionsWorker(comp, funcApp.GetArg(0), assertions, --budget, visited);
Range unaryOpResult = RangeOps::Negate(r1);
// We can use the result only if it never overflows.
result = unaryOpResult.IsConstantRange() ? unaryOpResult : result;
break;
}
case VNF_LSH:
case VNF_ADD:
case VNF_MUL:
case VNF_SUB:
case VNF_AND:
case VNF_OR:
case VNF_RSH:
case VNF_RSZ:
case VNF_UMOD:
case VNF_UDIV:
{
// Get ranges of both operands and perform the same operation on the ranges.
Range r1 = GetRangeFromAssertionsWorker(comp, funcApp.GetArg(0), assertions, --budget, visited);
Range r2 = GetRangeFromAssertionsWorker(comp, funcApp.GetArg(1), assertions, --budget, visited);
Range binOpResult = Range(Limit(Limit::keUnknown));
switch (funcApp.GetFunc())
{
case VNF_ADD:
binOpResult = RangeOps::Add(r1, r2);
break;
case VNF_MUL:
binOpResult = RangeOps::Multiply(r1, r2);
break;
case VNF_SUB:
binOpResult = RangeOps::Subtract(r1, r2);
break;
case VNF_AND:
binOpResult = RangeOps::And(r1, r2);
break;
case VNF_OR:
binOpResult = RangeOps::Or(r1, r2);
break;
case VNF_LSH:
{
if (varTypeIsLong(vnType))
{
// We can't handle LSH for long since we don't know the state of the upper 32-bits
return Limit(Limit::keUnknown);
}
binOpResult = RangeOps::ShiftLeft(r1, r2);
break;
}
case VNF_RSH:
{
if (varTypeIsLong(vnType))
{
int shiftAmount;
if (r2.IsSingleValueConstant(&shiftAmount) && (shiftAmount >= 32) && (shiftAmount < 64))
{
// The upper 33-bits will all match post shift, so we are within [INT32_MIN, INT32_MAX]
binOpResult = GetRangeFromType(TYP_INT);
break;
}
else
{
return Range(Limit::keUnknown);
}
}
binOpResult = RangeOps::ShiftRight(r1, r2, /*logical*/ false);
break;
}
case VNF_RSZ:
{
if (varTypeIsLong(vnType))
{
int shiftAmount;
if (r2.IsSingleValueConstant(&shiftAmount) && (shiftAmount >= 33) && (shiftAmount < 64))
{
// The upper 33-bits must all be zero post shift, so we are within [0, INT32_MAX]
// and can further reduce based on the remaining shift amount. This is notably one
// higher than RSH since we'd otherwise get a value within [INT32_MAX + 1, UINT32_MAX]
r1 = Range(Limit(Limit::keConstant, 0), Limit(Limit::keConstant, INT32_MAX));
r2 = Range(Limit(Limit::keConstant, shiftAmount - 33));
}
else
{
return Range(Limit::keUnknown);
}
}
binOpResult = RangeOps::ShiftRight(r1, r2, /*logical*/ true);
break;
}
case VNF_UMOD:
binOpResult = RangeOps::UnsignedMod(r1, r2);
break;
case VNF_UDIV:
binOpResult = RangeOps::UnsignedDivide(r1, r2);
break;
default:
unreached();
}
// We can use the result only if it never overflows.
result = binOpResult.IsConstantRange() ? binOpResult : result;
break;
}
case VNF_MDARR_LENGTH:
case VNF_ARR_LENGTH:
result.lLimit = Limit(Limit::keConstant, 0);
result.uLimit = Limit(Limit::keConstant, CORINFO_Array_MaxLength);
break;
case VNF_GT:
case VNF_GT_UN:
case VNF_GE:
case VNF_GE_UN:
case VNF_LT:
case VNF_LT_UN:
case VNF_LE:
case VNF_LE_UN:
case VNF_EQ:
case VNF_NE:
{
// These always return 0 or 1 (range is [0..1])
result.lLimit = Limit(Limit::keConstant, 0);
result.uLimit = Limit(Limit::keConstant, 1);
// But maybe we can do better and determine if they are always true or always false,
// hence, return [1..1] or [0..0]
Range r1 = GetRangeFromAssertionsWorker(comp, funcApp.GetArg(0), assertions, --budget, visited);
Range r2 = GetRangeFromAssertionsWorker(comp, funcApp.GetArg(1), assertions, --budget, visited);
if (r1.IsConstantRange() && r2.IsConstantRange())
{
bool isUnsigned = true;
genTreeOps cmpOper;
// Normalize the unsigned comparison operators.
if (funcApp.FuncIs(VNF_GT_UN))
cmpOper = GT_GT;
else if (funcApp.FuncIs(VNF_GE_UN))
cmpOper = GT_GE;
else if (funcApp.FuncIs(VNF_LT_UN))
cmpOper = GT_LT;
else if (funcApp.FuncIs(VNF_LE_UN))
cmpOper = GT_LE;
else
{
isUnsigned = false;
cmpOper = static_cast<genTreeOps>(funcApp.GetFunc());
}
result = RangeOps::EvalRelop(cmpOper, isUnsigned, r1, r2);
// Example: "(uint)(length - 4) > (uint)length" folds to false when
// length >= 4 (the typical Slice(length - cns) bounds check).
if (!result.IsSingleValueConstant() && (genActualType(vnType) == TYP_INT))
{
ValueNum op1VN = funcApp.GetArg(0);
ValueNum op2VN = funcApp.GetArg(1);
ValueNum addOpVN;
int addCns;
if (comp->vnStore->IsVNBinFuncWithConst(op1VN, VNF_ADD, &addOpVN, &addCns) &&
(addOpVN == op2VN) && (addCns < 0) && (addCns > INT32_MIN))
{
if (r2.LowerLimit().IsConstant() && (r2.LowerLimit().GetConstant() >= -addCns))
{
// ADD(A, K) < A is proven (both signed and unsigned).
switch (cmpOper)
{
case GT_LT:
case GT_LE:
case GT_NE:
result = Range(Limit(Limit::keConstant, 1));
break;
case GT_GT:
case GT_GE:
case GT_EQ:
result = Range(Limit(Limit::keConstant, 0));
break;
default:
break;
}
}
}
}
}
break;
}
#if defined(FEATURE_HW_INTRINSICS)
case VNF_HWI_Vector_ExtractMostSignificantBits:
#if defined(TARGET_XARCH)
case VNF_HWI_X86Base_MoveMask:
case VNF_HWI_AVX_MoveMask:
case VNF_HWI_AVX2_MoveMask:
case VNF_HWI_AVX512_MoveMask:
#endif
{
// We have 1 bit per element, remaining upper bits are 0
var_types simdBaseType;
uint32_t simdSize = comp->vnStore->GetVNHWIntrinsicSizeAndBaseType(funcApp, &simdBaseType);
size_t elementSize = genTypeSize(simdBaseType);
size_t elementCount = simdSize / elementSize;
if (elementCount <= 16)
{
result.lLimit = Limit(Limit::keConstant, 0);
result.uLimit = Limit(Limit::keConstant, (1 << elementCount) - 1);
}
else
{
// TODO: We could return `0, keUnknown` for `elementCount == 32` if the result is TYP_LONG
// but this would require more handling in other places to take advantage of.
}
break;
}
#if defined(TARGET_XARCH)
case VNF_HWI_AVX2_LeadingZeroCount:
case VNF_HWI_AVX2_TrailingZeroCount:
case VNF_HWI_AVX2_X64_LeadingZeroCount:
case VNF_HWI_AVX2_X64_TrailingZeroCount:
case VNF_HWI_X86Base_PopCount:
case VNF_HWI_X86Base_X64_PopCount:
#elif defined(TARGET_ARM64)
case VNF_HWI_ArmBase_LeadingZeroCount:
case VNF_HWI_ArmBase_Arm64_LeadingZeroCount:
case VNF_HWI_ArmBase_Arm64_LeadingSignCount:
#endif
#endif
case VNF_LeadingZeroCount:
case VNF_TrailingZeroCount:
case VNF_PopCount:
{
// The actual range is [0..32] or [0..64]
var_types baseType = comp->vnStore->TypeOfVN(funcApp.GetArg(0));
result.lLimit = Limit(Limit::keConstant, 0);
result.uLimit = Limit(Limit::keConstant, varTypeIsLong(baseType) ? 64 : 32);
break;
}
default:
break;
}
}
if (result.IsSingleValueConstant())
{
// If it was evaluated to a single constant value by now, return it, we can't do better anyway.
return result;
}
Range phiRange = Range(Limit(Limit::keUndef));
auto visitor = [comp, vnType, &phiRange, &budget, visited](ValueNum reachingVN, ASSERT_TP reachingAssertions) {
// call GetRangeFromAssertionsWorker for each reaching VN using reachingAssertions
Range edgeRange = GetRangeFromType(vnType);
if (reachingVN != ValueNumStore::NoVN)
{
edgeRange = GetRangeFromAssertionsWorker(comp, reachingVN, reachingAssertions, --budget, visited);
}
// If phiRange is not yet set, set it to the first edgeRange
// else merge it with the new edgeRange. Example: [10..100] U [50..150] = [10..150]
phiRange = phiRange.IsUndef() ? edgeRange : RangeOps::Merge(phiRange, edgeRange, false);
// if any edge produces a non-constant range, we abort further processing
// We also give up if the range is full, as it won't help tighten the result.
if (edgeRange.IsConstantRange() && !edgeRange.IsFullRange())