forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfgdiagnostic.cpp
4757 lines (4179 loc) · 162 KB
/
fgdiagnostic.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 "allocacheck.h" // for alloca
#include "jitstd/algorithm.h"
// Flowgraph Check and Dump Support
#ifdef DEBUG
void Compiler::fgPrintEdgeWeights()
{
// Print out all of the edge weights
for (BasicBlock* const bDst : Blocks())
{
if (bDst->bbPreds != nullptr)
{
printf(" Edge weights into " FMT_BB " :", bDst->bbNum);
for (FlowEdge* const edge : bDst->PredEdges())
{
BasicBlock* bSrc = edge->getSourceBlock();
// This is the control flow edge (bSrc -> bDst)
printf(FMT_BB " ", bSrc->bbNum);
const weight_t weight = edge->getLikelyWeight();
if (weight < BB_MAX_WEIGHT)
{
printf("(%f)", weight);
}
else
{
printf("(MAX)");
}
if (edge->getNextPredEdge() != nullptr)
{
printf(", ");
}
}
printf("\n");
}
}
}
#endif // DEBUG
/*****************************************************************************
* Check that the flow graph is really updated
*/
#ifdef DEBUG
void Compiler::fgDebugCheckUpdate()
{
if (!compStressCompile(STRESS_CHK_FLOW_UPDATE, 30))
{
return;
}
/* We check for these conditions:
* no unreachable blocks -> no blocks have countOfInEdges() = 0
* no empty blocks -> !block->isEmpty(), unless non-removable or multiple in-edges
* no un-imported blocks -> no blocks have BBF_IMPORTED not set (this is
* kind of redundant with the above, but to make sure)
* no un-compacted blocks -> BBJ_ALWAYS with jump to block with no other jumps to it (countOfInEdges() = 1)
*/
BasicBlock* prev;
BasicBlock* block;
for (prev = nullptr, block = fgFirstBB; block != nullptr; prev = block, block = block->Next())
{
/* no unreachable blocks */
if ((block->countOfInEdges() == 0) && !block->HasFlag(BBF_DONT_REMOVE))
{
noway_assert(!"Unreachable block not removed!");
}
/* no empty blocks */
if (block->isEmpty() && !block->HasFlag(BBF_DONT_REMOVE))
{
switch (block->GetKind())
{
case BBJ_CALLFINALLY:
case BBJ_EHFINALLYRET:
case BBJ_EHFAULTRET:
case BBJ_EHFILTERRET:
case BBJ_RETURN:
/* for BBJ_ALWAYS is probably just a GOTO, but will have to be treated */
case BBJ_ALWAYS:
case BBJ_EHCATCHRET:
/* These jump kinds are allowed to have empty tree lists */
break;
default:
/* it may be the case that the block had more than one reference to it
* so we couldn't remove it */
if (block->countOfInEdges() == 0)
{
noway_assert(!"Empty block not removed!");
}
break;
}
}
/* no un-imported blocks */
if (!block->HasFlag(BBF_IMPORTED))
{
/* internal blocks do not count */
if (!block->HasFlag(BBF_INTERNAL))
{
noway_assert(!"Non IMPORTED block not removed!");
}
}
// Check for an unnecessary jumps to the next block.
// A conditional branch should never jump to the next block as it can be folded into a BBJ_ALWAYS.
if (block->KindIs(BBJ_COND) && block->TrueEdgeIs(block->GetFalseEdge()))
{
noway_assert(!"Unnecessary jump to the next block!");
}
// For a BBJ_CALLFINALLY block we make sure that we are followed by a BBJ_CALLFINALLYRET block
// or that it's a BBF_RETLESS_CALL.
if (block->KindIs(BBJ_CALLFINALLY))
{
assert(block->HasFlag(BBF_RETLESS_CALL) || block->isBBCallFinallyPair());
}
/* no un-compacted blocks */
if (fgCanCompactBlock(block))
{
noway_assert(!"Found un-compacted blocks!");
}
}
}
#endif // DEBUG
#if DUMP_FLOWGRAPHS
struct escapeMapping_t
{
char ch;
const char* sub;
};
// clang-format off
static escapeMapping_t s_EscapeFileMapping[] =
{
{' ', "_"},
{':', "_"},
{',', "_"},
{'<', "~lt~"},
{'>', "~gt~"},
{';', "~semi~"},
{'|', "~bar~"},
{'&', "~amp~"},
{'"', "~quot~"},
{'*', "~star~"},
{0, nullptr}
};
static escapeMapping_t s_EscapeMapping[] =
{
{'<', "<"},
{'>', ">"},
{'&', "&"},
{'"', """},
{0, nullptr}
};
// clang-format on
const char* Compiler::fgProcessEscapes(const char* nameIn, escapeMapping_t* map)
{
const char* nameOut = nameIn;
unsigned lengthOut;
unsigned index;
bool match;
bool substitutionRequired;
const char* pChar;
lengthOut = 1;
substitutionRequired = false;
pChar = nameIn;
while (*pChar != '\0')
{
match = false;
index = 0;
while (map[index].ch != 0)
{
if (*pChar == map[index].ch)
{
match = true;
break;
}
index++;
}
if (match)
{
substitutionRequired = true;
lengthOut += (unsigned)strlen(map[index].sub);
}
else
{
lengthOut += 1;
}
pChar++;
}
if (substitutionRequired)
{
char* newName = getAllocator(CMK_DebugOnly).allocate<char>(lengthOut);
char* pDest;
pDest = newName;
pChar = nameIn;
while (*pChar != '\0')
{
match = false;
index = 0;
while (map[index].ch != 0)
{
if (*pChar == map[index].ch)
{
match = true;
break;
}
index++;
}
if (match)
{
strcpy(pDest, map[index].sub);
pDest += strlen(map[index].sub);
}
else
{
*pDest++ = *pChar;
}
pChar++;
}
*pDest++ = '\0';
nameOut = (const char*)newName;
}
return nameOut;
}
static void fprintfDouble(FILE* fgxFile, double value)
{
assert(value >= 0.0);
if ((value >= 0.010) || (value == 0.0))
{
fprintf(fgxFile, "\"%7.3f\"", value);
}
else if (value >= 0.00010)
{
fprintf(fgxFile, "\"%7.5f\"", value);
}
else
{
fprintf(fgxFile, "\"%7E\"", value);
}
}
//------------------------------------------------------------------------
// fgDumpTree: Dump a tree into the DOT file. Used to provide a very short, one-line,
// visualization of a BBJ_COND block.
//
// Arguments:
// fgxFile - The file we are writing to.
// tree - The operand to dump.
//
// static
void Compiler::fgDumpTree(FILE* fgxFile, GenTree* const tree)
{
if (tree->OperIsCompare())
{
// Want to generate something like:
// V01 <= 7
// V01 > V02
const char* opName = GenTree::OpName(tree->OperGet());
// Make it look nicer if we can
switch (tree->OperGet())
{
case GT_EQ:
opName = "==";
break;
case GT_NE:
opName = "!=";
break;
case GT_LT:
opName = "<";
break;
case GT_LE:
opName = "<=";
break;
case GT_GE:
opName = ">=";
break;
case GT_GT:
opName = ">";
break;
default:
break;
}
GenTree* const lhs = tree->AsOp()->gtOp1;
GenTree* const rhs = tree->AsOp()->gtOp2;
fgDumpTree(fgxFile, lhs);
fprintf(fgxFile, " %s ", opName);
fgDumpTree(fgxFile, rhs);
}
else if (tree->IsCnsIntOrI())
{
fprintf(fgxFile, "%d", tree->AsIntCon()->gtIconVal);
}
else if (tree->IsCnsFltOrDbl())
{
fprintf(fgxFile, "%g", tree->AsDblCon()->DconValue());
}
else if (tree->IsLocal())
{
fprintf(fgxFile, "V%02u", tree->AsLclVarCommon()->GetLclNum());
}
else if (tree->OperIs(GT_ARR_LENGTH))
{
GenTreeArrLen* arrLen = tree->AsArrLen();
GenTree* arr = arrLen->ArrRef();
fgDumpTree(fgxFile, arr);
fprintf(fgxFile, ".Length");
}
else if (tree->OperIs(GT_MDARR_LENGTH))
{
GenTreeMDArr* arrOp = tree->AsMDArr();
GenTree* arr = arrOp->ArrRef();
unsigned dim = arrOp->Dim();
fgDumpTree(fgxFile, arr);
fprintf(fgxFile, ".GetLength(%u)", dim);
}
else if (tree->OperIs(GT_MDARR_LOWER_BOUND))
{
GenTreeMDArr* arrOp = tree->AsMDArr();
GenTree* arr = arrOp->ArrRef();
unsigned dim = arrOp->Dim();
fgDumpTree(fgxFile, arr);
fprintf(fgxFile, ".GetLowerBound(%u)", dim);
}
else
{
fprintf(fgxFile, "[%s]", GenTree::OpName(tree->OperGet()));
}
}
//------------------------------------------------------------------------
// fgOpenFlowGraphFile: Open a file to dump either the xml or dot format flow graph
//
// Arguments:
// wbDontClose - A boolean out argument that indicates whether the caller should close the file
// phase - A phase identifier to indicate which phase is associated with the dump
// pos - Are we being called to dump the flow graph pre-phase or post-phase?
// type - A (wide) string indicating the type of dump, "dot" or "xml"
//
// Notes:
// The filename to use to write the data comes from the DOTNET_JitDumpFgFile or DOTNET_NgenDumpFgFile
// configuration. If unset, use "default". The "type" argument is used as a filename extension,
// e.g., "default.dot".
//
// There are several "special" filenames recognized:
// "profiled" -- only create graphs for methods with profile info, one file per method.
// "hot" -- only create graphs for the hot region, one file per method.
// "cold" -- only create graphs for the cold region, one file per method.
// "jit" -- only create graphs for JITing, one file per method.
// "all" -- create graphs for all regions, one file per method.
// "stdout" -- output to stdout, not a file.
// "stderr" -- output to stderr, not a file.
//
// Return Value:
// Opens a file to which a flowgraph can be dumped, whose name is based on the current
// config vales.
//
FILE* Compiler::fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, PhasePosition pos, const char* type)
{
FILE* fgxFile;
const char* prePhasePattern = nullptr; // pre-phase: default (used in Release) is no pre-phase dump
const char* postPhasePattern = "*"; // post-phase: default (used in Release) is dump all phases
bool dumpFunction = true; // default (used in Release) is always dump
const char* filename = nullptr;
const char* pathname = nullptr;
const char* escapedString;
if (fgBBcount <= 1)
{
return nullptr;
}
#ifdef DEBUG
dumpFunction = JitConfig.JitDumpFg().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args);
CompAllocator allocator = getAllocatorDebugOnly();
filename = JitConfig.JitDumpFgFile();
pathname = JitConfig.JitDumpFgDir();
prePhasePattern = JitConfig.JitDumpFgPrePhase();
postPhasePattern = JitConfig.JitDumpFgPhase();
#endif // DEBUG
if (!dumpFunction)
{
return nullptr;
}
const char* phaseName = PhaseEnums[phase] + strlen("PHASE_");
if (pos == PhasePosition::PrePhase)
{
if (prePhasePattern == nullptr)
{
// If pre-phase pattern is not specified, then don't dump for any pre-phase.
return nullptr;
}
else if (*prePhasePattern != '*')
{
if (strstr(prePhasePattern, phaseName) == nullptr)
{
return nullptr;
}
}
}
else
{
assert(pos == PhasePosition::PostPhase);
if (postPhasePattern == nullptr)
{
// There's no post-phase pattern specified. If there is a pre-phase pattern specified, then that will
// be the only set of phases dumped. If neither are specified, then post-phase dump after
// PHASE_DETERMINE_FIRST_COLD_BLOCK.
if (prePhasePattern != nullptr)
{
return nullptr;
}
if (phase != PHASE_DETERMINE_FIRST_COLD_BLOCK)
{
return nullptr;
}
}
else if (*postPhasePattern != '*')
{
if (strstr(postPhasePattern, phaseName) == nullptr)
{
return nullptr;
}
}
}
if (filename == nullptr)
{
filename = "default";
}
if (strcmp(filename, "profiled") == 0)
{
if (fgFirstBB->hasProfileWeight())
{
goto ONE_FILE_PER_METHOD;
}
else
{
return nullptr;
}
}
if (strcmp(filename, "hot") == 0)
{
if (info.compMethodInfo->regionKind == CORINFO_REGION_HOT)
{
goto ONE_FILE_PER_METHOD;
}
else
{
return nullptr;
}
}
else if (strcmp(filename, "cold") == 0)
{
if (info.compMethodInfo->regionKind == CORINFO_REGION_COLD)
{
goto ONE_FILE_PER_METHOD;
}
else
{
return nullptr;
}
}
else if (strcmp(filename, "jit") == 0)
{
if (info.compMethodInfo->regionKind == CORINFO_REGION_JIT)
{
goto ONE_FILE_PER_METHOD;
}
else
{
return nullptr;
}
}
else if (strcmp(filename, "all") == 0)
{
ONE_FILE_PER_METHOD:;
#define FILENAME_PATTERN "%s-%s-%s-%s.%s"
#define FILENAME_PATTERN_WITH_NUMBER "%s-%s-%s-%s~%d.%s"
const size_t MaxFileNameLength = MAX_PATH_FNAME - 20 /* give us some extra buffer */;
escapedString = fgProcessEscapes(info.compFullName, s_EscapeFileMapping);
size_t escapedStringLen = strlen(escapedString);
static const char* phasePositionStrings[] = {"pre", "post"};
assert((unsigned)pos < ArrLen(phasePositionStrings));
const char* phasePositionString = phasePositionStrings[(unsigned)pos];
const size_t phasePositionStringLen = strlen(phasePositionString);
const char* tierName = compGetTieringName(true);
size_t charCount = escapedStringLen + 1 + strlen(phasePositionString) + 1 + strlen(phaseName) + 1 +
strlen(tierName) + strlen("~999") + 1 + strlen(type) + 1;
if (charCount > MaxFileNameLength)
{
// Crop the escapedString.
charCount -= escapedStringLen;
size_t newEscapedStringLen = MaxFileNameLength - charCount;
char* newEscapedString = getAllocator(CMK_DebugOnly).allocate<char>(newEscapedStringLen + 1);
strncpy_s(newEscapedString, newEscapedStringLen + 1, escapedString, newEscapedStringLen);
newEscapedString[newEscapedStringLen] = '\0';
escapedString = newEscapedString;
escapedStringLen = newEscapedStringLen;
charCount += escapedStringLen;
}
if (pathname != nullptr)
{
charCount += strlen(pathname) + 1;
}
filename = (const char*)_alloca(charCount * sizeof(char));
if (pathname != nullptr)
{
sprintf_s((char*)filename, charCount, "%s\\" FILENAME_PATTERN, pathname, escapedString, phasePositionString,
phaseName, tierName, type);
}
else
{
sprintf_s((char*)filename, charCount, FILENAME_PATTERN, escapedString, phasePositionString, phaseName,
tierName, type);
}
fgxFile = fopen_utf8(filename, "wx"); // Open the file for writing only only if it doesn't already exist
if (fgxFile == nullptr)
{
// This filename already exists, so create a different one by appending ~2, ~3, etc...
for (int i = 2; i < 1000; i++)
{
if (pathname != nullptr)
{
sprintf_s((char*)filename, charCount, "%s\\" FILENAME_PATTERN_WITH_NUMBER, pathname, escapedString,
phasePositionString, phaseName, tierName, i, type);
}
else
{
sprintf_s((char*)filename, charCount, FILENAME_PATTERN_WITH_NUMBER, escapedString,
phasePositionString, phaseName, tierName, i, type);
}
fgxFile = fopen_utf8(filename, "wx"); // Open the file for writing only only if it doesn't already exist
if (fgxFile != nullptr)
{
break;
}
}
// If we have already created 1000 files with this name then just fail
if (fgxFile == nullptr)
{
return nullptr;
}
}
*wbDontClose = false;
}
else if (strcmp(filename, "stdout") == 0)
{
fgxFile = jitstdout();
*wbDontClose = true;
}
else if (strcmp(filename, "stderr") == 0)
{
fgxFile = stderr;
*wbDontClose = true;
}
else
{
const char* origFilename = filename;
size_t charCount = strlen(origFilename) + strlen(type) + 2;
if (pathname != nullptr)
{
charCount += strlen(pathname) + 1;
}
filename = (char*)_alloca(charCount * sizeof(char));
if (pathname != nullptr)
{
sprintf_s((char*)filename, charCount, "%s\\%s.%s", pathname, origFilename, type);
}
else
{
sprintf_s((char*)filename, charCount, "%s.%s", origFilename, type);
}
fgxFile = fopen_utf8(filename, "a+");
*wbDontClose = false;
}
return fgxFile;
}
//------------------------------------------------------------------------
// fgDumpFlowGraph: Dump the xml or dot format flow graph, if enabled for this phase.
//
// Arguments:
// phase - A phase identifier to indicate which phase is associated with the dump,
// i.e. which phase has just completed.
// pos - Are we being called to dump the flow graph pre-phase or post-phase?
//
// Return Value:
// True iff a flowgraph has been dumped.
//
// Notes:
// The xml dumps are the historical mechanism for dumping the flowgraph.
// The dot format can be viewed by:
// - https://sketchviz.com/
// - Graphviz (http://www.graphviz.org/)
// - The command:
// "C:\Program Files (x86)\Graphviz2.38\bin\dot.exe" -Tsvg -oFoo.svg -Kdot Foo.dot
// will produce a Foo.svg file that can be opened with any svg-capable browser.
// - http://rise4fun.com/Agl/
// - Cut and paste the graph from your .dot file, replacing the digraph on the page, and then click the play
// button.
// - It will show a rotating '/' and then render the graph in the browser.
// MSAGL has also been open-sourced to https://github.com/Microsoft/automatic-graph-layout.
//
// Here are the config values that control it:
// DOTNET_JitDumpFg A string (ala the DOTNET_JitDump string) indicating what methods to dump
// flowgraphs for.
// DOTNET_JitDumpFgDir A path to a directory into which the flowgraphs will be dumped.
// DOTNET_JitDumpFgFile The filename to use. The default is "default.[xml|dot]".
// Note that the new graphs will be appended to this file if it already exists.
// DOTNET_JitDumpFgPhase Phase(s) after which to dump the flowgraph.
// Set to the short name of a phase to see the flowgraph after that phase.
// Leave unset to dump after COLD-BLK (determine first cold block) or set to *
// for all phases.
// DOTNET_JitDumpFgPrePhase Phase(s) before which to dump the flowgraph.
// DOTNET_JitDumpFgDot 0 for xml format, non-zero for dot format. (Default is dot format.)
// DOTNET_JitDumpFgEH (dot only) 0 for no exception-handling information; non-zero to include
// exception-handling regions.
// DOTNET_JitDumpFgLoops (dot only) 0 for no loop information; non-zero to include loop regions.
// DOTNET_JitDumpFgConstrained (dot only) 0 == don't constrain to mostly linear layout; non-zero == force
// mostly lexical block linear layout.
// DOTNET_JitDumpFgBlockId Display blocks with block ID, not just bbNum.
//
// Example:
//
// If you want to dump just before and after a single phase, say loop cloning, use:
// set DOTNET_JitDumpFgPhase=LP-CLONE
// set DOTNET_JitDumpFgPrePhase=LP-CLONE
//
bool Compiler::fgDumpFlowGraph(Phases phase, PhasePosition pos)
{
bool result = false;
bool dontClose = false;
#ifdef DEBUG
const bool createDotFile = JitConfig.JitDumpFgDot() != 0;
const bool includeEH = (JitConfig.JitDumpFgEH() != 0) && !compIsForInlining();
const bool includeLoops = (JitConfig.JitDumpFgLoops() != 0) && !compIsForInlining();
const bool constrained = JitConfig.JitDumpFgConstrained() != 0;
const bool useBlockId = JitConfig.JitDumpFgBlockID() != 0;
const bool displayBlockFlags = JitConfig.JitDumpFgBlockFlags() != 0;
#else // !DEBUG
const bool createDotFile = true;
const bool includeEH = false;
const bool includeLoops = false;
const bool constrained = true;
const bool useBlockId = false;
const bool displayBlockFlags = false;
#endif // !DEBUG
FILE* fgxFile = fgOpenFlowGraphFile(&dontClose, phase, pos, createDotFile ? "dot" : "fgx");
if (fgxFile == nullptr)
{
return false;
}
JITDUMP("Writing out flow graph %s phase %s\n", (pos == PhasePosition::PrePhase) ? "before" : "after",
PhaseNames[phase]);
double weightDivisor = (double)BasicBlock::getCalledCount(this);
const char* escapedString;
const char* regionString = "NONE";
if (info.compMethodInfo->regionKind == CORINFO_REGION_HOT)
{
regionString = "HOT";
}
else if (info.compMethodInfo->regionKind == CORINFO_REGION_COLD)
{
regionString = "COLD";
}
else if (info.compMethodInfo->regionKind == CORINFO_REGION_JIT)
{
regionString = "JIT";
}
if (createDotFile)
{
fprintf(fgxFile, "digraph FlowGraph {\n");
fprintf(fgxFile, " graph [label = \"%s%s\\n%s\\n%s\"];\n", info.compMethodName,
compIsForInlining() ? "\\n(inlinee)" : "", (pos == PhasePosition::PrePhase) ? "before" : "after",
PhaseNames[phase]);
fprintf(fgxFile, " node [shape = \"Box\"];\n");
}
else
{
fprintf(fgxFile, "<method");
escapedString = fgProcessEscapes(info.compFullName, s_EscapeMapping);
fprintf(fgxFile, "\n name=\"%s\"", escapedString);
escapedString = fgProcessEscapes(info.compClassName, s_EscapeMapping);
fprintf(fgxFile, "\n className=\"%s\"", escapedString);
escapedString = fgProcessEscapes(info.compMethodName, s_EscapeMapping);
fprintf(fgxFile, "\n methodName=\"%s\"", escapedString);
fprintf(fgxFile, "\n ngenRegion=\"%s\"", regionString);
fprintf(fgxFile, "\n bytesOfIL=\"%d\"", info.compILCodeSize);
fprintf(fgxFile, "\n localVarCount=\"%d\"", lvaCount);
if (fgHaveProfileWeights())
{
fprintf(fgxFile, "\n calledCount=\"%f\"", fgCalledCount);
fprintf(fgxFile, "\n profileData=\"true\"");
}
if (compHndBBtabCount > 0)
{
fprintf(fgxFile, "\n hasEHRegions=\"true\"");
}
if (fgHasLoops)
{
fprintf(fgxFile, "\n hasLoops=\"true\"");
}
if (fgFirstColdBlock != nullptr)
{
fprintf(fgxFile, "\n firstColdBlock=\"%d\"", fgFirstColdBlock->bbNum);
}
fprintf(fgxFile, ">");
fprintf(fgxFile, "\n <blocks");
fprintf(fgxFile, "\n blockCount=\"%d\"", fgBBcount);
fprintf(fgxFile, ">");
}
// In some cases, we want to change the display based on whether an edge is lexically backwards, forwards,
// or lexical successor. Also, for the region tree, using the lexical order is useful for determining where
// to insert in the tree, to determine nesting. We'd like to use the bbNum to do this. However, we don't
// want to renumber the blocks. So, create a mapping of bbNum to ordinal, and compare block order by
// comparing the mapped ordinals instead.
//
// For inlinees, the max block number of the inliner is used, so we need to allocate the block map based on
// that size, even though it means allocating a block map possibly much bigger than what's required for just
// the inlinee blocks.
unsigned blkMapSize = 1 + fgBBNumMax;
unsigned blockOrdinal = 1;
unsigned* blkMap = new (this, CMK_DebugOnly) unsigned[blkMapSize];
memset(blkMap, 0, sizeof(unsigned) * blkMapSize);
for (BasicBlock* const block : Blocks())
{
assert(block->bbNum < blkMapSize);
blkMap[block->bbNum] = blockOrdinal++;
}
static const char* kindImage[] = {"EHFINALLYRET", "EHFILTERRET", "EHCATCHRET", "THROW", "RETURN", "NONE",
"ALWAYS", "LEAVE", "CALLFINALLY", "COND", "SWITCH"};
BasicBlock* block;
for (block = fgFirstBB, blockOrdinal = 1; block != nullptr; block = block->Next(), blockOrdinal++)
{
if (createDotFile)
{
fprintf(fgxFile, " " FMT_BB " [label = \"", block->bbNum);
if (useBlockId)
{
fprintf(fgxFile, "%s", block->dspToString());
}
else
{
fprintf(fgxFile, FMT_BB, block->bbNum);
}
if (displayBlockFlags)
{
// Don't display the `[` `]` unless we're going to display something.
const bool isTryEntryBlock = bbIsTryBeg(block);
if (isTryEntryBlock ||
block->HasAnyFlag(BBF_FUNCLET_BEG | BBF_RUN_RARELY | BBF_LOOP_HEAD | BBF_LOOP_ALIGN))
{
// Display a very few, useful, block flags
fprintf(fgxFile, " [");
if (isTryEntryBlock)
{
fprintf(fgxFile, "T");
}
if (block->HasFlag(BBF_FUNCLET_BEG))
{
fprintf(fgxFile, "F");
}
if (block->HasFlag(BBF_RUN_RARELY))
{
fprintf(fgxFile, "R");
}
if (block->HasFlag(BBF_LOOP_HEAD))
{
fprintf(fgxFile, "L");
}
if (block->HasFlag(BBF_LOOP_ALIGN))
{
fprintf(fgxFile, "A");
}
fprintf(fgxFile, "]");
}
}
// Optionally show GC Heap Mem SSA state and Memory Phis
//
if ((JitConfig.JitDumpFgMemorySsa() != 0) && (fgSsaPassesCompleted > 0))
{
fprintf(fgxFile, "\\n");
MemoryKind k = MemoryKind::GcHeap;
const unsigned ssaIn = block->bbMemorySsaNumIn[k];
const unsigned ssaOut = block->bbMemorySsaNumOut[k];
if (ssaIn != SsaConfig::RESERVED_SSA_NUM)
{
ValueNum vnIn = GetMemoryPerSsaData(ssaIn)->m_vnPair.GetLiberal();
BasicBlock::MemoryPhiArg* memPhi = block->bbMemorySsaPhiFunc[k];
if ((memPhi != nullptr) && (memPhi != BasicBlock::EmptyMemoryPhiDef))
{
fprintf(fgxFile, "MI %d " FMT_VN " = PHI(", ssaIn, vnIn);
bool first = true;
for (; memPhi != nullptr; memPhi = memPhi->m_nextArg)
{
ValueNum phiVN = GetMemoryPerSsaData(memPhi->GetSsaNum())->m_vnPair.GetLiberal();
fprintf(fgxFile, "%s%d " FMT_VN, first ? "" : ",", memPhi->m_ssaNum, phiVN);
first = false;
}
fprintf(fgxFile, ")");
}
else
{
ValueNum vn = GetMemoryPerSsaData(block->bbMemorySsaNumIn[k])->m_vnPair.GetLiberal();
fprintf(fgxFile, "MI %d " FMT_VN, block->bbMemorySsaNumIn[k], vn);
}
fprintf(fgxFile, "\\n");
if (block->bbMemoryHavoc != 0)
{
fprintf(fgxFile, "** HAVOC **\\n");
}
ValueNum vnOut = GetMemoryPerSsaData(ssaOut)->m_vnPair.GetLiberal();
fprintf(fgxFile, "MO %d " FMT_VN, ssaOut, vnOut);
}
}
if (block->KindIs(BBJ_COND))
{
fprintf(fgxFile, "\\n");
// Include a line with the basics of the branch condition, if possible.
// Find the loop termination test at the bottom of the loop.
Statement* condStmt = block->lastStmt();
if (condStmt != nullptr)
{
GenTree* const condTree = condStmt->GetRootNode();
noway_assert(condTree->gtOper == GT_JTRUE);
GenTree* const compareTree = condTree->AsOp()->gtOp1;
fgDumpTree(fgxFile, compareTree);
}
}
// "Raw" Profile weight
if (block->hasProfileWeight() || (JitConfig.JitSynthesizeCounts() > 0))
{
fprintf(fgxFile, "\\n\\n%7.2f", ((double)block->getBBWeight(this)) / BB_UNITY_WEIGHT);
}
// end of block label
fprintf(fgxFile, "\"");
// other node attributes
//
if (block == fgFirstBB)
{
fprintf(fgxFile, ", shape = \"house\"");
}
else if (block->KindIs(BBJ_RETURN))
{
fprintf(fgxFile, ", shape = \"invhouse\"");
}
else if (block->KindIs(BBJ_THROW))
{
fprintf(fgxFile, ", shape = \"trapezium\"");
}
else if (block->HasFlag(BBF_INTERNAL))
{
fprintf(fgxFile, ", shape = \"note\"");
}
fprintf(fgxFile, "];\n");
}
else
{
fprintf(fgxFile, "\n <block");
fprintf(fgxFile, "\n id=\"%d\"", block->bbNum);
fprintf(fgxFile, "\n ordinal=\"%d\"", blockOrdinal);
fprintf(fgxFile, "\n jumpKind=\"%s\"", kindImage[block->GetKind()]);
if (block->hasTryIndex())
{
fprintf(fgxFile, "\n inTry=\"%s\"", "true");
}
if (block->hasHndIndex())
{
fprintf(fgxFile, "\n inHandler=\"%s\"", "true");
}
if ((fgFirstBB->hasProfileWeight()) && !block->HasFlag(BBF_COLD))
{
fprintf(fgxFile, "\n hot=\"true\"");
}
if (block->HasFlag(BBF_HAS_NEWARR))
{
fprintf(fgxFile, "\n callsNewArr=\"true\"");
}
if (block->HasFlag(BBF_HAS_NEWOBJ))
{
fprintf(fgxFile, "\n callsNew=\"true\"");
}
if (block->HasFlag(BBF_HAS_NEWARR))
{
fprintf(fgxFile, "\n callsNewArr=\"true\"");
}
if (block->HasFlag(BBF_LOOP_HEAD))
{
fprintf(fgxFile, "\n loopHead=\"true\"");
}
const char* rootTreeOpName = "n/a";
if (block->IsLIR() || (block->lastStmt() != nullptr))
{
if (block->lastNode() != nullptr)
{
rootTreeOpName = GenTree::OpName(block->lastNode()->OperGet());
}
}
fprintf(fgxFile, "\n weight=");
fprintfDouble(fgxFile, ((double)block->bbWeight) / weightDivisor);
// fgGetCodeEstimate() will assert if the costs have not yet been initialized.
// fprintf(fgxFile, "\n codeEstimate=\"%d\"", fgGetCodeEstimate(block));
fprintf(fgxFile, "\n startOffset=\"%d\"", block->bbCodeOffs);
fprintf(fgxFile, "\n rootTreeOp=\"%s\"", rootTreeOpName);
fprintf(fgxFile, "\n endOffset=\"%d\"", block->bbCodeOffsEnd);
fprintf(fgxFile, ">");
fprintf(fgxFile, "\n </block>");
}
}
if (!createDotFile)
{
fprintf(fgxFile, "\n </blocks>");
fprintf(fgxFile, "\n <edges>");