-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathoptimizebools.cpp
2029 lines (1791 loc) · 67.3 KB
/
optimizebools.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 Optimizer XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
/*****************************************************************************/
//-----------------------------------------------------------------------------
// OptTestInfo: Member of OptBoolsDsc struct used to test if a GT_JTRUE or return node
// is a boolean comparison
//
struct OptTestInfo
{
Statement* testStmt; // Last statement of the basic block
GenTree* testTree; // The root node of the testStmt (GT_JTRUE or GT_RETURN/GT_SWIFT_ERROR_RET).
GenTree* compTree; // The compare node (i.e. GT_EQ or GT_NE node) of the testTree
bool isBool; // If the compTree is boolean expression
GenTree* GetTestOp() const
{
assert(testTree != nullptr);
if (testTree->OperIs(GT_JTRUE))
{
return testTree->gtGetOp1();
}
assert(testTree->OperIs(GT_RETURN, GT_SWIFT_ERROR_RET));
return testTree->AsOp()->GetReturnValue();
}
void SetTestOp(GenTree* const op)
{
assert(testTree != nullptr);
if (testTree->OperIs(GT_JTRUE))
{
testTree->AsOp()->gtOp1 = op;
}
else
{
assert(testTree->OperIs(GT_RETURN, GT_SWIFT_ERROR_RET));
testTree->AsOp()->SetReturnValue(op);
}
}
};
//-----------------------------------------------------------------------------
// OptBoolsDsc: Descriptor used for Boolean Optimization
//
class OptBoolsDsc
{
public:
OptBoolsDsc(BasicBlock* b1, BasicBlock* b2, Compiler* comp)
{
m_b1 = b1;
m_b2 = b2;
m_b3 = nullptr;
m_comp = comp;
}
private:
BasicBlock* m_b1; // The first basic block with the BBJ_COND conditional jump type
BasicBlock* m_b2; // The next basic block of m_b1. Either BBJ_COND or BBJ_RETURN type
BasicBlock* m_b3; // m_b1's target block. Null if m_b2 is not a return block.
Compiler* m_comp; // The pointer to the Compiler instance
OptTestInfo m_testInfo1; // The first test info
OptTestInfo m_testInfo2; // The second test info
GenTree* m_t3; // The root node of the first statement of m_b3
GenTree* m_c1; // The first operand of m_testInfo1.compTree
GenTree* m_c2; // The first operand of m_testInfo2.compTree
bool m_sameTarget; // if m_b1 and m_b2 jumps to the same destination
genTreeOps m_foldOp; // The fold operator (e.g., GT_AND or GT_OR)
var_types m_foldType; // The type of the folded tree
genTreeOps m_cmpOp; // The comparison operator (e.g., GT_EQ or GT_NE)
public:
bool optOptimizeBoolsCondBlock();
bool optOptimizeCompareChainCondBlock();
bool optOptimizeRangeTests();
bool optOptimizeBoolsReturnBlock(BasicBlock* b3);
#ifdef DEBUG
void optOptimizeBoolsGcStress();
#endif
private:
Statement* optOptimizeBoolsChkBlkCond();
GenTree* optIsBoolComp(OptTestInfo* pOptTest);
bool optOptimizeBoolsChkTypeCostCond();
void optOptimizeBoolsUpdateTrees();
bool FindCompareChain(GenTree* condition, bool* isTestCondition);
};
//-----------------------------------------------------------------------------
// optOptimizeBoolsCondBlock: Optimize boolean when bbKind of both m_b1 and m_b2 are BBJ_COND
//
// Returns:
// true if boolean optimization is done and m_b1 and m_b2 are folded into m_b1, else false.
//
// Notes:
// m_b1 and m_b2 are set on entry.
//
// Case 1: if b1->TargetIs(b2->GetTarget()), it transforms
// B1 : brtrue(t1, Bx)
// B2 : brtrue(t2, Bx)
// B3 :
// to
// B1 : brtrue(t1|t2, BX)
// B3 :
//
// For example, (x == 0 && y == 0 && z == 0) generates
// B1: GT_JTRUE (BBJ_COND), jump to B4
// B2: GT_JTRUE (BBJ_COND), jump to B4
// B3: GT_RETURN/GT_SWIFT_ERROR_RET (BBJ_RETURN)
// B4: GT_RETURN/GT_SWIFT_ERROR_RET (BBJ_RETURN)
// and B1 and B2 are folded into B1:
// B1: GT_JTRUE (BBJ_COND), jump to B4
// B3: GT_RETURN/GT_SWIFT_ERROR_RET (BBJ_RETURN)
// B4: GT_RETURN/GT_SWIFT_ERROR_RET (BBJ_RETURN)
//
// Case 2: if B2->FalseTargetIs(B1->GetTarget()), it transforms
// B1 : brtrue(t1, B3)
// B2 : brtrue(t2, Bx)
// B3 :
// to
// B1 : brtrue((!t1) && t2, Bx)
// B3 :
//
bool OptBoolsDsc::optOptimizeBoolsCondBlock()
{
assert(m_b1 != nullptr && m_b2 != nullptr && m_b3 == nullptr);
// Check if m_b1 and m_b2 jump to the same target and get back pointers to m_testInfo1 and t2 tree nodes
m_t3 = nullptr;
// Check if m_b1 and m_b2 have the same target
if (m_b1->TrueTargetIs(m_b2->GetTrueTarget()))
{
// Given the following sequence of blocks :
// B1: brtrue(t1, BX)
// B2: brtrue(t2, BX)
// B3:
// we will try to fold it to :
// B1: brtrue(t1|t2, BX)
// B3:
m_sameTarget = true;
}
else if (m_b2->FalseTargetIs(m_b1->GetTrueTarget()))
{
// Given the following sequence of blocks :
// B1: brtrue(t1, B3)
// B2: brtrue(t2, BX)
// B3:
// we will try to fold it to :
// B1: brtrue((!t1)&&t2, BX)
// B3:
m_sameTarget = false;
}
else
{
return false;
}
Statement* const s1 = optOptimizeBoolsChkBlkCond();
if (s1 == nullptr)
{
return false;
}
// Find the branch conditions of m_b1 and m_b2
m_c1 = optIsBoolComp(&m_testInfo1);
if (m_c1 == nullptr)
{
return false;
}
m_c2 = optIsBoolComp(&m_testInfo2);
if (m_c2 == nullptr)
{
return false;
}
// Find the type and cost conditions of m_testInfo1 and m_testInfo2
if (!optOptimizeBoolsChkTypeCostCond())
{
return false;
}
// Get the fold operator and the comparison operator
genTreeOps foldOp;
genTreeOps cmpOp;
var_types foldType = genActualType(m_c1);
if (varTypeIsGC(foldType))
{
foldType = TYP_I_IMPL;
}
assert(m_testInfo1.compTree->OperIs(GT_EQ, GT_NE, GT_LT, GT_GT, GT_GE, GT_LE));
if (m_sameTarget)
{
if (m_c1->gtOper == GT_LCL_VAR && m_c2->gtOper == GT_LCL_VAR &&
m_c1->AsLclVarCommon()->GetLclNum() == m_c2->AsLclVarCommon()->GetLclNum())
{
if ((m_testInfo1.compTree->gtOper == GT_LT && m_testInfo2.compTree->gtOper == GT_EQ) ||
(m_testInfo1.compTree->gtOper == GT_EQ && m_testInfo2.compTree->gtOper == GT_LT))
{
// Case: t1:c1<0 t2:c1==0
// So we will branch to BX if c1<=0
//
// Case: t1:c1==0 t2:c1<0
// So we will branch to BX if c1<=0
cmpOp = GT_LE;
}
else if ((m_testInfo1.compTree->gtOper == GT_GT && m_testInfo2.compTree->gtOper == GT_EQ) ||
(m_testInfo1.compTree->gtOper == GT_EQ && m_testInfo2.compTree->gtOper == GT_GT))
{
// Case: t1:c1>0 t2:c1==0
// So we will branch to BX if c1>=0
//
// Case: t1:c1==0 t2:c1>0
// So we will branch to BX if c1>=0
cmpOp = GT_GE;
}
else
{
return false;
}
foldOp = GT_NONE;
}
else if (m_testInfo1.compTree->gtOper == GT_EQ && m_testInfo2.compTree->gtOper == GT_EQ)
{
// t1:c1==0 t2:c2==0 ==> Branch to BX if either value is 0
// So we will branch to BX if (c1&c2)==0
foldOp = GT_AND;
cmpOp = GT_EQ;
}
else if (m_testInfo1.compTree->gtOper == GT_LT && m_testInfo2.compTree->gtOper == GT_LT &&
(!m_testInfo1.GetTestOp()->IsUnsigned() && !m_testInfo2.GetTestOp()->IsUnsigned()))
{
// t1:c1<0 t2:c2<0 ==> Branch to BX if either value < 0
// So we will branch to BX if (c1|c2)<0
foldOp = GT_OR;
cmpOp = GT_LT;
}
else if (m_testInfo1.compTree->gtOper == GT_NE && m_testInfo2.compTree->gtOper == GT_NE)
{
// t1:c1!=0 t2:c2!=0 ==> Branch to BX if either value is non-0
// So we will branch to BX if (c1|c2)!=0
foldOp = GT_OR;
cmpOp = GT_NE;
}
else
{
return false;
}
}
else
{
if (m_c1->gtOper == GT_LCL_VAR && m_c2->gtOper == GT_LCL_VAR &&
m_c1->AsLclVarCommon()->GetLclNum() == m_c2->AsLclVarCommon()->GetLclNum())
{
if ((m_testInfo1.compTree->gtOper == GT_LT && m_testInfo2.compTree->gtOper == GT_NE) ||
(m_testInfo1.compTree->gtOper == GT_EQ && m_testInfo2.compTree->gtOper == GT_GE))
{
// Case: t1:c1<0 t2:c1!=0
// So we will branch to BX if c1>0
//
// Case: t1:c1==0 t2:c1>=0
// So we will branch to BX if c1>0
cmpOp = GT_GT;
}
else if ((m_testInfo1.compTree->gtOper == GT_GT && m_testInfo2.compTree->gtOper == GT_NE) ||
(m_testInfo1.compTree->gtOper == GT_EQ && m_testInfo2.compTree->gtOper == GT_LE))
{
// Case: t1:c1>0 t2:c1!=0
// So we will branch to BX if c1<0
//
// Case: t1:c1==0 t2:c1<=0
// So we will branch to BX if c1<0
cmpOp = GT_LT;
}
else
{
return false;
}
foldOp = GT_NONE;
}
else if (m_testInfo1.compTree->gtOper == GT_EQ && m_testInfo2.compTree->gtOper == GT_NE)
{
// t1:c1==0 t2:c2!=0 ==> Branch to BX if both values are non-0
// So we will branch to BX if (c1&c2)!=0
foldOp = GT_AND;
cmpOp = GT_NE;
}
else if (m_testInfo1.compTree->gtOper == GT_LT && m_testInfo2.compTree->gtOper == GT_GE &&
(!m_testInfo1.GetTestOp()->IsUnsigned() && !m_testInfo2.GetTestOp()->IsUnsigned()))
{
// t1:c1<0 t2:c2>=0 ==> Branch to BX if both values >= 0
// So we will branch to BX if (c1|c2)>=0
foldOp = GT_OR;
cmpOp = GT_GE;
}
else if (m_testInfo1.compTree->gtOper == GT_NE && m_testInfo2.compTree->gtOper == GT_EQ)
{
// t1:c1!=0 t2:c2==0 ==> Branch to BX if both values are 0
// So we will branch to BX if (c1|c2)==0
foldOp = GT_OR;
cmpOp = GT_EQ;
}
else
{
return false;
}
}
// Anding requires both values to be 0 or 1
if ((foldOp == GT_AND) && (!m_testInfo1.isBool || !m_testInfo2.isBool))
{
return false;
}
//
// Now update the trees
//
m_foldOp = foldOp;
m_foldType = foldType;
m_cmpOp = cmpOp;
optOptimizeBoolsUpdateTrees();
#ifdef DEBUG
if (m_comp->verbose)
{
printf("Folded %sboolean conditions of " FMT_BB " and " FMT_BB " to :\n", m_c2->OperIsLeaf() ? "" : "non-leaf ",
m_b1->bbNum, m_b2->bbNum);
m_comp->gtDispStmt(s1);
printf("\n");
}
#endif
// Return true to continue the bool optimization for the rest of the BB chain
return true;
}
//-----------------------------------------------------------------------------
// FindCompareChain: Check if the given condition is a compare chain.
//
// Arguments:
// condition: Condition to check.
// isTestCondition: Returns true if condition is but is not a compare chain.
//
// Returns:
// true if chain optimization is a compare chain.
//
// Assumptions:
// m_b1 and m_b2 are set on entry.
//
bool OptBoolsDsc::FindCompareChain(GenTree* condition, bool* isTestCondition)
{
GenTree* condOp1 = condition->gtGetOp1();
GenTree* condOp2 = condition->gtGetOp2();
*isTestCondition = false;
if (condition->OperIs(GT_EQ, GT_NE) && condOp2->IsIntegralConst())
{
ssize_t condOp2Value = condOp2->AsIntCon()->IconValue();
if (condOp2Value == 0)
{
// Found a EQ/NE(...,0). Does it contain a compare chain (ie - conditions that have
// previously been combined by optOptimizeCompareChainCondBlock) or is it a test condition
// that will be optimised to cbz/cbnz during lowering?
if (condOp1->OperIs(GT_AND, GT_OR))
{
// Check that the second operand of AND/OR ends with a compare operation, as this will be
// the condition the new link in the chain will connect with.
if (condOp1->gtGetOp2()->OperIsCmpCompare() && varTypeIsIntegralOrI(condOp1->gtGetOp2()->gtGetOp1()))
{
return true;
}
}
*isTestCondition = true;
}
else if (condOp1->OperIs(GT_AND) && isPow2(static_cast<target_size_t>(condOp2Value)) &&
condOp1->gtGetOp2()->IsIntegralConst(condOp2Value))
{
// Found a EQ/NE(AND(...,n),n) which will be optimized to tbz/tbnz during lowering.
*isTestCondition = true;
}
}
return false;
}
//------------------------------------------------------------------------------
// GetIntersection: Given two ranges, return true if they intersect and form a closed range.
// Examples:
// >10 and <=20 -> [11,20]
// >10 and >100 -> false
// <10 and >10 -> false
//
// Arguments:
// type - The type of the compare nodes.
// cmp1 - The first compare node.
// cmp2 - The second compare node.
// cns1 - The constant value of the first compare node (always RHS).
// cns2 - The constant value of the second compare node (always RHS).
// pRangeStart - [OUT] The start of the intersection range (inclusive).
// pRangeEnd - [OUT] The end of the intersection range (inclusive).
//
// Returns:
// true if the ranges intersect and form a closed range.
//
static bool GetIntersection(var_types type,
genTreeOps cmp1,
genTreeOps cmp2,
ssize_t cns1,
ssize_t cns2,
ssize_t* pRangeStart,
ssize_t* pRangeEnd)
{
if ((cns1 < 0) || (cns2 < 0))
{
// We don't yet support negative ranges.
return false;
}
// Convert to a canonical form with GT_GE or GT_LE (inclusive).
auto normalize = [](genTreeOps* cmp, ssize_t* cns) {
if (*cmp == GT_GT)
{
// "X > cns" -> "X >= cns + 1"
*cns = *cns + 1;
*cmp = GT_GE;
}
if (*cmp == GT_LT)
{
// "X < cns" -> "X <= cns - 1"
*cns = *cns - 1;
*cmp = GT_LE;
}
// whether these overflow or not is checked below.
};
normalize(&cmp1, &cns1);
normalize(&cmp2, &cns2);
if (cmp1 == cmp2)
{
// Ranges have the same direction (we don't yet support that yet).
return false;
}
if (cmp1 == GT_GE)
{
*pRangeStart = cns1;
*pRangeEnd = cns2;
}
else
{
assert(cmp1 == GT_LE);
*pRangeStart = cns2;
*pRangeEnd = cns1;
}
if ((*pRangeStart >= *pRangeEnd) || (*pRangeStart < 0) || (*pRangeEnd < 0) || !FitsIn(type, *pRangeStart) ||
!FitsIn(type, *pRangeEnd))
{
// TODO: If ranges don't intersect we might be able to fold the condition to true/false.
// Also, check again if any of the ranges are negative (in case of overflow after normalization)
// and fits into the given type.
return false;
}
return true;
}
//------------------------------------------------------------------------------
// IsConstantRangeTest: Does the given compare node represent a constant range test? E.g.
// "X relop CNS" or "CNS relop X" where relop is [<, <=, >, >=]
//
// Arguments:
// tree - compare node
// varNode - [OUT] this will be set to the variable part of the constant range test
// cnsNode - [OUT] this will be set to the constant part of the constant range test
// cmp - [OUT] this will be set to a normalized compare operator so that the constant
// is always on the right hand side of the compare.
//
// Returns:
// true if the compare node represents a constant range test.
//
bool IsConstantRangeTest(GenTreeOp* tree, GenTree** varNode, GenTreeIntCon** cnsNode, genTreeOps* cmp)
{
if (tree->OperIs(GT_LE, GT_LT, GT_GE, GT_GT) && !tree->IsUnsigned())
{
GenTree* op1 = tree->gtGetOp1();
GenTree* op2 = tree->gtGetOp2();
if (varTypeIsIntegral(op1) && varTypeIsIntegral(op2) && op1->TypeIs(op2->TypeGet()))
{
if (op2->IsCnsIntOrI())
{
// X relop CNS
*varNode = op1;
*cnsNode = op2->AsIntCon();
*cmp = tree->OperGet();
return true;
}
if (op1->IsCnsIntOrI())
{
// CNS relop X
*varNode = op2;
*cnsNode = op1->AsIntCon();
// Normalize to "X relop CNS"
*cmp = GenTree::SwapRelop(tree->OperGet());
return true;
}
}
}
return false;
}
//------------------------------------------------------------------------------
// FoldRangeTests: Given two compare nodes (cmp1 && cmp2) where cmp1 is X >= 0
// and cmp2 is X < NN (NeverNegative), try to fold the range test into a single
// X u< NN (unsigned) compare node.
//
// Arguments:
// compiler - compiler instance
// cmp1 - first compare node
// cmp1IsReversed - true if cmp1 is in fact reversed
// cmp2 - second compare node
// cmp2IsReversed - true if cmp2 is in fact reversed
//
// Returns:
// true if cmp1 now represents the folded range check and cmp2 can be removed.
//
bool FoldNeverNegativeRangeTest(
Compiler* comp, GenTreeOp* cmp1, bool cmp1IsReversed, GenTreeOp* cmp2, bool cmp2IsReversed)
{
GenTree* var1Node;
GenTreeIntCon* cns1Node;
genTreeOps cmp1Op;
// First cmp has to be "X >= 0" (or "0 <= X")
// TODO: handle "X < NN && X >= 0" (where the 2nd comparison is the lower bound)
// It seems to be a rare case, so we don't handle it for now.
if (!IsConstantRangeTest(cmp1, &var1Node, &cns1Node, &cmp1Op))
{
return false;
}
// Now, reverse the comparison if necessary depending on cmp1IsReversed and cmp2IsReversed
// so we'll get a canonical form of "X >= 0 && X </<= NN"
cmp1Op = cmp1IsReversed ? GenTree::ReverseRelop(cmp1Op) : cmp1Op;
genTreeOps cmp2Op = cmp2IsReversed ? GenTree::ReverseRelop(cmp2->OperGet()) : cmp2->OperGet();
if ((cmp1Op != GT_GE) || (!cns1Node->IsIntegralConst(0)))
{
// Lower bound check has to be "X >= 0".
// We already re-ordered the comparison so that the constant is always on the right side.
return false;
}
// Upper bound check has to be "X relop NN" or "NN relop X" (NN = NeverNegative)
// We allow var1Node to be a GT_COMMA node, so we need to call gtEffectiveVal() to get the actual variable
// since it's guaranteed to be evaluated first.
GenTree* upperBound;
if (cmp2->gtGetOp1()->OperIs(GT_LCL_VAR, GT_LCL_FLD) &&
GenTree::Compare(var1Node->gtEffectiveVal(), cmp2->gtGetOp1()))
{
// "X relop NN"
upperBound = cmp2->gtGetOp2();
}
else if (cmp2->gtGetOp2()->OperIs(GT_LCL_VAR, GT_LCL_FLD) &&
GenTree::Compare(var1Node->gtEffectiveVal(), cmp2->gtGetOp2()))
{
// "NN relop X"
upperBound = cmp2->gtGetOp1();
// Normalize to "X relop NN"
cmp2Op = GenTree::SwapRelop(cmp2Op);
}
else
{
return false;
}
// Check that our upper bound is known to be never negative (e.g. GT_ARR_LENGTH or Span.Length, etc.)
if (!upperBound->IsNeverNegative(comp) || !upperBound->TypeIs(var1Node->TypeGet()))
{
return false;
}
if ((upperBound->gtFlags & GTF_SIDE_EFFECT) != 0)
{
// We can't fold "X >= 0 && X < NN" to "X u< NN" if NN has side effects.
return false;
}
if ((cmp2Op != GT_LT) && (cmp2Op != GT_LE))
{
// Upper bound check has to be "X < NN" or "X <= NN" (normalized form).
return false;
}
cmp1->gtOp1 = var1Node;
cmp1->gtOp2 = upperBound;
cmp1->SetOper(cmp2IsReversed ? GenTree::ReverseRelop(cmp2Op) : cmp2Op);
cmp1->SetUnsigned();
return true;
}
//------------------------------------------------------------------------------
// FoldRangeTests: Given two compare nodes (cmp1 && cmp2) that represent a range check,
// fold them into a single compare node if possible, e.g.:
// 1) "X >= 10 && X <= 100" -> "(X - 10) u<= 90"
// 2) "X >= 0 && X <= 100" -> "X u<= 100"
// where 'u' stands for unsigned comparison. cmp1 is used as the target node for folding.
// It's also guaranteed to be first in the execution order (so can allow some side effects).
//
// Arguments:
// compiler - compiler instance
// cmp1 - first compare node
// cmp1IsReversed - true if cmp1 is in fact reversed
// cmp2 - second compare node
// cmp2IsReversed - true if cmp2 is in fact reversed
//
// Returns:
// true if cmp1 now represents the folded range check and cmp2 can be removed.
//
bool FoldRangeTests(Compiler* comp, GenTreeOp* cmp1, bool cmp1IsReversed, GenTreeOp* cmp2, bool cmp2IsReversed)
{
GenTree* var1Node;
GenTree* var2Node;
GenTreeIntCon* cns1Node;
GenTreeIntCon* cns2Node;
genTreeOps cmp1Op;
genTreeOps cmp2Op;
// Make sure both conditions are constant range checks, e.g. "X > CNS"
if (!IsConstantRangeTest(cmp1, &var1Node, &cns1Node, &cmp1Op) ||
!IsConstantRangeTest(cmp2, &var2Node, &cns2Node, &cmp2Op))
{
// Give FoldNeverNegativeRangeTest a try if both conditions are not constant range checks.
return FoldNeverNegativeRangeTest(comp, cmp1, cmp1IsReversed, cmp2, cmp2IsReversed);
}
// Reverse the comparisons if necessary so we'll get a canonical form "cond1 == true && cond2 == true" -> InRange.
cmp1Op = cmp1IsReversed ? GenTree::ReverseRelop(cmp1Op) : cmp1Op;
cmp2Op = cmp2IsReversed ? GenTree::ReverseRelop(cmp2Op) : cmp2Op;
// Make sure variables are the same:
if (!var2Node->OperIs(GT_LCL_VAR) || !GenTree::Compare(var1Node->gtEffectiveVal(), var2Node))
{
// Variables don't match in two conditions
// We use gtEffectiveVal() for the first block's variable to ignore COMMAs, e.g.
//
// m_b1:
// * JTRUE void
// \--* LT int
// +--* COMMA int
// | +--* STORE_LCL_VAR int V03 cse0
// | | \--* CAST int <- ushort <- int
// | | \--* LCL_VAR int V01 arg1
// | \--* LCL_VAR int V03 cse0
// \--* CNS_INT int 97
//
// m_b2:
// * JTRUE void
// \--* GT int
// +--* LCL_VAR int V03 cse0
// \--* CNS_INT int 122
//
// For the m_b2 we require the variable to be just a local with no side-effects (hence, no statements)
return false;
}
ssize_t rangeStart;
ssize_t rangeEnd;
if (!GetIntersection(var1Node->TypeGet(), cmp1Op, cmp2Op, cns1Node->IconValue(), cns2Node->IconValue(), &rangeStart,
&rangeEnd))
{
// The range we test via two conditions is not a closed range
// TODO: We should support overlapped ranges here, e.g. "X > 10 && x > 100" -> "X > 100"
return false;
}
assert(rangeStart < rangeEnd);
if (rangeStart == 0)
{
// We don't need to subtract anything, it's already 0-based
cmp1->gtOp1 = var1Node;
}
else
{
// We need to subtract the rangeStartIncl from the variable to make the range start from 0
cmp1->gtOp1 = comp->gtNewOperNode(GT_SUB, var1Node->TypeGet(), var1Node,
comp->gtNewIconNode(rangeStart, var1Node->TypeGet()));
}
cmp1->gtOp2->BashToConst(rangeEnd - rangeStart, var1Node->TypeGet());
cmp1->SetOper(cmp2IsReversed ? GT_GT : GT_LE);
cmp1->SetUnsigned();
return true;
}
//------------------------------------------------------------------------------
// optOptimizeRangeTests : Optimize two conditional blocks representing a constant range test.
// E.g. "X >= 10 && X <= 100" is optimized to "(X - 10) <= 90".
//
// Return Value:
// True if m_b1 and m_b2 are merged.
//
bool OptBoolsDsc::optOptimizeRangeTests()
{
// At this point we have two consecutive conditional blocks (BBJ_COND): m_b1 and m_b2
assert((m_b1 != nullptr) && (m_b2 != nullptr) && (m_b3 == nullptr));
assert(m_b1->KindIs(BBJ_COND) && m_b2->KindIs(BBJ_COND) && m_b1->FalseTargetIs(m_b2));
if (m_b2->isRunRarely())
{
// We don't want to make the first comparison to be slightly slower
// if the 2nd one is rarely executed.
return false;
}
if (!BasicBlock::sameEHRegion(m_b1, m_b2) || m_b2->HasFlag(BBF_DONT_REMOVE))
{
// Conditions aren't in the same EH region or m_b2 can't be removed
return false;
}
if (m_b1->TrueTargetIs(m_b1) || m_b1->TrueTargetIs(m_b2) || m_b2->TrueTargetIs(m_b2) || m_b2->TrueTargetIs(m_b1))
{
// Ignoring weird cases like a condition jumping to itself or when JumpDest == Next
return false;
}
// We're interested in just two shapes for e.g. "X > 10 && X < 100" range test:
//
BasicBlock* notInRangeBb = m_b1->GetTrueTarget();
BasicBlock* inRangeBb;
weight_t inRangeLikelihood = m_b1->GetFalseEdge()->getLikelihood();
if (m_b2->TrueTargetIs(notInRangeBb))
{
// Shape 1: both conditions jump to NotInRange
//
// if (X <= 10)
// goto NotInRange;
//
// if (X >= 100)
// goto NotInRange
//
// InRange:
// ...
inRangeBb = m_b2->GetFalseTarget();
inRangeLikelihood *= m_b2->GetFalseEdge()->getLikelihood();
}
else if (m_b2->FalseTargetIs(notInRangeBb))
{
// Shape 2: 2nd block jumps to InRange
//
// if (X <= 10)
// goto NotInRange;
//
// if (X > 100)
// goto InRange
//
// NotInRange:
// ...
inRangeBb = m_b2->GetTrueTarget();
inRangeLikelihood *= m_b2->GetTrueEdge()->getLikelihood();
}
else
{
// Unknown shape
return false;
}
if (!m_b2->hasSingleStmt() || (m_b2->GetUniquePred(m_comp) != m_b1))
{
// The 2nd block has to be single-statement to avoid side-effects between the two conditions.
// Also, make sure m_b2 has no other predecessors.
return false;
}
// m_b1 and m_b2 are both BBJ_COND blocks with GT_JTRUE(cmp) root nodes
GenTreeOp* cmp1 = m_b1->lastStmt()->GetRootNode()->gtGetOp1()->AsOp();
GenTreeOp* cmp2 = m_b2->lastStmt()->GetRootNode()->gtGetOp1()->AsOp();
// cmp1 is always reversed (see shape1 and shape2 above)
const bool cmp1IsReversed = true;
// cmp2 can be either reversed or not
const bool cmp2IsReversed = m_b2->TrueTargetIs(notInRangeBb);
if (!FoldRangeTests(m_comp, cmp1, cmp1IsReversed, cmp2, cmp2IsReversed))
{
return false;
}
// Re-direct firstBlock to jump to inRangeBb
FlowEdge* const newEdge = m_comp->fgAddRefPred(inRangeBb, m_b1);
FlowEdge* const oldFalseEdge = m_b1->GetFalseEdge();
FlowEdge* const oldTrueEdge = m_b1->GetTrueEdge();
if (!cmp2IsReversed)
{
m_b1->SetFalseEdge(oldTrueEdge);
m_b1->SetTrueEdge(newEdge);
assert(m_b1->TrueTargetIs(inRangeBb));
assert(m_b1->FalseTargetIs(notInRangeBb));
newEdge->setLikelihood(inRangeLikelihood);
oldTrueEdge->setLikelihood(1.0 - inRangeLikelihood);
}
else
{
m_b1->SetFalseEdge(newEdge);
assert(m_b1->TrueTargetIs(notInRangeBb));
assert(m_b1->FalseTargetIs(inRangeBb));
oldTrueEdge->setLikelihood(inRangeLikelihood);
newEdge->setLikelihood(1.0 - inRangeLikelihood);
}
// Remove the 2nd condition block as we no longer need it
m_comp->fgRemoveRefPred(oldFalseEdge);
m_comp->fgRemoveBlock(m_b2, true);
// Update profile
if (m_b1->hasProfileWeight())
{
BasicBlock* const trueTarget = m_b1->GetTrueTarget();
BasicBlock* const falseTarget = m_b1->GetFalseTarget();
trueTarget->setBBProfileWeight(trueTarget->computeIncomingWeight());
falseTarget->setBBProfileWeight(falseTarget->computeIncomingWeight());
if ((trueTarget->NumSucc() > 0) || (falseTarget->NumSucc() > 0))
{
JITDUMP("optOptimizeRangeTests: Profile needs to be propagated through " FMT_BB
"'s successors. Data %s inconsistent.\n",
m_b1->bbNum, m_comp->fgPgoConsistent ? "is now" : "was already");
m_comp->fgPgoConsistent = false;
}
}
Statement* const stmt = m_b1->lastStmt();
m_comp->gtSetStmtInfo(stmt);
m_comp->fgSetStmtSeq(stmt);
m_comp->gtUpdateStmtSideEffects(stmt);
return true;
}
//-----------------------------------------------------------------------------
// optOptimizeCompareChainCondBlock: Create a chain when both m_b1 and m_b2 are BBJ_COND.
//
// Returns:
// true if chain optimization is done and m_b1 and m_b2 are folded into m_b1, else false.
//
// Assumptions:
// m_b1 and m_b2 are set on entry.
//
// Notes:
//
// This aims to reduced the number of conditional jumps by joining cases when multiple
// conditions gate the execution of a block.
//
// Example 1:
// If ( a > b || c == d) { x = y; }
//
// Will be represented in IR as:
//
// ------------ BB01 -> BB03 (cond), succs={BB02,BB03}
// * JTRUE (GT a,b)
//
// ------------ BB02 -> BB04 (cond), preds={BB01} succs={BB03,BB04}
// * JTRUE (NE c,d)
//
// ------------ BB03, preds={BB01, BB02} succs={BB04}
// * STORE_LCL_VAR<x>(y)
//
// These operands will be combined into a single AND in the first block (with the first
// condition inverted), wrapped by the test condition (NE(...,0)). Giving:
//
// ------------ BB01 -> BB03 (cond), succs={BB03,BB04}
// * JTRUE (NE (AND (LE a,b), (NE c,d)), 0)
//
// ------------ BB03, preds={BB01} succs={BB04}
// * STORE_LCL_VAR<x>(y)
//
//
// Example 2:
// If ( a > b && c == d) { x = y; } else { x = z; }
//
// Here the && conditions are connected via an OR. After the pass:
//
// ------------ BB01 -> BB03 (cond), succs={BB03,BB04}
// * JTRUE (NE (OR (LE a,b), (NE c,d)), 0)
//
// ------------ BB03, preds={BB01} succs={BB05}
// * STORE_LCL_VAR<x>(y)
//
// ------------ BB04, preds={BB01} succs={BB05}
// * STORE_LCL_VAR<x>(z)
//
//
// Example 3:
// If ( a > b || c == d || e < f ) { x = y; }
// The first pass of the optimization will combine two of the conditions. The
// second pass will then combine remaining condition the earlier chain.
//
// ------------ BB01 -> BB03 (cond), succs={BB03,BB04}
// * JTRUE (NE (OR ((NE (OR (NE c,d), (GE e,f)), 0), (LE a,b))), 0)
//
// ------------ BB03, preds={BB01} succs={BB04}
// * STORE_LCL_VAR<x>(y)
//
//
// This optimization means that every condition within the IF statement is always evaluated,
// as opposed to stopping at the first positive match.
// Theoretically there is no maximum limit on the size of the generated chain. Therefore cost
// checking is used to limit the maximum number of conditions that can be chained together.
//
bool OptBoolsDsc::optOptimizeCompareChainCondBlock()
{
assert((m_b1 != nullptr) && (m_b2 != nullptr) && (m_b3 == nullptr));
m_t3 = nullptr;
bool foundEndOfOrConditions = false;
if (m_b1->FalseTargetIs(m_b2) && m_b2->FalseTargetIs(m_b1->GetTrueTarget()))
{
// Found the end of two (or more) conditions being ORed together.
// The final condition has been inverted.
foundEndOfOrConditions = true;
}
else if (m_b1->FalseTargetIs(m_b2) && m_b1->TrueTargetIs(m_b2->GetTrueTarget()))
{
// Found two conditions connected together.
}
else
{
return false;
}
Statement* const s1 = optOptimizeBoolsChkBlkCond();
if (s1 == nullptr)
{
return false;
}
Statement* s2 = m_b2->firstStmt();
assert(m_testInfo1.testTree->OperIs(GT_JTRUE));
GenTree* cond1 = m_testInfo1.testTree->gtGetOp1();
assert(m_testInfo2.testTree->OperIs(GT_JTRUE));
GenTree* cond2 = m_testInfo2.testTree->gtGetOp1();
// Ensure both conditions are suitable.
if (!cond1->OperIsCompare() || !cond2->OperIsCompare())
{
return false;
}