-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathfgprofile.cpp
5065 lines (4450 loc) · 170 KB
/
fgprofile.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
#include "fgprofilesynthesis.h"
// Flowgraph Profile Support
//------------------------------------------------------------------------
// fgHaveProfileData: check if profile data is available
//
// Returns:
// true if so
//
// Note:
// In most cases it is more appropriate to call fgHaveProfileWeights,
// since that tells you if blocks have profile-based weights.
//
// This method literally checks if the runtime had a profile schema,
// from which we can derive weights.
//
// Schema-based data comes from Tier0 methods, which currently do not do
// any inlining; thus inlinee profile data should be available and
// representative.
//
bool Compiler::fgHaveProfileData()
{
return (fgPgoSchema != nullptr);
}
//------------------------------------------------------------------------
// fgHaveProfileWeights: Check if we have a profile that has weights.
//
// Notes:
// These weights may come from instrumentation or from synthesis.
//
bool Compiler::fgHaveProfileWeights()
{
return fgPgoHaveWeights;
}
//------------------------------------------------------------------------
// fgRemoveProfileData: Remove all traces of profile info
//
// Notes:
// Needed if the jit initially thought it was going to optimize
// the method, but then decided not to.
//
// Does not modify any block fields, so should be called before
// we start to incorporate profile data.
//
void Compiler::fgRemoveProfileData(const char* reason)
{
fgPgoFailReason = reason;
fgPgoQueryResult = E_FAIL;
fgPgoHaveWeights = false;
fgPgoData = nullptr;
fgPgoSchema = nullptr;
fgPgoDisabled = true;
fgPgoDynamic = false;
}
//------------------------------------------------------------------------
// fgHaveSufficientProfileWeights: check if profile data is available
// and is sufficient enough to be trustful.
//
// Returns:
// true if so
//
// Note:
// See notes for fgHaveProfileData.
//
bool Compiler::fgHaveSufficientProfileWeights()
{
if (!fgHaveProfileWeights())
{
return false;
}
switch (fgPgoSource)
{
case ICorJitInfo::PgoSource::Dynamic:
case ICorJitInfo::PgoSource::Text:
case ICorJitInfo::PgoSource::Blend:
return true;
case ICorJitInfo::PgoSource::Static:
{
// We sometimes call this very early, eg evaluating the prejit root.
//
if (fgFirstBB != nullptr)
{
const weight_t sufficientSamples = 1000;
return fgFirstBB->bbWeight > sufficientSamples;
}
return true;
}
default:
return false;
}
}
//------------------------------------------------------------------------
// fgHaveTrustedProfileWeights: check if profile data source is one
// that can be trusted to faithfully represent the current program
// behavior.
//
// Returns:
// true if so
//
// Note:
// See notes for fgHaveProfileData.
//
bool Compiler::fgHaveTrustedProfileWeights()
{
if (!fgHaveProfileWeights())
{
return false;
}
// We allow Text to be trusted so we can use it to stand in
// for Dynamic results.
//
switch (fgPgoSource)
{
case ICorJitInfo::PgoSource::Dynamic:
case ICorJitInfo::PgoSource::Blend:
case ICorJitInfo::PgoSource::Text:
return true;
default:
return false;
}
}
//------------------------------------------------------------------------
// fgApplyProfileScale: scale inlinee counts by appropriate scale factor
//
void Compiler::fgApplyProfileScale()
{
// Only applicable to inlinees
//
if (!compIsForInlining())
{
return;
}
JITDUMP("Computing inlinee profile scale:\n");
// Callee has profile data?
//
if (!fgHaveProfileWeights())
{
// No; we will carry on nonetheless.
//
JITDUMP(" ... no callee profile data, will use non-pgo weight to scale\n");
}
// Determine the weight of the first block preds, if any.
// (only happens if the first block is a loop head).
//
weight_t firstBlockPredWeight = 0;
for (FlowEdge* const firstBlockPred : fgFirstBB->PredEdges())
{
firstBlockPredWeight += firstBlockPred->getLikelyWeight();
}
// Determine the "input" weight for the callee
//
weight_t calleeWeight = fgFirstBB->bbWeight;
// Callee entry weight is zero or negative (taking backedges into account)?
// If so, just choose the smallest plausible weight.
//
if (calleeWeight <= firstBlockPredWeight)
{
calleeWeight = fgHaveProfileWeights() ? 1.0 : BB_UNITY_WEIGHT;
JITDUMP(" ... callee entry has zero or negative weight, will use weight of " FMT_WT " to scale\n",
calleeWeight);
JITDUMP("Profile data could not be scaled consistently. Data %s inconsistent.\n",
fgPgoConsistent ? "is now" : "was already");
if (fgPgoConsistent)
{
Metrics.ProfileInconsistentInlineeScale++;
fgPgoConsistent = false;
}
}
else
{
calleeWeight -= firstBlockPredWeight;
}
// Call site has profile weight?
//
const BasicBlock* callSiteBlock = impInlineInfo->iciBlock;
if (!callSiteBlock->hasProfileWeight())
{
// No? We will carry on nonetheless.
//
JITDUMP(" ... call site not profiled, will use non-pgo weight to scale\n");
}
const weight_t callSiteWeight = callSiteBlock->bbWeight;
// Call site has zero count?
//
// Todo: perhaps retain some semblance of callee profile data,
// possibly scaled down severely.
//
// You might wonder why we bother to inline at cold sites.
// Recall ALWAYS and FORCE inlines bypass all profitability checks.
// And, there can be hot-path benefits to a cold-path inline.
//
if (callSiteWeight == BB_ZERO_WEIGHT)
{
JITDUMP(" ... zero call site count; scale will be 0.0\n");
}
// If profile data reflects a complete single run we can expect
// calleeWeight >= callSiteWeight.
//
// However if our profile is just a subset of execution we may
// not see this.
//
// So, we are willing to scale the callee counts down or up as
// needed to match the call site.
//
// Hence, scale can be somewhat arbitrary...
//
const weight_t scale = callSiteWeight / calleeWeight;
JITDUMP(" call site count " FMT_WT " callee entry count " FMT_WT " scale " FMT_WT "\n", callSiteWeight,
calleeWeight, scale);
JITDUMP("Scaling inlinee blocks\n");
for (BasicBlock* const block : Blocks())
{
block->scaleBBWeight(scale);
}
}
//------------------------------------------------------------------------
// fgGetProfileWeightForBasicBlock: obtain profile data for a block
//
// Arguments:
// offset - IL offset of the block
// weightWB - [OUT] weight obtained
//
// Returns:
// true if data was found
//
bool Compiler::fgGetProfileWeightForBasicBlock(IL_OFFSET offset, weight_t* weightWB)
{
noway_assert(weightWB != nullptr);
weight_t weight = 0;
#ifdef DEBUG
unsigned hashSeed = fgStressBBProf();
if (hashSeed != 0)
{
unsigned hash = (info.compMethodHash() * hashSeed) ^ (offset * 1027);
// We need to especially stress the procedure splitting codepath. Therefore
// one third the time we should return a weight of zero.
// Otherwise we should return some random weight (usually between 0 and 288).
// The below gives a weight of zero, 44% of the time
if (hash % 3 == 0)
{
weight = BB_ZERO_WEIGHT;
}
else if (hash % 11 == 0)
{
weight = (weight_t)(hash % 23) * (hash % 29) * (hash % 31);
}
else
{
weight = (weight_t)(hash % 17) * (hash % 19);
}
// The first block is never given a weight of zero
if ((offset == 0) && (weight == BB_ZERO_WEIGHT))
{
weight = (weight_t)1 + (hash % 5);
}
*weightWB = weight;
return true;
}
#endif // DEBUG
if (!fgHaveProfileWeights())
{
return false;
}
for (UINT32 i = 0; i < fgPgoSchemaCount; i++)
{
if ((IL_OFFSET)fgPgoSchema[i].ILOffset != offset)
{
continue;
}
if (fgPgoSchema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount)
{
*weightWB = (weight_t) * (uint32_t*)(fgPgoData + fgPgoSchema[i].Offset);
return true;
}
if (fgPgoSchema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::BasicBlockLongCount)
{
*weightWB = (weight_t) * (uint64_t*)(fgPgoData + fgPgoSchema[i].Offset);
return true;
}
}
*weightWB = 0;
return true;
}
typedef jitstd::vector<ICorJitInfo::PgoInstrumentationSchema> Schema;
//------------------------------------------------------------------------
// Instrumentor: base class for count and class instrumentation
//
class Instrumentor
{
protected:
Compiler* m_comp;
unsigned m_schemaCount;
unsigned m_instrCount;
bool m_modifiedFlow;
protected:
Instrumentor(Compiler* comp)
: m_comp(comp)
, m_schemaCount(0)
, m_instrCount(0)
, m_modifiedFlow(false)
{
}
public:
virtual bool ShouldProcess(BasicBlock* block)
{
return false;
}
virtual bool ShouldInstrument(BasicBlock* block)
{
return ShouldProcess(block);
}
virtual void Prepare(bool preImport)
{
}
virtual void BuildSchemaElements(BasicBlock* block, Schema& schema)
{
}
virtual void Instrument(BasicBlock* block, Schema& schema, uint8_t* profileMemory)
{
}
unsigned SchemaCount() const
{
return m_schemaCount;
}
unsigned InstrCount() const
{
return m_instrCount;
}
void SetModifiedFlow()
{
m_modifiedFlow = true;
}
bool ModifiedFlow() const
{
return m_modifiedFlow;
}
};
//------------------------------------------------------------------------
// NonInstrumentor: instrumentor that does not instrument anything
//
class NonInstrumentor : public Instrumentor
{
public:
NonInstrumentor(Compiler* comp)
: Instrumentor(comp)
{
}
};
//------------------------------------------------------------------------
// BlockCountInstrumentor: instrumentor that adds a counter to each
// non-internal imported basic block
//
class BlockCountInstrumentor : public Instrumentor
{
private:
void RelocateProbes();
BasicBlock* m_entryBlock;
public:
BlockCountInstrumentor(Compiler* comp)
: Instrumentor(comp)
, m_entryBlock(nullptr)
{
}
bool ShouldProcess(BasicBlock* block) override
{
return block->HasFlag(BBF_IMPORTED) && !block->HasFlag(BBF_INTERNAL);
}
void Prepare(bool isPreImport) override;
void BuildSchemaElements(BasicBlock* block, Schema& schema) override;
void Instrument(BasicBlock* block, Schema& schema, uint8_t* profileMemory) override;
static GenTree* CreateCounterIncrement(Compiler* comp, uint8_t* counterAddr, var_types countType);
};
//------------------------------------------------------------------------
// BlockCountInstrumentor::Prepare: prepare for count instrumentation
//
// Arguments:
// preImport - true if this is the prepare call that happens before
// importation
//
void BlockCountInstrumentor::Prepare(bool preImport)
{
if (preImport)
{
return;
}
RelocateProbes();
#ifdef DEBUG
// Set schema index to invalid value
//
for (BasicBlock* const block : m_comp->Blocks())
{
block->bbCountSchemaIndex = -1;
}
#endif
}
//------------------------------------------------------------------------
// BlockCountInstrumentor::RelocateProbes: relocate any probes that
// would appear in post-tail call blocks.
//
// Notes:
// Conveys relocation information by updating the m_relocationMap.
//
// Actual relocation happens during Instrument, keying off of the
// BBF_TAILCALL_SUCCESSOR flag and m_relocationMap entries.
//
void BlockCountInstrumentor::RelocateProbes()
{
// We only see such blocks when optimizing. They are flagged by the importer.
//
if (!m_comp->opts.IsInstrumentedAndOptimized() || ((m_comp->optMethodFlags & OMF_HAS_TAILCALL_SUCCESSOR) == 0))
{
// No problematic blocks to worry about.
//
return;
}
JITDUMP("Optimized + instrumented + potential tail calls --- preparing to relocate edge probes\n");
// We should be in a root method compiler instance. We currently do not instrument inlinees.
//
// Relaxing this will require changes below because inlinee compilers
// share the root compiler flow graph (and hence bb epoch), and flow
// from inlinee tail calls to returns can be more complex.
//
assert(!m_comp->compIsForInlining());
// Keep track of return blocks needing special treatment.
//
ArrayStack<BasicBlock*> criticalPreds(m_comp->getAllocator(CMK_Pgo));
// Walk blocks looking for BBJ_RETURNs that are successors of potential tail calls.
//
// If any such block has a conditional pred, we will need to reroute flow from those preds
// via an intermediary block. That block will subsequently hold the relocated block
// probe for the returnBlock for those preds.
//
for (BasicBlock* const block : m_comp->Blocks())
{
// Ignore blocks that we won't process.
//
if (!ShouldProcess(block))
{
continue;
}
if (!block->HasFlag(BBF_TAILCALL_SUCCESSOR))
{
continue;
}
JITDUMP("Return " FMT_BB " is successor of possible tail call\n", block->bbNum);
assert(block->KindIs(BBJ_RETURN));
// Scan for critical preds, and add relocated probes to non-critical preds.
//
criticalPreds.Reset();
for (BasicBlock* const pred : block->PredBlocks())
{
if (!ShouldProcess(pred))
{
JITDUMP(FMT_BB " -> " FMT_BB " is dead edge\n", pred->bbNum, block->bbNum);
continue;
}
BasicBlock* const succ = pred->GetUniqueSucc();
if ((succ == nullptr) || pred->isBBCallFinallyPairTail())
{
// Route pred through the intermediary.
//
JITDUMP(FMT_BB " -> " FMT_BB " is critical edge\n", pred->bbNum, block->bbNum);
criticalPreds.Push(pred);
}
else
{
assert(pred->KindIs(BBJ_ALWAYS));
}
}
// If there are any critical preds, create and instrument the
// intermediary and reroute flow. Mark the intermediary so we make
// sure to instrument it later.
//
if (criticalPreds.Height() > 0)
{
BasicBlock* const intermediary = m_comp->fgNewBBbefore(BBJ_ALWAYS, block, /* extendRegion */ true);
intermediary->SetFlags(BBF_IMPORTED | BBF_MARKED);
intermediary->inheritWeight(block);
FlowEdge* const newEdge = m_comp->fgAddRefPred(block, intermediary);
intermediary->SetTargetEdge(newEdge);
SetModifiedFlow();
while (criticalPreds.Height() > 0)
{
BasicBlock* const pred = criticalPreds.Pop();
// Redirect any jumps
//
m_comp->fgReplaceJumpTarget(pred, block, intermediary);
}
}
}
}
//------------------------------------------------------------------------
// BlockCountInstrumentor::BuildSchemaElements: create schema elements for a block counter
//
// Arguments:
// block -- block to instrument
// schema -- schema that we're building
//
void BlockCountInstrumentor::BuildSchemaElements(BasicBlock* block, Schema& schema)
{
unsigned numCountersPerProbe = 1;
// When we have both interlocked and scalable profile modes enabled, we will
// count both ways, so allocate two count slots per probe.
//
if ((JitConfig.JitScalableProfiling() > 0) && (JitConfig.JitInterlockedProfiling() > 0))
{
numCountersPerProbe = 2;
}
else if (JitConfig.JitCounterPadding() > 0)
{
numCountersPerProbe = (unsigned)JitConfig.JitCounterPadding();
}
// Remember the schema index for this block.
//
assert(block->bbCountSchemaIndex == -1);
block->bbCountSchemaIndex = (int)schema.size();
// Assign the current block's IL offset into the profile data
// (make sure IL offset is sane)
//
IL_OFFSET offset = block->bbCodeOffs;
assert((int)offset >= 0);
ICorJitInfo::PgoInstrumentationSchema schemaElem;
schemaElem.Count = numCountersPerProbe;
schemaElem.Other = 0;
schemaElem.InstrumentationKind = m_comp->opts.compCollect64BitCounts
? ICorJitInfo::PgoInstrumentationKind::BasicBlockLongCount
: ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount;
schemaElem.ILOffset = offset;
schemaElem.Offset = 0;
schema.push_back(schemaElem);
m_schemaCount++;
// If this is the entry block, remember it for later.
// Note it might not be fgFirstBB, if we have a scratchBB.
//
if (offset == 0)
{
assert(m_entryBlock == nullptr);
m_entryBlock = block;
}
}
//------------------------------------------------------------------------
// BlockCountInstrumentor::Instrument: add counter probe to block
//
// Arguments:
// block -- block of interest
// schema -- instrumentation schema
// profileMemory -- profile data slab
//
void BlockCountInstrumentor::Instrument(BasicBlock* block, Schema& schema, uint8_t* profileMemory)
{
const ICorJitInfo::PgoInstrumentationSchema& entry = schema[block->bbCountSchemaIndex];
assert(block->bbCodeOffs == (IL_OFFSET)entry.ILOffset);
assert((entry.InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount) ||
(entry.InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::BasicBlockLongCount));
uint8_t* addrOfCurrentExecutionCount = entry.Offset + profileMemory;
#ifdef DEBUG
if (JitConfig.JitPropagateSynthesizedCountsToProfileData() > 0)
{
// Write the current synthesized count as the profile data
//
weight_t blockWeight = block->bbWeight;
if (entry.InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::EdgeIntCount)
{
*((uint32_t*)addrOfCurrentExecutionCount) = (uint32_t)blockWeight;
}
else
{
*((uint64_t*)addrOfCurrentExecutionCount) = (uint64_t)blockWeight;
}
return;
}
#endif
var_types typ =
entry.InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount ? TYP_INT : TYP_LONG;
GenTree* incCount = CreateCounterIncrement(m_comp, addrOfCurrentExecutionCount, typ);
if (block->HasFlag(BBF_TAILCALL_SUCCESSOR))
{
// This block probe needs to be relocated; instrument each predecessor.
//
bool first = true;
for (BasicBlock* pred : block->PredBlocks())
{
const bool isLivePred = ShouldProcess(pred) || pred->HasFlag(BBF_MARKED);
if (!isLivePred)
{
continue;
}
JITDUMP("Placing copy of block probe for " FMT_BB " in pred " FMT_BB "\n", block->bbNum, pred->bbNum);
if (!first)
{
incCount = m_comp->gtCloneExpr(incCount);
}
m_comp->fgNewStmtAtBeg(pred, incCount);
pred->RemoveFlags(BBF_MARKED);
first = false;
}
}
else
{
m_comp->fgNewStmtAtBeg(block, incCount);
}
m_instrCount++;
}
//------------------------------------------------------------------------
// BlockCountInstrumentor::CreateCounterIncrement: create a tree that increments a profile counter.
//
// Arguments:
// comp - compiler instance
// counterAddr - address of counter to increment
// countType - type of counter
//
// Returns:
// A node that increments the specified count.
//
GenTree* BlockCountInstrumentor::CreateCounterIncrement(Compiler* comp, uint8_t* counterAddr, var_types countType)
{
const bool interlocked = JitConfig.JitInterlockedProfiling() > 0;
const bool scalable = JitConfig.JitScalableProfiling() > 0;
if (interlocked || scalable)
{
GenTree* result = nullptr;
if (interlocked)
{
// Form counter address
GenTree* addressNode = comp->gtNewIconHandleNode(reinterpret_cast<size_t>(counterAddr), GTF_ICON_BBC_PTR);
// Interlocked increment
result = comp->gtNewAtomicNode(GT_XADD, countType, addressNode, comp->gtNewIconNode(1, countType));
}
if (scalable)
{
if (interlocked)
{
assert(result != nullptr);
counterAddr += (countType == TYP_INT) ? 4 : 8;
}
// Form counter address
GenTree* addressNode = comp->gtNewIconHandleNode(reinterpret_cast<size_t>(counterAddr), GTF_ICON_BBC_PTR);
// Scalable increment
GenTree* scalableNode = comp->gtNewHelperCallNode((countType == TYP_INT) ? CORINFO_HELP_COUNTPROFILE32
: CORINFO_HELP_COUNTPROFILE64,
countType, addressNode);
if (interlocked)
{
result = comp->gtNewOperNode(GT_COMMA, countType, result, scalableNode);
}
else
{
result = scalableNode;
}
}
return result;
}
// Else do an unsynchronized update
//
// Read Basic-Block count value
GenTree* valueNode =
comp->gtNewIndOfIconHandleNode(countType, reinterpret_cast<size_t>(counterAddr), GTF_ICON_BBC_PTR, false);
// Increment value by 1
GenTree* incValueNode = comp->gtNewOperNode(GT_ADD, countType, valueNode, comp->gtNewIconNode(1, countType));
// Write new Basic-Block count value
GenTree* counterAddrNode = comp->gtNewIconHandleNode(reinterpret_cast<size_t>(counterAddr), GTF_ICON_BBC_PTR);
GenTree* updateNode = comp->gtNewStoreIndNode(countType, counterAddrNode, incValueNode);
return updateNode;
}
//------------------------------------------------------------------------
// SpanningTreeVisitor: abstract class for computations done while
// evolving a spanning tree.
//
class SpanningTreeVisitor
{
public:
// To save visitors a bit of work, we also note
// for non-tree edges whether the edge postdominates
// the source, dominates the target, or is a critical edge.
//
// Later we may need to relocate or duplicate probes. We
// overload this enum to also represent those cases.
//
enum class EdgeKind
{
Unknown,
PostdominatesSource,
Pseudo,
DominatesTarget,
CriticalEdge,
Deleted,
Relocated,
Leader,
Duplicate
};
virtual void Badcode() = 0;
virtual void VisitBlock(BasicBlock* block) = 0;
virtual void VisitTreeEdge(BasicBlock* source, BasicBlock* target) = 0;
virtual void VisitNonTreeEdge(BasicBlock* source, BasicBlock* target, EdgeKind kind) = 0;
};
//------------------------------------------------------------------------
// WalkSpanningTree: evolve a "maximal cost" depth first spanning tree,
// invoking the visitor as each edge is classified, or each node is first
// discovered.
//
// Arguments:
// visitor - visitor to notify
//
// Notes:
// We only have rudimentary weights at this stage, and so in practice
// we use a depth-first spanning tree (DFST) where we try to steer
// the DFS to preferentially visit "higher" cost edges.
//
// Since instrumentation happens after profile incorporation
// we could in principle use profile weights to steer the DFS or to build
// a true maximum weight tree. However we are relying on being able to
// rebuild the exact same spanning tree "later on" when doing a subsequent
// profile reconstruction. So, we restrict ourselves to just using
// information apparent in the IL.
//
void Compiler::WalkSpanningTree(SpanningTreeVisitor* visitor)
{
// We will track visited or queued nodes with a bit vector.
//
BitVecTraits traits(compBasicBlockID, this);
BitVec marked = BitVecOps::MakeEmpty(&traits);
// And nodes to visit with a bit vector and stack.
//
ArrayStack<BasicBlock*> stack(getAllocator(CMK_Pgo));
// Scratch vector for visiting successors of blocks with
// multiple successors.
//
// Bit vector to track progress through those successors.
//
ArrayStack<BasicBlock*> scratch(getAllocator(CMK_Pgo));
BitVec processed = BitVecOps::MakeEmpty(&traits);
// Push the method entry and all EH handler region entries on the stack.
// (push method entry last so it's visited first).
//
// Note inlinees are "contaminated" with root method EH structures.
// We know the inlinee itself doesn't have EH, so we only look at
// handlers for root methods.
//
// If we ever want to support inlining methods with EH, we'll
// have to revisit this.
//
if (!compIsForInlining())
{
for (EHblkDsc* const HBtab : EHClauses(this))
{
BasicBlock* hndBegBB = HBtab->ebdHndBeg;
stack.Push(hndBegBB);
BitVecOps::AddElemD(&traits, marked, hndBegBB->bbID);
if (HBtab->HasFilter())
{
BasicBlock* filterBB = HBtab->ebdFilter;
stack.Push(filterBB);
BitVecOps::AddElemD(&traits, marked, filterBB->bbID);
}
}
}
stack.Push(fgFirstBB);
BitVecOps::AddElemD(&traits, marked, fgFirstBB->bbID);
unsigned nBlocks = 0;
while (!stack.Empty())
{
BasicBlock* const block = stack.Pop();
// Visit the block.
//
assert(BitVecOps::IsMember(&traits, marked, block->bbID));
visitor->VisitBlock(block);
nBlocks++;
switch (block->GetKind())
{
case BBJ_CALLFINALLY:
{
// Just queue up the continuation block,
// unless the finally doesn't return, in which
// case we really should treat this block as a throw,
// and so this block would get instrumented.
//
// Since our keying scheme is IL based and this
// block has no IL offset, we'd need to invent
// some new keying scheme. For now we just
// ignore this (rare) case.
//
if (block->isBBCallFinallyPair())
{
// This block should be the only pred of the continuation.
//
BasicBlock* const target = block->Next();
assert(!BitVecOps::IsMember(&traits, marked, target->bbID));
visitor->VisitTreeEdge(block, target);
stack.Push(target);
BitVecOps::AddElemD(&traits, marked, target->bbID);
}
}
break;
case BBJ_THROW:
// Ignore impact of throw blocks on flow, if we're doing minimal
// method profiling, and it appears the method can return without throwing.
//
// fgReturnCount is provisionally set in fgFindBasicBlocks based on
// the raw IL stream prescan.
//
if (JitConfig.JitMinimalJitProfiling() && (fgReturnCount > 0))
{
break;
}
__fallthrough;
case BBJ_RETURN:
{
// Pseudo-edge back to method entry.
//
// Note if the throw is caught locally this will over-state the profile
// count for method entry. But we likely don't care too much about
// profiles for methods that throw lots of exceptions.
//
BasicBlock* const target = fgFirstBB;
assert(BitVecOps::IsMember(&traits, marked, target->bbID));
visitor->VisitNonTreeEdge(block, target, SpanningTreeVisitor::EdgeKind::Pseudo);
}
break;
case BBJ_EHFINALLYRET:
case BBJ_EHFAULTRET:
case BBJ_EHCATCHRET:
case BBJ_EHFILTERRET:
case BBJ_LEAVE:
{
// See if we're leaving an EH handler region.
//
bool isInTry = false;
unsigned const regionIndex = ehGetMostNestedRegionIndex(block, &isInTry);
EHblkDsc* const dsc = ehGetBlockHndDsc(block);
if (isInTry || (dsc->ebdHandlerType == EH_HANDLER_CATCH))
{
// We're leaving a try or catch, not a handler.
// Treat this as a normal edge.
//
BasicBlock* const target = block->GetTarget();
// In some bad IL cases we may not have a target.
// In others we may see something other than LEAVE be most-nested in a try.
//
if (target == nullptr)
{
JITDUMP("No jump dest for " FMT_BB ", suspect bad code\n", block->bbNum);
visitor->Badcode();
}
else if (!block->KindIs(BBJ_LEAVE))
{
JITDUMP("EH RET in " FMT_BB " most-nested in try, suspect bad code\n", block->bbNum);
visitor->Badcode();
}
else
{
if (BitVecOps::IsMember(&traits, marked, target->bbID))
{
visitor->VisitNonTreeEdge(block, target,
SpanningTreeVisitor::EdgeKind::PostdominatesSource);
}
else
{
visitor->VisitTreeEdge(block, target);
stack.Push(target);
BitVecOps::AddElemD(&traits, marked, target->bbID);
}
}
}
else
{
// Pseudo-edge back to handler entry.
//
BasicBlock* const target = dsc->ebdHndBeg;
assert(BitVecOps::IsMember(&traits, marked, target->bbID));
visitor->VisitNonTreeEdge(block, target, SpanningTreeVisitor::EdgeKind::Pseudo);
}
}
break;
default:
{
// If this block is a control flow fork, we want to
// preferentially visit critical edges first; if these
// edges end up in the DFST then instrumentation will
// require edge splitting.
//