-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
fgbasic.cpp
6616 lines (5720 loc) · 243 KB
/
fgbasic.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.
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
// Flowgraph Construction and Maintenance
//------------------------------------------------------------------------------
// fgCanonicalizeFirstBB: Canonicalize the method entry to be dominate all
// blocks in the BB and to be executed exactly once.
//
// Returns:
// Suitable phase status.
//
PhaseStatus Compiler::fgCanonicalizeFirstBB()
{
if (fgFirstBB->hasTryIndex())
{
JITDUMP("Canonicalizing entry because it currently is the beginning of a try region\n");
}
else if (fgFirstBB->bbPreds != nullptr)
{
JITDUMP("Canonicalizing entry because it currently has predecessors\n");
}
else if (opts.compDbgCode && !fgFirstBB->HasFlag(BBF_INTERNAL))
{
// For debug ensure the first BB is internal so as to not conflate user
// code with JIT added code.
JITDUMP("Canonicalizing entry because it currently is a user BB and we are generating debug code\n");
}
else
{
return PhaseStatus::MODIFIED_NOTHING;
}
fgCreateNewInitBB();
return PhaseStatus::MODIFIED_EVERYTHING;
}
//------------------------------------------------------------------------------
// fgCreateNewInitBB:
// Create a new init BB at the beginning of the function.
//
void Compiler::fgCreateNewInitBB()
{
// The first block has an implicit ref count which we must remove. Note the
// ref count could be greater than one, if the first block is targeted by a
// branch.
assert(fgFirstBB->bbRefs >= 1);
fgFirstBB->bbRefs--;
BasicBlock* block = BasicBlock::New(this);
// If we have profile data determine the weight of the initBB BB
//
if (fgFirstBB->hasProfileWeight())
{
// If current entry has preds, sum up those weights
//
weight_t nonEntryWeight = 0;
for (FlowEdge* const edge : fgFirstBB->PredEdges())
{
nonEntryWeight += edge->getLikelyWeight();
}
// entry weight is weight not from any pred
//
weight_t const entryWeight = fgFirstBB->bbWeight - nonEntryWeight;
if (entryWeight <= 0)
{
// If the result is clearly nonsensical, just inherit
//
JITDUMP("\fgCanonicalizeFirstBB: Profile data could not be locally repaired. Data %s inconsistent.\n",
fgPgoConsistent ? "is now" : "was already");
if (fgPgoConsistent)
{
Metrics.ProfileInconsistentScratchBB++;
fgPgoConsistent = false;
}
block->inheritWeight(fgFirstBB);
}
else
{
block->setBBProfileWeight(entryWeight);
}
}
// The new scratch bb will fall through to the old first bb
FlowEdge* const edge = fgAddRefPred(fgFirstBB, block);
block->SetKindAndTargetEdge(BBJ_ALWAYS, edge);
fgInsertBBbefore(fgFirstBB, block);
// Set the expected flags
block->SetFlags(BBF_INTERNAL);
// This new first BB has an implicit ref, and no others.
//
assert(fgPredsComputed);
block->bbRefs = 1;
JITDUMP("New init " FMT_BB "\n", block->bbNum);
}
/*
Removes a block from the return block list
*/
void Compiler::fgRemoveReturnBlock(BasicBlock* block)
{
if (fgReturnBlocks == nullptr)
{
return;
}
if (fgReturnBlocks->block == block)
{
// It's the 1st entry, assign new head of list.
fgReturnBlocks = fgReturnBlocks->next;
return;
}
for (BasicBlockList* retBlocks = fgReturnBlocks; retBlocks->next != nullptr; retBlocks = retBlocks->next)
{
if (retBlocks->next->block == block)
{
// Found it; splice it out.
retBlocks->next = retBlocks->next->next;
return;
}
}
}
//------------------------------------------------------------------------
// fgConvertBBToThrowBB: Change a given block to a throw block.
//
// Arguments:
// block - block in question
//
void Compiler::fgConvertBBToThrowBB(BasicBlock* block)
{
JITDUMP("Converting " FMT_BB " to BBJ_THROW\n", block->bbNum);
assert(fgPredsComputed);
// Ordering of the following operations matters.
// First, if we are looking at the first block of a callfinally pair, remove the pairing.
// Don't actually remove the BBJ_CALLFINALLYRET as that might affect block iteration in
// the callers.
if (block->isBBCallFinallyPair())
{
BasicBlock* const leaveBlock = block->Next();
fgPrepareCallFinallyRetForRemoval(leaveBlock);
}
// Scrub this block from the pred lists of any successors
fgRemoveBlockAsPred(block);
// Update jump kind after the scrub.
block->SetKindAndTargetEdge(BBJ_THROW);
block->RemoveFlags(BBF_RETLESS_CALL); // no longer a BBJ_CALLFINALLY
// Any block with a throw is rare
block->bbSetRunRarely();
}
/*****************************************************************************
* fgChangeSwitchBlock:
*
* We have a BBJ_SWITCH jump at 'oldSwitchBlock' and we want to move this
* switch jump over to 'newSwitchBlock'. All of the blocks that are jumped
* to from jumpTab[] need to have their predecessor lists updated by removing
* the 'oldSwitchBlock' and adding 'newSwitchBlock'.
*/
void Compiler::fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock)
{
noway_assert(oldSwitchBlock != nullptr);
noway_assert(newSwitchBlock != nullptr);
noway_assert(oldSwitchBlock->KindIs(BBJ_SWITCH));
assert(fgPredsComputed);
// Walk the switch's jump table, updating the predecessor for each branch.
BBswtDesc* swtDesc = oldSwitchBlock->GetSwitchTargets();
for (unsigned i = 0; i < swtDesc->bbsCount; i++)
{
FlowEdge* succEdge = swtDesc->bbsDstTab[i];
assert(succEdge != nullptr);
if (succEdge->getSourceBlock() != oldSwitchBlock)
{
// swtDesc can have duplicate targets, so we may have updated this edge already
//
assert(succEdge->getSourceBlock() == newSwitchBlock);
assert(succEdge->getDupCount() > 1);
}
else
{
// Redirect edge's source block from oldSwitchBlock to newSwitchBlock,
// and keep successor block's pred list in order
//
fgReplacePred(succEdge, newSwitchBlock);
}
}
if (m_switchDescMap != nullptr)
{
SwitchUniqueSuccSet uniqueSuccSet;
// If already computed and cached the unique descriptors for the old block, let's
// update those for the new block.
if (m_switchDescMap->Lookup(oldSwitchBlock, &uniqueSuccSet))
{
m_switchDescMap->Set(newSwitchBlock, uniqueSuccSet, BlockToSwitchDescMap::Overwrite);
}
else
{
fgInvalidateSwitchDescMapEntry(newSwitchBlock);
}
fgInvalidateSwitchDescMapEntry(oldSwitchBlock);
}
}
//------------------------------------------------------------------------
// fgChangeEhfBlock: We have a BBJ_EHFINALLYRET block at 'oldBlock' and we want to move this
// to 'newBlock'. All of the 'oldBlock' successors need to have their predecessor lists updated
// by removing edges to 'oldBlock' and adding edges to 'newBlock'.
//
// Arguments:
// oldBlock - previous BBJ_EHFINALLYRET block
// newBlock - block that is replacing 'oldBlock'
//
void Compiler::fgChangeEhfBlock(BasicBlock* oldBlock, BasicBlock* newBlock)
{
assert(oldBlock != nullptr);
assert(newBlock != nullptr);
assert(oldBlock->KindIs(BBJ_EHFINALLYRET));
assert(fgPredsComputed);
BBehfDesc* ehfDesc = oldBlock->GetEhfTargets();
for (unsigned i = 0; i < ehfDesc->bbeCount; i++)
{
FlowEdge* succEdge = ehfDesc->bbeSuccs[i];
fgReplacePred(succEdge, newBlock);
}
}
//------------------------------------------------------------------------
// fgReplaceEhfSuccessor: update BBJ_EHFINALLYRET block so that all control
// that previously flowed to oldSucc now flows to newSucc. It is assumed
// that oldSucc is currently a successor of `block`. We only allow a successor
// block to appear once in the successor list. Thus, if the new successor
// already exists in the list, we simply remove the old successor.
//
// Arguments:
// block - BBJ_EHFINALLYRET block
// newSucc - new successor
// oldSucc - old successor
//
void Compiler::fgReplaceEhfSuccessor(BasicBlock* block, BasicBlock* oldSucc, BasicBlock* newSucc)
{
assert(block != nullptr);
assert(oldSucc != nullptr);
assert(newSucc != nullptr);
assert(block->KindIs(BBJ_EHFINALLYRET));
assert(fgPredsComputed);
BBehfDesc* const ehfDesc = block->GetEhfTargets();
const unsigned succCount = ehfDesc->bbeCount;
FlowEdge** const succTab = ehfDesc->bbeSuccs;
// Walk the successor table looking for the old successor, which we expect to find only once.
unsigned oldSuccNum = UINT_MAX;
unsigned newSuccNum = UINT_MAX;
for (unsigned i = 0; i < succCount; i++)
{
assert(succTab[i]->getSourceBlock() == block);
if (succTab[i]->getDestinationBlock() == newSucc)
{
assert(newSuccNum == UINT_MAX);
newSuccNum = i;
}
if (succTab[i]->getDestinationBlock() == oldSucc)
{
assert(oldSuccNum == UINT_MAX);
oldSuccNum = i;
}
}
noway_assert((oldSuccNum != UINT_MAX) && "Did not find oldSucc in succTab[]");
if (newSuccNum != UINT_MAX)
{
// The new successor is already in the table; simply remove the old one.
fgRemoveEhfSuccessor(block, oldSuccNum);
JITDUMP("Remove existing BBJ_EHFINALLYRET " FMT_BB " successor " FMT_BB "; replacement successor " FMT_BB
" already exists in list\n",
block->bbNum, oldSucc->bbNum, newSucc->bbNum);
}
else
{
// Remove the old edge [block => oldSucc]
//
fgRemoveAllRefPreds(oldSucc, block);
// Create the new edge [block => newSucc]
//
FlowEdge* const newEdge = fgAddRefPred(newSucc, block);
// Replace the old one with the new one.
//
succTab[oldSuccNum] = newEdge;
JITDUMP("Replace BBJ_EHFINALLYRET " FMT_BB " successor " FMT_BB " with " FMT_BB "\n", block->bbNum,
oldSucc->bbNum, newSucc->bbNum);
}
}
//------------------------------------------------------------------------
// fgRemoveEhfSuccessor: update BBJ_EHFINALLYRET block to remove the successor at `succIndex`
// in the block's jump table.
// Updates the predecessor list of the successor, if necessary.
//
// Arguments:
// block - BBJ_EHFINALLYRET block
// succIndex - index of the successor in block->GetEhfTargets()->bbeSuccs
//
void Compiler::fgRemoveEhfSuccessor(BasicBlock* block, const unsigned succIndex)
{
assert(block != nullptr);
assert(block->KindIs(BBJ_EHFINALLYRET));
assert(fgPredsComputed);
BBehfDesc* const ehfDesc = block->GetEhfTargets();
const unsigned succCount = ehfDesc->bbeCount;
FlowEdge** succTab = ehfDesc->bbeSuccs;
assert(succIndex < succCount);
FlowEdge* succEdge = succTab[succIndex];
fgRemoveRefPred(succEdge);
// If succEdge not the last entry, move everything after in the table down one slot.
if ((succIndex + 1) < succCount)
{
memmove_s(&succTab[succIndex], (succCount - succIndex) * sizeof(FlowEdge*), &succTab[succIndex + 1],
(succCount - succIndex - 1) * sizeof(FlowEdge*));
}
#ifdef DEBUG
// We only expect to see a successor once in the table.
for (unsigned i = succIndex; i < (succCount - 1); i++)
{
assert(succTab[i]->getDestinationBlock() != succEdge->getDestinationBlock());
}
#endif // DEBUG
ehfDesc->bbeCount--;
}
//------------------------------------------------------------------------
// fgRemoveEhfSuccessor: Removes `succEdge` from its BBJ_EHFINALLYRET source block's jump table.
// Updates the predecessor list of the successor block, if necessary.
//
// Arguments:
// block - BBJ_EHFINALLYRET block
// succEdge - FlowEdge* to be removed from predecessor block's jump table
//
void Compiler::fgRemoveEhfSuccessor(FlowEdge* succEdge)
{
assert(succEdge != nullptr);
assert(fgPredsComputed);
BasicBlock* block = succEdge->getSourceBlock();
assert(block != nullptr);
assert(block->KindIs(BBJ_EHFINALLYRET));
fgRemoveRefPred(succEdge);
BBehfDesc* const ehfDesc = block->GetEhfTargets();
const unsigned succCount = ehfDesc->bbeCount;
FlowEdge** succTab = ehfDesc->bbeSuccs;
bool found = false;
// Search succTab for succEdge so we can splice it out of the table.
for (unsigned i = 0; i < succCount; i++)
{
if (succTab[i] == succEdge)
{
// If succEdge not the last entry, move everything after in the table down one slot.
if ((i + 1) < succCount)
{
memmove_s(&succTab[i], (succCount - i) * sizeof(FlowEdge*), &succTab[i + 1],
(succCount - i - 1) * sizeof(FlowEdge*));
}
found = true;
#ifdef DEBUG
// We only expect to see a successor once in the table.
for (; i < (succCount - 1); i++)
{
assert(succTab[i]->getDestinationBlock() != succEdge->getDestinationBlock());
}
#endif // DEBUG
}
}
assert(found);
ehfDesc->bbeCount--;
}
//------------------------------------------------------------------------
// Compiler::fgReplaceJumpTarget: For a given block, replace the target 'oldTarget' with 'newTarget'.
//
// Arguments:
// block - the block in which a jump target will be replaced.
// newTarget - the new branch target of the block.
// oldTarget - the old branch target of the block.
//
// Notes:
// 1. Only branches are changed: BBJ_ALWAYS, the non-fallthrough path of BBJ_COND, BBJ_SWITCH, etc.
// We assert for other jump kinds.
// 2. All branch targets found are updated. If there are multiple ways for a block
// to reach 'oldTarget' (e.g., multiple arms of a switch), all of them are changed.
// 3. The predecessor lists are updated.
// 4. If any switch table entry was updated, the switch table "unique successor" cache is invalidated.
//
void Compiler::fgReplaceJumpTarget(BasicBlock* block, BasicBlock* oldTarget, BasicBlock* newTarget)
{
assert(block != nullptr);
assert(fgPredsComputed);
switch (block->GetKind())
{
case BBJ_CALLFINALLY:
case BBJ_CALLFINALLYRET:
case BBJ_ALWAYS:
case BBJ_EHCATCHRET:
case BBJ_EHFILTERRET:
case BBJ_LEAVE: // This function can be called before import, so we still have BBJ_LEAVE
assert(block->TargetIs(oldTarget));
fgRedirectTargetEdge(block, newTarget);
break;
case BBJ_COND:
if (block->TrueTargetIs(oldTarget))
{
if (block->FalseEdgeIs(block->GetTrueEdge()))
{
// Branch was degenerate, simplify it first
//
fgRemoveConditionalJump(block);
assert(block->KindIs(BBJ_ALWAYS));
assert(block->TargetIs(oldTarget));
fgRedirectTargetEdge(block, newTarget);
}
else
{
fgRedirectTrueEdge(block, newTarget);
}
}
else
{
// Already degenerate cases should have taken the true path above
//
assert(block->FalseTargetIs(oldTarget));
assert(!block->TrueEdgeIs(block->GetFalseEdge()));
fgRedirectFalseEdge(block, newTarget);
}
if (block->KindIs(BBJ_COND) && block->TrueEdgeIs(block->GetFalseEdge()))
{
// Block became degenerate, simplify
//
fgRemoveConditionalJump(block);
assert(block->KindIs(BBJ_ALWAYS));
assert(block->TargetIs(newTarget));
}
break;
case BBJ_SWITCH:
{
unsigned const jumpCnt = block->GetSwitchTargets()->bbsCount;
FlowEdge** const jumpTab = block->GetSwitchTargets()->bbsDstTab;
bool existingEdge = false;
FlowEdge* oldEdge = nullptr;
FlowEdge* newEdge = nullptr;
bool changed = false;
for (unsigned i = 0; i < jumpCnt; i++)
{
if (jumpTab[i]->getDestinationBlock() == newTarget)
{
// The new target already has an edge from this switch statement.
// We'll need to add the likelihood from the edge we're redirecting
// to the existing edge. Note that if there is no existing edge,
// then we'll copy the likelihood from the existing edge we pass to
// `fgAddRefPred`. Note also that we can visit the same edge multiple
// times if there are multiple switch cases with the same target. The
// edge has a dup count and a single likelihood for all the possible
// paths to the target, so we only want to add the likelihood once
// despite visiting the duplicated edges in the `jumpTab` array
// multiple times.
existingEdge = true;
}
if (jumpTab[i]->getDestinationBlock() == oldTarget)
{
assert((oldEdge == nullptr) || (oldEdge == jumpTab[i]));
oldEdge = jumpTab[i];
fgRemoveRefPred(oldEdge);
newEdge = fgAddRefPred(newTarget, block, oldEdge);
jumpTab[i] = newEdge;
changed = true;
}
}
if (existingEdge)
{
assert(oldEdge != nullptr);
assert(oldEdge->getSourceBlock() == block);
assert(oldEdge->getDestinationBlock() == oldTarget);
assert(newEdge != nullptr);
assert(newEdge->getSourceBlock() == block);
assert(newEdge->getDestinationBlock() == newTarget);
newEdge->addLikelihood(oldEdge->getLikelihood());
}
assert(changed);
InvalidateUniqueSwitchSuccMap();
break;
}
case BBJ_EHFINALLYRET:
fgReplaceEhfSuccessor(block, oldTarget, newTarget);
break;
default:
assert(!"Block doesn't have a jump target!");
unreached();
break;
}
}
//------------------------------------------------------------------------
// fgReplacePred: redirects the given edge to a new predecessor block
//
// Arguments:
// edge - the edge whose source block we want to update
// newPred - the new predecessor block for edge
//
// Notes:
//
// This function assumes that all branches from the predecessor (practically, that all
// switch cases that target the successor block) are changed to branch from the new predecessor,
// with the same dup count.
//
// Note that the successor block's bbRefs is not changed, since it has the same number of
// references as before, just from a different predecessor block.
//
// Also note this may cause reordering of the pred list.
//
void Compiler::fgReplacePred(FlowEdge* edge, BasicBlock* const newPred)
{
assert(edge != nullptr);
assert(newPred != nullptr);
assert(edge->getSourceBlock() != newPred);
// Remove the edge, modify it, then add it back
//
BasicBlock* const target = edge->getDestinationBlock();
BasicBlock* const oldPred = edge->getSourceBlock();
FlowEdge** listp = fgGetPredInsertPoint(oldPred, target);
assert(*listp == edge);
*listp = edge->getNextPredEdge();
edge->setSourceBlock(newPred);
listp = fgGetPredInsertPoint(newPred, target);
edge->setNextPredEdge(*listp);
*listp = edge;
assert(target->checkPredListOrder());
}
/*****************************************************************************
* For a block that is in a handler region, find the first block of the most-nested
* handler containing the block.
*/
BasicBlock* Compiler::fgFirstBlockOfHandler(BasicBlock* block)
{
assert(block->hasHndIndex());
return ehGetDsc(block->getHndIndex())->ebdHndBeg;
}
#ifdef DEBUG
//------------------------------------------------------------------------
// fgInvalidateBBLookup: In non-Release builds, set fgBBs to a dummy value.
// After calling this, fgInitBBLookup must be called before using fgBBs again.
//
void Compiler::fgInvalidateBBLookup()
{
fgBBs = (BasicBlock**)0xCDCD;
}
#endif // DEBUG
/*****************************************************************************
*
* The following helps find a basic block given its PC offset.
*/
void Compiler::fgInitBBLookup()
{
BasicBlock** dscBBptr;
/* Allocate the basic block table */
dscBBptr = fgBBs = new (this, CMK_BasicBlock) BasicBlock*[fgBBcount];
/* Walk all the basic blocks, filling in the table */
for (BasicBlock* const block : Blocks())
{
*dscBBptr++ = block;
}
noway_assert(dscBBptr == fgBBs + fgBBcount);
}
BasicBlock* Compiler::fgLookupBB(unsigned addr)
{
unsigned lo;
unsigned hi;
/* Do a binary search */
for (lo = 0, hi = fgBBcount - 1;;)
{
AGAIN:;
if (lo > hi)
{
break;
}
unsigned mid = (lo + hi) / 2;
BasicBlock* dsc = fgBBs[mid];
// We introduce internal blocks for BBJ_CALLFINALLY. Skip over these.
while (dsc->HasFlag(BBF_INTERNAL))
{
dsc = dsc->Next();
mid++;
// We skipped over too many, Set hi back to the original mid - 1
if (mid > hi)
{
mid = (lo + hi) / 2;
hi = mid - 1;
goto AGAIN;
}
}
unsigned pos = dsc->bbCodeOffs;
if (pos < addr)
{
if ((lo == hi) && (lo == (fgBBcount - 1)))
{
noway_assert(addr == dsc->bbCodeOffsEnd);
return nullptr; // NULL means the end of method
}
lo = mid + 1;
continue;
}
if (pos > addr)
{
hi = mid - 1;
continue;
}
return dsc;
}
#ifdef DEBUG
printf("ERROR: Couldn't find basic block at offset %04X\n", addr);
#endif // DEBUG
NO_WAY("fgLookupBB failed.");
}
//------------------------------------------------------------------------
// FgStack: simple stack model for the inlinee's evaluation stack.
//
// Model the inputs available to various operations in the inline body.
// Tracks constants, arguments, array lengths.
class FgStack
{
public:
FgStack()
: slot0(SLOT_INVALID)
, slot1(SLOT_INVALID)
, depth(0)
{
// Empty
}
enum FgSlot
{
SLOT_INVALID = UINT_MAX,
SLOT_UNKNOWN = 0,
SLOT_CONSTANT = 1,
SLOT_ARRAYLEN = 2,
SLOT_ARGUMENT = 3
};
void Clear()
{
depth = 0;
}
void PushUnknown()
{
Push(SLOT_UNKNOWN);
}
void PushConstant()
{
Push(SLOT_CONSTANT);
}
void PushArrayLen()
{
Push(SLOT_ARRAYLEN);
}
void PushArgument(unsigned arg)
{
Push((FgSlot)(SLOT_ARGUMENT + arg));
}
FgSlot GetSlot0() const
{
return depth >= 1 ? slot0 : FgSlot::SLOT_UNKNOWN;
}
FgSlot GetSlot1() const
{
return depth >= 2 ? slot1 : FgSlot::SLOT_UNKNOWN;
}
FgSlot Top(const int n = 0)
{
if (n == 0)
{
return depth >= 1 ? slot0 : SLOT_UNKNOWN;
}
if (n == 1)
{
return depth == 2 ? slot1 : SLOT_UNKNOWN;
}
unreached();
}
static bool IsConstant(FgSlot value)
{
return value == SLOT_CONSTANT;
}
static bool IsConstantOrConstArg(FgSlot value, InlineInfo* info)
{
return IsConstant(value) || IsConstArgument(value, info);
}
static bool IsArrayLen(FgSlot value)
{
return value == SLOT_ARRAYLEN;
}
static bool IsArgument(FgSlot value)
{
return value >= SLOT_ARGUMENT;
}
static bool IsConstArgument(FgSlot value, InlineInfo* info)
{
if ((info == nullptr) || !IsArgument(value))
{
return false;
}
const unsigned argNum = value - SLOT_ARGUMENT;
if (argNum < info->argCnt)
{
return info->inlArgInfo[argNum].argIsInvariant;
}
return false;
}
static bool IsExactArgument(FgSlot value, InlineInfo* info)
{
if ((info == nullptr) || !IsArgument(value))
{
return false;
}
const unsigned argNum = value - SLOT_ARGUMENT;
if (argNum < info->argCnt)
{
return info->inlArgInfo[argNum].argIsExact;
}
return false;
}
static unsigned SlotTypeToArgNum(FgSlot value)
{
assert(IsArgument(value));
return value - SLOT_ARGUMENT;
}
bool IsStackTwoDeep() const
{
return depth == 2;
}
bool IsStackOneDeep() const
{
return depth == 1;
}
bool IsStackAtLeastOneDeep() const
{
return depth >= 1;
}
void Push(FgSlot slot)
{
assert(depth <= 2);
slot1 = slot0;
slot0 = slot;
if (depth < 2)
{
depth++;
}
}
private:
FgSlot slot0;
FgSlot slot1;
unsigned depth;
};
//------------------------------------------------------------------------
// fgFindJumpTargets: walk the IL stream, determining jump target offsets
//
// Type arguments:
// makeInlineObservations - whether or not to record inline observations about the method
//
// Arguments:
// codeAddr - base address of the IL code buffer
// codeSize - number of bytes in the IL code buffer
// jumpTarget - [OUT] bit vector for flagging jump targets
//
// Notes:
// If "makeInlineObservations" is true this method also makes
// various observations about the method that factor into inline
// decisions.
//
// May throw an exception if the IL is malformed.
//
// jumpTarget[N] is set to 1 if IL offset N is a jump target in the method.
//
// Also sets m_addrExposed and lvHasILStoreOp, ilHasMultipleILStoreOp in lvaTable[].
//
template <bool makeInlineObservations>
void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget)
{
const BYTE* codeBegp = codeAddr;
const BYTE* codeEndp = codeAddr + codeSize;
unsigned varNum;
var_types varType = DUMMY_INIT(TYP_UNDEF); // TYP_ type
bool typeIsNormed = false;
FgStack pushedStack;
const bool isForceInline = (info.compFlags & CORINFO_FLG_FORCEINLINE) != 0;
const bool isInlining = compIsForInlining();
unsigned retBlocks = 0;
int prefixFlags = 0;
bool preciseScan = makeInlineObservations && compInlineResult->GetPolicy()->RequiresPreciseScan();
const bool resolveTokens = preciseScan;
// Track offsets where IL instructions begin in DEBUG builds. Used to
// validate debug info generated by the JIT.
assert(codeSize == compInlineContext->GetILSize());
INDEBUG(FixedBitVect* ilInstsSet = FixedBitVect::bitVectInit(codeSize, this));
if (makeInlineObservations)
{
// Set default values for profile (to avoid NoteFailed in CALLEE_IL_CODE_SIZE's handler)
// these will be overridden later.
compInlineResult->NoteBool(InlineObservation::CALLSITE_HAS_PROFILE_WEIGHTS, true);
compInlineResult->NoteDouble(InlineObservation::CALLSITE_PROFILE_FREQUENCY, 1.0);
// Observe force inline state and code size.
compInlineResult->NoteBool(InlineObservation::CALLEE_IS_FORCE_INLINE, isForceInline);
compInlineResult->NoteInt(InlineObservation::CALLEE_IL_CODE_SIZE, codeSize);
// Determine if call site is within a try.
if (isInlining && impInlineInfo->iciBlock->hasTryIndex())
{
compInlineResult->Note(InlineObservation::CALLSITE_IN_TRY_REGION);
}
// Determine if the call site is in a no-return block
if (isInlining && impInlineInfo->iciBlock->KindIs(BBJ_THROW))
{
compInlineResult->Note(InlineObservation::CALLSITE_IN_NORETURN_REGION);
}
// Determine if the call site is in a loop.
if (isInlining && impInlineInfo->iciBlock->HasFlag(BBF_BACKWARD_JUMP))
{
compInlineResult->Note(InlineObservation::CALLSITE_IN_LOOP);
}
#ifdef DEBUG
// If inlining, this method should still be a candidate.
if (isInlining)
{
assert(compInlineResult->IsCandidate());
}
#endif // DEBUG
// note that we're starting to look at the opcodes.
compInlineResult->Note(InlineObservation::CALLEE_BEGIN_OPCODE_SCAN);
}
CORINFO_RESOLVED_TOKEN resolvedToken;
OPCODE opcode = CEE_NOP;
OPCODE prevOpcode = CEE_NOP;
bool handled = false;
while (codeAddr < codeEndp)
{
prevOpcode = opcode;
opcode = (OPCODE)getU1LittleEndian(codeAddr);
INDEBUG(ilInstsSet->bitVectSet((UINT)(codeAddr - codeBegp)));
codeAddr += sizeof(int8_t);
if (!handled && preciseScan)
{
// Push something unknown to the stack since we couldn't find anything useful for inlining
pushedStack.PushUnknown();
}
handled = false;
DECODE_OPCODE:
if ((unsigned)opcode >= CEE_COUNT)
{
BADCODE3("Illegal opcode", ": %02X", (int)opcode);
}
if ((opcode >= CEE_LDARG_0 && opcode <= CEE_STLOC_S) || (opcode >= CEE_LDARG && opcode <= CEE_STLOC))
{
opts.lvRefCount++;
}
if (makeInlineObservations && (opcode >= CEE_LDNULL) && (opcode <= CEE_LDC_R8))
{
// LDTOKEN and LDSTR are handled below
pushedStack.PushConstant();
handled = true;
}
unsigned sz = opcodeSizes[opcode];
switch (opcode)
{
case CEE_PREFIX1:
{
if (codeAddr >= codeEndp)
{
goto TOO_FAR;
}
opcode = (OPCODE)(256 + getU1LittleEndian(codeAddr));
codeAddr += sizeof(int8_t);
goto DECODE_OPCODE;
}
case CEE_PREFIX2:
case CEE_PREFIX3:
case CEE_PREFIX4:
case CEE_PREFIX5:
case CEE_PREFIX6:
case CEE_PREFIX7:
case CEE_PREFIXREF:
{
BADCODE3("Illegal opcode", ": %02X", (int)opcode);
}
case CEE_SIZEOF:
case CEE_LDTOKEN:
case CEE_LDSTR:
{
if (preciseScan)
{
pushedStack.PushConstant();
handled = true;