File: Stats.cpp

package info (click to toggle)
intel-graphics-compiler 1.0.12504.6-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 83,912 kB
  • sloc: cpp: 910,147; lisp: 202,655; ansic: 15,197; python: 4,025; yacc: 2,241; lex: 1,570; pascal: 244; sh: 104; makefile: 25
file content (1529 lines) | stat: -rw-r--r-- 51,823 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2021 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#include "common/Stats.hpp"
#include "Compiler/CodeGenPublic.h"
#include "common/debug/Dump.hpp"

#include <iStdLib/File.h>
#include <iStdLib/Timestamp.h>

#include "common/LLVMWarningsPush.hpp"
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/Support/Debug.h>
#include "common/LLVMWarningsPop.hpp"

#include "common/secure_string.h"
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <iostream>
#include "Probe/Assertion.h"

#if GET_TIME_STATS
// Functions exposed by VISA lib API
extern "C" int64_t getTimerTicks(unsigned int idx);
extern "C" double getTimerCounts(unsigned int idx);
extern "C" void getTimerNames(char* timerName, unsigned int idx);
extern "C" unsigned int getTimerHits(unsigned int idx);
extern "C" unsigned int getTotalTimers();
#endif

namespace {
    static const unsigned g_cIndentSZ = 4; //<! number of spaces to indent by
}

const char* g_cShaderStatItems[STATS_MAX_SHADER_STATS_ITEMS+1] =
{
#define DEFINE_SHADER_STAT( enumName, stringName ) stringName,
#include "shaderStats.h"
#undef DEFINE_SHADER_STAT
};

#if GET_SHADER_STATS

int ShaderStats::getShaderStats( SHADER_STATS_ITEMS compileInterval )
{
    IGC_ASSERT(0 <= compileInterval);
    IGC_ASSERT(compileInterval < STATS_MAX_SHADER_STATS_ITEMS);
    return m_CompileShaderStats[compileInterval];
}

void ShaderStats::printSumShaderStats()
{
    std::string outputFile = IGC::Debug::GetShaderOutputFolder() + std::string("\\SQM\\")+"shaderStatSum.csv";
    std::string sqm_out = IGC::Debug::GetShaderOutputFolder() + std::string("\\SQM\\") + "sqmStats.txt";
    bool fileExist = 0, fileExist_sqm=0;

    FILE* fp = fopen(outputFile.c_str(), "r");
    if( fp )
    {
        fileExist = 1;
        fclose(fp);
    }

    FILE* fileName = fopen(outputFile.c_str(), "a");

    FILE* fp_sqm = fopen(sqm_out.c_str(), "r");
    if (fp_sqm)
    {
        fileExist_sqm = 1;
        fclose(fp_sqm);
    }

    FILE* fileName_sqm = fopen(sqm_out.c_str(), "a");

    if( !fileExist && fileName )
    {
        fprintf(fileName, "test label, shader type, shader count,");
        for (int i=0;i<STATS_MAX_SHADER_STATS_ITEMS;i++)
        {
            fprintf(fileName, "%s,", g_cShaderStatItems[i] );
        }
        fprintf(fileName, "\n");
    }

    if (fileName && m_totalShaderCount!=0)
    {
        fprintf(fileName, "%s,", IGC::Debug::GetShaderCorpusName() );
        fprintf(fileName, "%s,", ShaderTypeString[(int)m_shaderType] );
        fprintf(fileName, "%d,", m_totalShaderCount);
        for (int i=0;i<STATS_MAX_SHADER_STATS_ITEMS;i++)
        {
            fprintf(fileName, "%d,", m_CompileShaderStats[i] );
        }
        fprintf(fileName, "\n");

        fclose(fileName);
    }

    bool printToConsole = true;
    if (printToConsole && m_totalShaderCount!=0)
    {
        fprintf(fileName_sqm, "\n%d %s shaders\n", m_totalShaderCount, ShaderTypeString[(int)m_shaderType]);
        printf("\n%d %s shaders\n", m_totalShaderCount, ShaderTypeString[(int)m_shaderType]);
        if( m_CompileShaderStats[STATS_ISA_INST_COUNT] != 0 )
        {
            fprintf(fileName_sqm, "total SIMD8  isa count = %d\n", m_CompileShaderStats[STATS_ISA_INST_COUNT]);
            printf("total SIMD8  isa count = %d\n", m_CompileShaderStats[STATS_ISA_INST_COUNT] );
        }
        if( m_CompileShaderStats[STATS_ISA_INST_COUNT_SIMD16] != 0 )
        {
            fprintf(fileName_sqm, "total SIMD16 isa count = %d\n", m_CompileShaderStats[STATS_ISA_INST_COUNT_SIMD16]);
            printf("total SIMD16 isa count = %d\n", m_CompileShaderStats[STATS_ISA_INST_COUNT_SIMD16] );
        }
        if( m_CompileShaderStats[STATS_ISA_INST_COUNT_SIMD32] != 0 )
        {
            fprintf(fileName_sqm, "total SIMD32 isa count = %d\n", m_CompileShaderStats[STATS_ISA_INST_COUNT_SIMD32]);
            printf("total SIMD32 isa count = %d\n", m_CompileShaderStats[STATS_ISA_INST_COUNT_SIMD32] );
        }
        if (m_CompileShaderStats[STATS_ISA_SPILL8] != 0)
        {
            fprintf(fileName_sqm, "total SIMD8 spill count = %d\n", m_CompileShaderStats[STATS_ISA_SPILL8]);
            printf("total SIMD8 spill count = %d\n", m_CompileShaderStats[STATS_ISA_SPILL8]);
        }
        if (m_CompileShaderStats[STATS_ISA_SPILL16] != 0)
        {
            fprintf(fileName_sqm, "total SIMD16 spill count = %d\n", m_CompileShaderStats[STATS_ISA_SPILL16]);
            printf("total SIMD16 spill count = %d\n", m_CompileShaderStats[STATS_ISA_SPILL16]);
        }
        if (m_CompileShaderStats[STATS_ISA_SPILL32] != 0)
        {
            fprintf(fileName_sqm,"total SIMD32 spill count = %d\n", m_CompileShaderStats[STATS_ISA_SPILL32]);
            printf("total SIMD32 spill count = %d\n", m_CompileShaderStats[STATS_ISA_SPILL32]);
        }
        if (m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE8] != 0)
        {
            fprintf(fileName_sqm, "total SIMD8 cycle estimate = %d\n", m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE8]);
            printf("total SIMD8 cycle estimate = %d\n", m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE8]);
        }
        if (m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE16] != 0)
        {
            fprintf(fileName_sqm, "total SIMD16 cycle estimate = %d\n", m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE16]);
            printf("total SIMD16 cycle estimate = %d\n", m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE16]);
        }
        if (m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE32] != 0)
        {
            fprintf(fileName_sqm, "total SIMD32 cycle estimate = %d\n", m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE32]);
            printf("total SIMD32 cycle estimate = %d\n", m_CompileShaderStats[STATS_ISA_CYCLE_ESTIMATE32]);
        }
        if (m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE8] != 0)
        {
            fprintf(fileName_sqm, "total SIMD8 stall estimate = %d\n", m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE8]);
            printf("total SIMD8 stall estimate = %d\n", m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE8]);
        }
        if (m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE16] != 0)
        {
            fprintf(fileName_sqm, "total SIMD16 stall estimate = %d\n", m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE16]);
            printf("total SIMD16 stall estimate = %d\n", m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE16]);
        }
        if (m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE32] != 0)
        {
            fprintf(fileName_sqm, "total SIMD32 stall estimate = %d\n", m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE32]);
            printf("total SIMD32 stall estimate = %d\n", m_CompileShaderStats[STATS_ISA_STALL_ESTIMATE32]);
        }

        if (m_CompileShaderStats[STATS_GRF_USED_SIMD8] != 0)
        {
            fprintf(fileName_sqm, "total SIMD8 grf used = %d\n", m_CompileShaderStats[STATS_GRF_USED_SIMD8]);
            printf("total SIMD8 grf used = %d\n", m_CompileShaderStats[STATS_GRF_USED_SIMD8]);
        }
        if (m_CompileShaderStats[STATS_GRF_USED_SIMD16] != 0)
        {
            fprintf(fileName_sqm, "total SIMD16 grf used = %d\n", m_CompileShaderStats[STATS_GRF_USED_SIMD16]);
            printf("total SIMD16 grf used = %d\n", m_CompileShaderStats[STATS_GRF_USED_SIMD16]);
        }
        if (m_CompileShaderStats[STATS_GRF_USED_SIMD32] != 0)
        {
            fprintf(fileName_sqm, "total SIMD32 grf used = %d\n", m_CompileShaderStats[STATS_GRF_USED_SIMD32]);
            printf("total SIMD8 grf used = %d\n", m_CompileShaderStats[STATS_GRF_USED_SIMD32]);
        }
        if (m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD8] != 0)
        {
            fprintf(fileName_sqm, "total SIMD8 grf pressure = %d\n", m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD8]);
            printf("total SIMD8 grf pressure = %d\n", m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD8]);
        }
        if (m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD16] != 0)
        {
            fprintf(fileName_sqm, "total SIMD16 grf pressure = %d\n", m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD16]);
            printf("total SIMD16 grf pressure = %d\n", m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD16]);
        }
        if (m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD32] != 0)
        {
            fprintf(fileName_sqm, "total SIMD32 grf pressure = %d\n", m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD32]);
            printf("total SIMD32 grf pressure = %d\n", m_CompileShaderStats[STATS_GRF_PRESSURE_SIMD32]);
        }

        fprintf(fileName_sqm, "total SIMD8  shaders = %d\n", m_TotalSimd8);
        fprintf(fileName_sqm, "total SIMD16 shaders = %d\n", m_TotalSimd16);
        fprintf(fileName_sqm, "total SIMD32 shaders = %d\n", m_TotalSimd32);
        printf("total SIMD8  shaders = %d\n", m_TotalSimd8);
        printf("total SIMD16 shaders = %d\n", m_TotalSimd16);
        printf("total SIMD32 shaders = %d\n", m_TotalSimd32);
    }
    fclose(fileName);
}

void ShaderStats::printShaderStats( ShaderHash hash, ShaderType shaderType, const std::string &postFix)
{
    const std::string outputFilePath = IGC::Debug::GetShaderOutputFolder() + std::string("\\SQM\\") + IGC::Debug::GetShaderCorpusName() + "ShaderStats.csv";
    const char *outputFile = outputFilePath.c_str();

    bool fileExist = 0;

    FILE* fp = fopen(outputFile, "r");
    if (fp)
    {
        fileExist = 1;
        fclose(fp);
    }

    FILE* fileName = fopen(outputFile, "a");

    if (!fileExist)
    {
        fprintf(fileName, "shader,");
        for (int i = 0; i<STATS_MAX_SHADER_STATS_ITEMS; i++)
        {
            fprintf(fileName, "%s,", g_cShaderStatItems[i]);
        }
        fprintf(fileName, "\n");
    }

    std::string asmFileName;

        asmFileName =
            IGC::Debug::DumpName(IGC::Debug::GetShaderOutputName())
            .Type(shaderType)
            .Hash(hash)
            .Extension("asm")
            .str();
        if (asmFileName.find_last_of("\\") != std::string::npos)
        {
            asmFileName = asmFileName.substr(asmFileName.find_last_of("\\") + 1, asmFileName.size());
        }


    fprintf(fileName, "%s,", asmFileName.c_str());
    for (int i = 0; i<STATS_MAX_SHADER_STATS_ITEMS; i++)
    {
        fprintf(fileName, "%d,", m_CompileShaderStats[i]);
    }

    fprintf(fileName, "\n");
    fclose(fileName);
}

void ShaderStats::sumShaderStat( SHADER_STATS_ITEMS compileInterval, int count )
{
    IGC_ASSERT(0 <= compileInterval);
    IGC_ASSERT(compileInterval < STATS_MAX_SHADER_STATS_ITEMS);
    m_CompileShaderStats[ compileInterval ] += count;
};

void ShaderStats::miscSumShaderStat(ShaderStats* sStats)
{
    ++m_totalShaderCount;
    if (sStats->getShaderStats(STATS_ISA_INST_COUNT) > 0)
    {
        ++m_TotalSimd8;
    }
    if (sStats->getShaderStats(STATS_ISA_INST_COUNT_SIMD16) > 0)
    {
        ++m_TotalSimd16;
    }
    if (sStats->getShaderStats(STATS_ISA_INST_COUNT_SIMD32) > 0)
    {
        ++m_TotalSimd32;
    }
}

#endif // GET_SHADER_STATS

const char* g_cCompTimeIntervals[MAX_COMPILE_TIME_INTERVALS+1] =
{
#define DEFINE_TIME_STAT( enumName, stringName, parentEnum, isVISA, isUnacc, isCoarseTimer, isDashBoardTimer ) stringName,
#include "timeStats.h"
#undef DEFINE_TIME_STAT
};

std::string str(COMPILE_TIME_INTERVALS cti)
{
    switch (cti)
    {
#define DEFINE_TIME_STAT( enumName, stringName, parentEnum, isVISA, isUnacc, isCoarseTimer, isDashBoardTimer ) case enumName: return #enumName;
#include "timeStats.h"
#undef DEFINE_TIME_STAT
    default: IGC_ASSERT_MESSAGE(0, "unreachable"); break;
    }

    return "";
}

COMPILE_TIME_INTERVALS interval( std::string const& str )
{
#define DEFINE_TIME_STAT( enumName, stringName, parentEnum, isVISA, isUnacc, isCoarseTimer, isDashBoardTimer ) \
    if ( str == stringName ) \
    { \
        return enumName; \
    }
#include "timeStats.h"
#undef DEFINE_TIME_STAT
    //llvm::errs() << str;
    IGC_ASSERT_MESSAGE(0, "unreachable, unknown COMPILE_TIME_INTERVALS name");
    return MAX_COMPILE_TIME_INTERVALS;
}

bool isVISATimer( COMPILE_TIME_INTERVALS cti )
{
    switch (cti)
    {
#define DEFINE_TIME_STAT( enumName, stringName, parentEnum, isVISA, isUnacc, isCoarseTimer, isDashBoardTimer ) case enumName: return isVISA;
#include "timeStats.h"
#undef DEFINE_TIME_STAT
    default: IGC_ASSERT_MESSAGE(0, "unreachable"); break;
    }
    return false;
}

bool isUnaccounted( COMPILE_TIME_INTERVALS cti )
{
    switch (cti)
    {
#define DEFINE_TIME_STAT( enumName, stringName, parentEnum, isVISA, isUnacc, isCoarseTimer, isDashBoardTimer ) case enumName: return isUnacc;
#include "timeStats.h"
#undef DEFINE_TIME_STAT
    default: IGC_ASSERT_MESSAGE(0, "unreachable"); break;
    }
    return false;
}

bool isCoarseTimer( COMPILE_TIME_INTERVALS cti )
{
    switch (cti)
    {
#define DEFINE_TIME_STAT( enumName, stringName, parentEnum, isVISA, isUnacc, isCoarseTimer, isDashBoardTimer ) case enumName: return isCoarseTimer;
#include "timeStats.h"
#undef DEFINE_TIME_STAT
    default: IGC_ASSERT_MESSAGE(0, "unreachable"); break;
    }
    return true;
}

bool isDashboardTimer( COMPILE_TIME_INTERVALS cti )
{
    switch (cti)
    {
#define DEFINE_TIME_STAT( enumName, stringName, parentEnum, isVISA, isUnacc, isCoarseTimer, isDashBoardTimer ) case enumName: return isDashBoardTimer;
#include "timeStats.h"
#undef DEFINE_TIME_STAT
    default: IGC_ASSERT_MESSAGE(0, "unreachable"); break;
    }

    return true;
}

COMPILE_TIME_INTERVALS parentInterval( COMPILE_TIME_INTERVALS cti )
{
    switch (cti)
    {
#define DEFINE_TIME_STAT( enumName, stringName, parentEnum, isVISA, isUnacc, isCoarseTimer, isDashBoardTimer ) case enumName: return parentEnum;
#include "timeStats.h"
#undef DEFINE_TIME_STAT
    default: IGC_ASSERT_MESSAGE(0, "unreachable"); break;
    }
    return MAX_COMPILE_TIME_INTERVALS;
}

int parentIntervalDepth( COMPILE_TIME_INTERVALS cti )
{
    if ( cti == TIME_TOTAL )
    {
        return 0;
    }
    else
    {
        return 1 + parentIntervalDepth( parentInterval( cti ) );
    }
}

#if GET_TIME_STATS

TimeStats::TimeStats()
    : m_isPostProcessed(false)
    , m_totalShaderCount(0)
    , m_PassTotalTicks (0)
{
    std::fill(std::begin(m_wallclockStart), std::end(m_wallclockStart), 0);
    std::fill(std::begin(m_elapsedTime),    std::end(m_elapsedTime),    0);
    std::fill(std::begin(m_hitCount),       std::end(m_hitCount),       0);
    m_freq = iSTD::GetTimestampFrequency();

    m_PassTimeStatsMap.clear();
}

TimeStats::~TimeStats()
{
    m_PassTimeStatsMap.clear();
}

void TimeStats::recordVISATimers()
{
    // getTotalTimers() +1 because there is a unaccounted counter
    for (unsigned int i = 0; i < getTotalTimers(); ++i)
    {
        m_elapsedTime[TIME_VISA_TOTAL+i] += getTimerTicks(i);
        m_hitCount[TIME_VISA_TOTAL + i] = getTimerHits(i);
    }
}

void TimeStats::recordTimerStart( COMPILE_TIME_INTERVALS compileInterval )
{
    IGC_ASSERT(0 <= compileInterval);
    IGC_ASSERT(compileInterval < MAX_COMPILE_TIME_INTERVALS);
    m_wallclockStart[ compileInterval ] = iSTD::GetTimestampCounter();
}

void TimeStats::recordTimerEnd( COMPILE_TIME_INTERVALS compileInterval )
{
    IGC_ASSERT(0 <= compileInterval);
    IGC_ASSERT(compileInterval < MAX_COMPILE_TIME_INTERVALS);
    m_elapsedTime[ compileInterval ] += iSTD::GetTimestampCounter() - m_wallclockStart[ compileInterval ];
    m_hitCount[ compileInterval ]++;
}

uint64_t TimeStats::getCompileTime( COMPILE_TIME_INTERVALS compileInterval ) const
{
    IGC_ASSERT(0 <= compileInterval);
    IGC_ASSERT(compileInterval < MAX_COMPILE_TIME_INTERVALS);
    return m_elapsedTime[ compileInterval ];
}

uint64_t TimeStats::getCompileHit( COMPILE_TIME_INTERVALS compileInterval ) const
{
    IGC_ASSERT(0 <= compileInterval);
    IGC_ASSERT(compileInterval < MAX_COMPILE_TIME_INTERVALS);
    return m_hitCount[ compileInterval ];
}

void TimeStats::sumWith( const TimeStats* pOther )
{
    // Add pOther's compile time's to us
    for (int i=0;i<MAX_COMPILE_TIME_INTERVALS;i++)
    {
        m_elapsedTime[ i ] += pOther->m_elapsedTime[ i ];
        m_hitCount[ i ]    += pOther->m_hitCount[ i ];
    }

    m_totalShaderCount++;

    m_PassTotalTicks += pOther->m_PassTotalTicks;

    if (IGC_REGKEY_OR_FLAG_ENABLED(DumpTimeStatsPerPass, TIME_STATS_PER_PASS))
    {
        if (m_PassTimeStatsMap.empty())
        {
            m_PassTimeStatsMap.insert(pOther->m_PassTimeStatsMap.begin(), pOther->m_PassTimeStatsMap.end());
        }
        else
        {
            std::map<std::string, PerPassTimeStat>::const_iterator fromIter;
            std::map<std::string, PerPassTimeStat>::iterator toIter;

            for (fromIter = pOther->m_PassTimeStatsMap.begin(); fromIter != pOther->m_PassTimeStatsMap.end(); fromIter++)
            {
                toIter = m_PassTimeStatsMap.find(fromIter->first);
                if (toIter != m_PassTimeStatsMap.end())
                {
                    // If the pass is already included in the combined list, add the numbers
                    toIter->second.PassHitCount += fromIter->second.PassHitCount;
                    toIter->second.PassElapsedTime += fromIter->second.PassElapsedTime;
                }
                else
                {
                    // Add new pass from this run to the combined list
                    PerPassTimeStat stat;
                    stat.PassElapsedTime = fromIter->second.PassElapsedTime;
                    stat.PassHitCount = fromIter->second.PassHitCount;
                    m_PassTimeStatsMap.insert(std::pair<std::string, PerPassTimeStat>(fromIter->first, stat));
                }
            }
        }
    }
}

void TimeStats::printTime( ShaderType type, ShaderHash hash) const
{
    printTime(type, hash, nullptr, 0);
}

void TimeStats::printTime(ShaderType type, ShaderHash hash, void* context) const
{
    printTime(type, hash, context , 0);
}

void TimeStats::printTime(ShaderType type, ShaderHash hash, UINT64 psoDDIHash) const
{
    printTime(type, hash, nullptr, psoDDIHash);
}

void TimeStats::printTime(ShaderType type, ShaderHash hash, void* context, UINT64 psoDDIHash) const
{
    TimeStats pp = postProcess();

    std::string shaderName = IGC::Debug::DumpName(IGC::Debug::GetShaderOutputName()).Type(type).Hash(hash).StagedInfo(context).str().c_str();
    if (shaderName.find_last_of("\\") != std::string::npos)
    {
        shaderName = shaderName.substr(shaderName.find_last_of("\\") + 1, shaderName.size());
    }

    pp.printTimeCSV( shaderName, psoDDIHash);

    // Skip printing PerPass info to CSV for now
    //pp.printPerPassTimeCSV( shaderName );
    // Avoid printing the timestats for each shader to screen
    // pp.printSumTimeTable(llvm::dbgs());
}

void TimeStats::printSumTime() const
{
    // If using regkey to turn on timestats, CorpusName is not initialized properly
    if (strnlen_s(IGC::Debug::GetShaderCorpusName(), 1) == 0)
    {
        std::stringstream corpusName;
        corpusName << m_totalShaderCount << " shaders";
        IGC::Debug::SetShaderCorpusName(corpusName.str().c_str());
    }

    TimeStats pp = postProcess();

    bool dumpCoarse = IGC_REGKEY_OR_FLAG_ENABLED(DumpTimeStatsCoarse, TIME_STATS_COARSE);

    if ( dumpCoarse )
    {
        pp.printSumTimeCSV("c:\\Intel\\TimeStatCoarseSum.csv");
    }
    else
    {
        pp.printSumTimeCSV("c:\\Intel\\TimeStatSum.csv");
    }

    if (IGC_REGKEY_OR_FLAG_ENABLED(DumpTimeStatsPerPass, TIME_STATS_PER_PASS))
    {
        pp.printPerPassSumTime(llvm::dbgs());
        pp.printPerPassSumTimeCSV("c:\\Intel\\TimeStatPerPassSum.csv");
    }

    pp.printSumTimeTable(llvm::dbgs());
}

bool TimeStats::skipTimer( int i ) const
{
    const COMPILE_TIME_INTERVALS interval = static_cast<COMPILE_TIME_INTERVALS>(i);
    if( IGC_REGKEY_OR_FLAG_ENABLED(DumpTimeStatsCoarse, TIME_STATS_COARSE ) && !isCoarseTimer( interval ) )
    {
        return true;
    }
    if( !isDashboardTimer( interval ) )
    {
        return true;
    }
    return false;
}
void TimeStats::printSumTimeCSV(const char* outputFile) const
{
    IGC_ASSERT_MESSAGE(m_isPostProcessed, "Print functions should only be called on a Post-Processed TimeStats object");

    bool fileExist = false;

    FILE* fp = fopen(outputFile, "r");
    if( fp )
    {
        fileExist = true;
        fclose(fp);
    }

    FILE* fileName = fopen(outputFile, "a");

    if( !fileExist && fileName )
    {
        fprintf(fileName, "Frequency,%ju\n\n", m_freq);
        fprintf(fileName, "corpus name,shader count,");
        for (int i=0;i<MAX_COMPILE_TIME_INTERVALS;i++)
        {
            if( !skipTimer( i ) )
            {
                fprintf(fileName, "%s,", g_cCompTimeIntervals[i] );
            }
        }
        fprintf(fileName, "\n");
    }

    if( fileName )
    {
        fprintf(fileName, "%s,%d,", IGC::Debug::GetShaderCorpusName(), m_totalShaderCount );

        // print ticks
        for (int i=0;i<MAX_COMPILE_TIME_INTERVALS;i++)
        {
            if( !skipTimer( i ) )
            {
                fprintf(fileName, "%jd,", getCompileTime(static_cast<COMPILE_TIME_INTERVALS>(i)) );
            }
        }
        fprintf(fileName, "\n");

        if( !IGC_REGKEY_OR_FLAG_ENABLED(DumpTimeStatsCoarse, TIME_STATS_COARSE))
        {
            // print secs
            fprintf(fileName, "seconds,," );
            for (int i=0;i<MAX_COMPILE_TIME_INTERVALS;i++)
            {
                fprintf(fileName, "%f,", (double)getCompileTime(static_cast<COMPILE_TIME_INTERVALS>(i))/(double)m_freq);
            }
            fprintf(fileName, "\n");

            // print percentage
            fprintf(fileName, "percentage,," );
            for (int i=0;i<MAX_COMPILE_TIME_INTERVALS;i++)
            {
                fprintf(fileName, "%f,", (double)getCompileTime(static_cast<COMPILE_TIME_INTERVALS>(i))/(double)getCompileTime(TIME_TOTAL) * 100. );
            }
            fprintf(fileName, "\n");

            // print hit count
            fprintf(fileName, "hit,," );
            for (int i=0;i<MAX_COMPILE_TIME_INTERVALS;i++)
            {
                fprintf(fileName, "%ju,", m_hitCount[i] );
            }
            fprintf(fileName, "\n");
        }

        fclose(fileName);
    }
}

void TimeStats::printPerPassSumTimeCSV(const char* outputFile) const
{
    IGC_ASSERT_MESSAGE(m_isPostProcessed, "Print functions should only be called on a Post-Processed TimeStats object");

    if (m_PassTimeStatsMap.empty())
    {
        return;
    }

    bool fileExist = false;

    FILE* fp = fopen(outputFile, "r");
    if (fp)
    {
        fileExist = true;
        fclose(fp);
    }

    FILE* fileName = fopen(outputFile, "a");
    std::map<std::string, PerPassTimeStat>::const_iterator iter;

    if (!fileExist && fileName)
    {
        fprintf(fileName, "Frequency,%ju\n\n", m_freq);
        fprintf(fileName, "corpus name,passes count,Total,");

        for (iter = m_PassTimeStatsMap.begin(); iter != m_PassTimeStatsMap.end(); iter++)
        {
            fprintf(fileName, "%s,", iter->first.c_str());
        }
        fprintf(fileName, "\n");
    }

    if (fileName)
    {
        fprintf(fileName, "%s,%d,%ju,", IGC::Debug::GetShaderCorpusName(), (int)m_PassTimeStatsMap.size(), m_PassTotalTicks);

        for (iter = m_PassTimeStatsMap.begin(); iter != m_PassTimeStatsMap.end(); iter++)
        {
            fprintf(fileName, "%jd,", iter->second.PassElapsedTime);
        }

        fprintf(fileName, "\n");
        fclose(fileName);
    }
}

void TimeStats::recordPerPassTimerStart(std::string PassName)
{
    IGC_ASSERT(!PassName.empty());

    std::map<std::string, PerPassTimeStat>::iterator iter = m_PassTimeStatsMap.find(PassName);
    if (iter == m_PassTimeStatsMap.end())
    {
        PerPassTimeStat stat;
        stat.PassElapsedTime = 0;
        stat.PassHitCount = 0;
        stat.PassClockStart = iSTD::GetTimestampCounter();

        m_PassTimeStatsMap.insert(std::pair<std::string, PerPassTimeStat>(PassName, stat));
    }
    else
    {
        iter->second.PassClockStart = iSTD::GetTimestampCounter();
    }
}

void TimeStats::recordPerPassTimerEnd(std::string PassName)
{
    IGC_ASSERT(!PassName.empty());

    std::map<std::string, PerPassTimeStat>::iterator iter = m_PassTimeStatsMap.find(PassName);

    if (iter == m_PassTimeStatsMap.end())
    {
        std::cerr << "Invalid Pass " << PassName << std::endl;
    }
    else
    {
        uint64_t start = iter->second.PassClockStart;
        uint64_t elapsed = iSTD::GetTimestampCounter() - start;

        iter->second.PassHitCount += 1;
        iter->second.PassElapsedTime += elapsed;
        m_PassTotalTicks += elapsed;
    }
}

namespace {
    std::string str( double num, unsigned width, unsigned sigFigs )
    {
        char numStr[32];
#if defined( WIN32 ) || defined( _WIN64 )
        sprintf_s(numStr,                "%*.*f", width, sigFigs, num);
#else
        snprintf(numStr, sizeof(numStr), "%*.*f", width, sigFigs, num);
#endif
        return numStr;
    }

    std::string str( uint64_t num, unsigned width )
    {
        char numStr[32];
#if defined( WIN32 ) || defined( _WIN64 )
        sprintf_s(numStr,                "%*llu", width, num);
#else
        snprintf(numStr, sizeof(numStr), "%*llu", width, (long long unsigned int)num);
#endif
        return numStr;
    }
} // anonymous namespace

void TimeStats::printSumTimeTable( llvm::raw_ostream & OS ) const
{
    IGC_ASSERT_MESSAGE(m_isPostProcessed, "Print functions should only be called on a Post-Processed TimeStats object");

    llvm::formatted_raw_ostream FS(OS);

    FS << "\n";
    FS << "ShaderCount:  "  << m_totalShaderCount << " shaders\n";
    FS << "CorpusName:   \"" << IGC::Debug::GetShaderCorpusName() << "\"\n";
    FS << "Frequency:    "  << m_freq << " ticks/sec\n";

    const unsigned colWidth =  8;                        //<! Width of each of the data columns
    const unsigned startCol =  4;                        //<! Spacing to the left of the whole table
    const unsigned ticksCol = 50;                        //<! Location of the first character of the ticks column
    const unsigned secsCol  = ticksCol + colWidth + 2;   //<! Location of the first character of the seconds column
    const unsigned percCol  =  secsCol + colWidth + 2;   //<! Location of the first character of the percent column
    const unsigned hitCol   =  percCol + colWidth + 2;   //<! Location of the first character of the hit column

    // table header
    FS.PadToColumn(ticksCol) << "ticks";
    FS.PadToColumn( secsCol) << "seconds";
    FS.PadToColumn( percCol) << "percent";
    FS.PadToColumn(  hitCol) << "hits";
    FS << "\n";
    const std::string bar(colWidth+1,'-');
    FS.PadToColumn(ticksCol) << bar;
    FS.PadToColumn( secsCol) << bar;
    FS.PadToColumn( percCol) << bar;
    FS.PadToColumn(  hitCol) << bar;
    FS << "\n";

    // table body
    if (IGC_REGKEY_OR_FLAG_ENABLED(DumpTimeStatsCoarse, TIME_STATS_COARSE))
    {
        uint64_t timeNotInCoarse = getCompileTime(TIME_TOTAL);
        for (int i = 0; i < MAX_COMPILE_TIME_INTERVALS; i++)
        {
            const COMPILE_TIME_INTERVALS interval = static_cast<COMPILE_TIME_INTERVALS>(i);
            if (!skipTimer(i))
            {
                const uint64_t intervalTicks = getCompileTime(interval);
                if (intervalTicks)
                {
                    if (interval != TIME_TOTAL)
                    {
                        timeNotInCoarse -= intervalTicks;
                    }
                    FS.PadToColumn(startCol) << g_cCompTimeIntervals[interval];
                    FS.PadToColumn(ticksCol) << str(intervalTicks, colWidth);
                    FS.PadToColumn(secsCol) << str(intervalTicks / (double)m_freq, colWidth, 4);
                    FS.PadToColumn(percCol) << str(intervalTicks / (double)getCompileTime(TIME_TOTAL) * 100.0, colWidth, 2);
                    FS.PadToColumn(percCol) << str(m_hitCount[i], colWidth);
                    FS << "\n";
                }
            }
        }
        // print the "others" for coarse
        FS.PadToColumn(startCol) << "Others";
        FS.PadToColumn(ticksCol) << str(timeNotInCoarse, colWidth);
        FS.PadToColumn(secsCol) << str(timeNotInCoarse / (double)m_freq, colWidth, 4);
        FS.PadToColumn(percCol) << str(timeNotInCoarse / (double)getCompileTime(TIME_TOTAL) * 100.0, colWidth, 2);
        FS.PadToColumn(percCol) << str(0, colWidth);
        FS << "\n";
    }
    else
    {
        for (int i = 0; i < MAX_COMPILE_TIME_INTERVALS; i++)
        {
            const COMPILE_TIME_INTERVALS interval = static_cast<COMPILE_TIME_INTERVALS>(i);
            if (!skipTimer(i))
            {
                const uint64_t intervalTicks = getCompileTime(interval);
                if (intervalTicks)
                {
                    FS.PadToColumn(startCol).indent(2 * parentIntervalDepth(interval))
                        << g_cCompTimeIntervals[interval];
                    FS.PadToColumn(ticksCol) << str(intervalTicks, colWidth);
                    FS.PadToColumn(secsCol) << str(intervalTicks / (double)m_freq, colWidth, 4);
                    FS.PadToColumn(percCol) << str(intervalTicks / (double)getCompileTime(TIME_TOTAL) * 100.0, colWidth, 2);
                    FS.PadToColumn(percCol) << str(m_hitCount[i], colWidth);
                    FS << "\n";
                }
            }
        }
    }
    FS << "\n";

    FS.flush();
    OS.flush();
}

void TimeStats::printPerPassSumTime(llvm::raw_ostream& OS) const
{
    if (m_PassTimeStatsMap.empty())
    {
        return;
    }

    llvm::formatted_raw_ostream FS(OS);

    FS << "\n";
    FS << "PassesCount:  " << m_PassTimeStatsMap.size() << " IGC/LLVM passes\n";
    FS << "Total Ticks:  " << m_PassTotalTicks << " ticks\n";

    const unsigned colWidth = 8;                      //<! Width of each of the data columns
    const unsigned startCol = 6;                      //<! Spacing to the left of the whole table
    const unsigned ticksCol = 50;                     //<! Location of the first character of the ticks column
    const unsigned percCol = ticksCol + colWidth + 2; //<! Location of the first character of the percent column
    const unsigned hitCol = percCol + colWidth + 2;   //<! Location of the first character of the hit column

    // table header
    FS.PadToColumn(ticksCol) << "ticks";
    FS.PadToColumn(percCol)  << "percent";
    FS.PadToColumn(hitCol)   << "hits";
    FS << "\n";
    const std::string bar(colWidth + 1, '-');
    FS.PadToColumn(ticksCol) << bar;
    FS.PadToColumn(percCol) << bar;
    FS.PadToColumn(hitCol) << bar;
    FS << "\n";

    PerPassTimeStat stat;
    uint64_t ticks = 0;
    std::map<std::string, PerPassTimeStat>::const_iterator iter;

    for (iter = m_PassTimeStatsMap.begin(); iter != m_PassTimeStatsMap.end(); iter++)
    {
        stat = iter->second;
        ticks = stat.PassElapsedTime;

        // pass ticks % hit
        FS.PadToColumn(startCol) << iter->first.substr(0, ticksCol - startCol - 1);
        FS.PadToColumn(ticksCol) << str(ticks, colWidth);
        FS.PadToColumn(percCol) << str(ticks / (double)m_PassTotalTicks * 100.0, colWidth, 2);
        FS.PadToColumn(percCol) << str(stat.PassHitCount, colWidth);
        FS << "\n";
    }

    FS << "\n";
    FS.flush();
    OS.flush();
}

void TimeStats::printTimeCSV( std::string const& corpusName, UINT64 psoDDIHash ) const
{
    IGC_ASSERT_MESSAGE(m_isPostProcessed, "Print functions should only be called on a Post-Processed TimeStats object");

    std::string subFile = "TimeStat_";
    if (strnlen_s(IGC::Debug::GetShaderCorpusName(), 1) == 0)
        subFile += "Shaders";
    else
        subFile += IGC::Debug::GetShaderCorpusName();
    const std::string outputFilePath =
#if defined(__linux__)
    subFile + ".csv";
#else
    std::string("c:\\Intel\\") + subFile + ".csv";
#endif
    const char *outputFile = outputFilePath.c_str();

    bool fileExist = false;

    FILE* fp = fopen(outputFile, "r");
    if( fp )
    {
        fileExist = true;
        fclose(fp);
    }

    FILE* fileName = fopen(outputFile, "a");

    if( !fileExist && fileName)
    {
        fprintf(fileName, "Frequency:%ju,", m_freq);

        if (IGC_IS_FLAG_ENABLED(PrintPsoDdiHash))
            fprintf(fileName, "psoDDIHash,");

        for (int i=0;i<MAX_COMPILE_TIME_INTERVALS;i++)
        {
            if( !skipTimer(i) )
            {
                fprintf(fileName, "%s,", g_cCompTimeIntervals[i] );
            }
        }
        fprintf(fileName, "\n");
    }

    if (fileName)
    {
        fprintf(fileName, "%s.isa,", corpusName.c_str());

        if (IGC_IS_FLAG_ENABLED(PrintPsoDdiHash))
            fprintf(fileName, "%#jx,", psoDDIHash);

        for (int i = 0; i < MAX_COMPILE_TIME_INTERVALS; i++)
        {
            if (!skipTimer(i))
            {
                const COMPILE_TIME_INTERVALS interval = static_cast<COMPILE_TIME_INTERVALS>(i);
                fprintf(fileName, "%jd,", getCompileTime(interval));
            }
        }

        fprintf(fileName, "\n");
        fclose(fileName);
    }

}

void TimeStats::printPerPassTimeCSV(std::string const& corpusName) const
{
    IGC_ASSERT_MESSAGE(m_isPostProcessed, "Print functions should only be called on a Post-Processed TimeStats object");

    if (m_PassTimeStatsMap.empty())
    {
        return;
    }

    std::string subFile = "TimeStatPerPass_";
    if (strnlen_s(IGC::Debug::GetShaderCorpusName(), 1) == 0)
        subFile += "Shaders";
    else
        subFile += IGC::Debug::GetShaderCorpusName();
    const std::string outputFilePath = std::string("c:\\Intel\\") + subFile + ".csv";
    const char* outputFile = outputFilePath.c_str();
    bool fileExist = false;

    FILE* fp = fopen(outputFile, "r");
    if (fp)
    {
        fileExist = true;
        fclose(fp);
    }

    FILE* fileName = fopen(outputFile, "a");

    if (!fileExist && fileName)
    {
        fprintf(fileName, "Frequency:%ju,", m_freq);

        std::map<std::string, PerPassTimeStat>::const_iterator iter;
        fprintf(fileName, "Passes Count,Total,");
        for (iter = m_PassTimeStatsMap.begin(); iter != m_PassTimeStatsMap.end(); iter++)
        {
            fprintf(fileName, "%s,", iter->first.c_str());
        }
        fprintf(fileName, "\n");
    }

    if (fileName)
    {
        fprintf(fileName, "%s.isa,%d,%ju,", corpusName.c_str(), (int)m_PassTimeStatsMap.size(), m_PassTotalTicks);
        std::map<std::string, PerPassTimeStat>::const_iterator iter;

        for (iter = m_PassTimeStatsMap.begin(); iter != m_PassTimeStatsMap.end(); iter++)
        {
            fprintf(fileName, "%jd,", iter->second.PassElapsedTime);
        }

        fprintf(fileName, "\n");
        fclose(fileName);
    }
}

TimeStats TimeStats::postProcess() const
{
    TimeStats copy(*this);

    uint64_t childSum[MAX_COMPILE_TIME_INTERVALS+1];
    std::fill( std::begin(childSum), std::end(childSum), 0 );

    for (int i=0; i <MAX_COMPILE_TIME_INTERVALS; ++i)
    {
        const COMPILE_TIME_INTERVALS interval = static_cast<COMPILE_TIME_INTERVALS>(i);
        const COMPILE_TIME_INTERVALS parent = parentInterval( interval );

        if (m_elapsedTime[interval] == 0) {
            continue;
        }

        if ( isUnaccounted(interval) == false )
        {
            childSum[ parent ] += m_elapsedTime[ interval ];
        }
    }

    for (int i=0; i <MAX_COMPILE_TIME_INTERVALS; ++i)
    {
        const COMPILE_TIME_INTERVALS interval = static_cast<COMPILE_TIME_INTERVALS>(i);
        const COMPILE_TIME_INTERVALS parent = parentInterval( interval );

        if ( isUnaccounted(interval) == true )
        {
            copy.m_elapsedTime[ interval ] = m_elapsedTime[ parent ] - childSum[ parent ];
        }
    }

    copy.m_isPostProcessed = true;

    return copy;
}

#endif // GET_TIME_STATS

#if GET_MEM_STATS

void CMemoryReport::CreateMemStatsFiles()
{
    if( IGC::Debug::GetDebugFlag(IGC::Debug::DebugFlag::MEM_STATS ) )
    {
        sprintf_s(g_MemoryReport.m_CsvNameUsageSum, sizeof(m_CsvNameUsageSum),
            "c:\\Intel\\MemoryStatsSum.csv" );

        sprintf_s(g_MemoryReport.m_CsvNameUsage, sizeof(m_CsvNameUsage),
            "c:\\Intel\\%sMemoryStatsUsage.csv",
            IGC::Debug::GetShaderCorpusName() );

        sprintf_s(g_MemoryReport.m_CsvNameAllocs, sizeof(m_CsvNameAllocs),
            "c:\\Intel\\%sMemoryStatsAllocs.csv",
            IGC::Debug::GetShaderCorpusName() );

        sprintf_s(g_MemoryReport.m_CsvNameAllocsSubset, sizeof(m_CsvNameAllocsSubset),
            "c:\\Intel\\%sMemoryStatsAllocsSubset.csv",
            IGC::Debug::GetShaderCorpusName() );

        FILE* outputFileUsage           = (FILE*)iSTD::FileOpen( (const char*)g_MemoryReport.m_CsvNameUsage, "w" );
        FILE* outputFileAllocs          = (FILE*)iSTD::FileOpen( (const char*)g_MemoryReport.m_CsvNameAllocs, "w" );
        FILE* outputFileAllocsSubset    = (FILE*)iSTD::FileOpen( (const char*)g_MemoryReport.m_CsvNameAllocsSubset, "w" );
        // Write header
        iSTD::FileWrite( outputFileUsage, "Name,Global mem. peak" );
        iSTD::FileWrite( outputFileAllocs, "Name,Global num alloc." );
        iSTD::FileWrite( outputFileAllocsSubset, "Name,Type of Subset" );
        for( int i = 0; i < IGC::MAX_SHADER_MEMORY_SNAPSHOT; i++ )
        {
            if( g_MemoryReport.m_GrabDetailed || IGC::g_cShaderMemorySnapshot[ i ].IsMilestone )
            {
                iSTD::FileWrite( outputFileUsage, ",%s peak,%s end", IGC::g_cShaderMemorySnapshot[ i ].Name, IGC::g_cShaderMemorySnapshot[ i ].Name );
                iSTD::FileWrite( outputFileAllocs, ",%s allocs,%s curr. allocs", IGC::g_cShaderMemorySnapshot[ i ].Name, IGC::g_cShaderMemorySnapshot[ i ].Name );
                iSTD::FileWrite( outputFileAllocsSubset, ",%s allocs", IGC::g_cShaderMemorySnapshot[ i ].Name, IGC::g_cShaderMemorySnapshot[ i ].Name );
            }
        }
        iSTD::FileWrite( outputFileUsage, "\n" );
        iSTD::FileWrite( outputFileAllocs, "\n" );
        iSTD::FileWrite( outputFileAllocsSubset, "\n" );

        iSTD::FileClose( outputFileUsage );
        iSTD::FileClose( outputFileAllocs );
        iSTD::FileClose( outputFileAllocsSubset );
    }
}

/*****************************************************************************\

Function: CMemoryReport::DumpMemoryStats

Description:
    Saves memory statistics to already created file.

Input:
    None

Output:
    None

\*****************************************************************************/
void CMemoryReport::DumpMemoryStats( ShaderType type, ShaderHash hash )
{
    if( IGC::Debug::GetDebugFlag(IGC::Debug::DebugFlag::MEM_STATS ) )
    {
        m_type = type;
        CopyToSummary();

        FILE* csvFileGlobal = (FILE*)iSTD::FileOpen( (const char*) g_MemoryReport.m_CsvNameUsage, "a" );
        FILE* csvFileAllocs = (FILE*)iSTD::FileOpen( (const char*) g_MemoryReport.m_CsvNameAllocs, "a" );
        FILE* csvFileAllocsSubset = (FILE*)iSTD::FileOpen( (const char*) g_MemoryReport.m_CsvNameAllocsSubset, "a" );

        std::string shaderName = IGC::Debug::DumpName(IGC::Debug::GetShaderOutputName()).Type(type).Hash(hash).str().c_str();
        if (shaderName.find_last_of("\\") != std::string::npos)
        {
            shaderName = shaderName.substr(shaderName.find_last_of("\\") + 1, shaderName.size());
        }

        sprintf_s(m_DumpMemoryStatsFileName, sizeof(m_DumpMemoryStatsFileName),
            "%s", shaderName.c_str());

        iSTD::FileWrite(  csvFileGlobal, "%s,%u", m_DumpMemoryStatsFileName, g_MemoryReport.m_Stat.HeapUsedPeak/1024 );
        iSTD::FileWrite(  csvFileAllocs, "%s,%u", m_DumpMemoryStatsFileName, g_MemoryReport.m_Stat.NumAllocations );

        for( int i = 0; i < IGC::MAX_SHADER_MEMORY_SNAPSHOT; i++ )
        {
            if( g_MemoryReport.m_GrabDetailed || IGC::g_cShaderMemorySnapshot[ i ].IsMilestone )
            {
                iSTD::FileWrite( csvFileGlobal, ",%d,%d", g_MemoryReport.m_Snapshots[ i ].SnapHeapUsedAbsolutePeak/1024,
                    g_MemoryReport.m_Snapshots[ i ].HeapUsed/1024 );
                iSTD::FileWrite( csvFileAllocs, ",%d,%d", g_MemoryReport.m_Snapshots[ i ].NumSnapAllocations,
                    g_MemoryReport.m_Snapshots[ i ].NumCurrSnapAllocationsPeak );
            }
        }
        iSTD::FileWrite( csvFileGlobal, "\n" );
        iSTD::FileWrite( csvFileAllocs, "\n" );

        for ( int i = 0; i < IGC::SMAT_NUM_OF_TYPES; i++ )
        {
            iSTD::FileWrite( csvFileAllocsSubset, "%s,%s", m_DumpMemoryStatsFileName,
                IGC::g_cShaderMemoryAllocsType[ i ].Name );
            for( int j = 0; j < IGC::MAX_SHADER_MEMORY_SNAPSHOT; j++ )
            {
                if( g_MemoryReport.m_GrabDetailed || IGC::g_cShaderMemorySnapshot[ j ].IsMilestone )
                {
                    iSTD::FileWrite( csvFileAllocsSubset, ",%d", g_MemoryReport.m_Snapshots[ j ].NumSnapAllocationsType[ i ]);
                }
            }
            iSTD::FileWrite( csvFileAllocsSubset, "\n" );
        }
        iSTD::FileClose( csvFileGlobal );
        iSTD::FileClose( csvFileAllocs );
        iSTD::FileClose( csvFileAllocsSubset );
    }
}

CMemoryReport g_MemoryReport;

/*****************************************************************************\

Function: MemUsageSnapshot

Description: Helper global function for setting usage snapshot

Input: IGC::SHADER_MEMORY_SNAPSHOT phase

Output: None

\*****************************************************************************/
void MemUsageSnapshot( IGC::SHADER_MEMORY_SNAPSHOT phase )
{
    if( IGC::Debug::GetDebugFlag(IGC::Debug::DebugFlag::MEM_STATS ) )
    {
        if( phase == IGC::SMS_COMPILE_START )
        {
            g_MemoryReport.UsageReset();
        }
        g_MemoryReport.UsageSnapshot( phase );
    }
}

/*****************************************************************************\

Function: CMemoryReport::CMemoryReport

Description: CMemoryReport constructor

Input: None

Output: None

\*****************************************************************************/
CMemoryReport::CMemoryReport()
{
    m_GrabDetailed = false;
    m_SnapCnt = 0;
    m_LastSnapHeapUsed = 0;

    for( int sumI = 0; sumI<MAX_MEMORY_SUMMARY_ITEM; sumI++ )
    {
        m_SummaryDump[sumI].clear();
    }
}

/*****************************************************************************\

Function: CMemoryReport::~CMemoryReport

Description: CMemoryReport constructor

Input: None

Output: None

\*****************************************************************************/
CMemoryReport::~CMemoryReport()
{
}

/*****************************************************************************\

Function:
    CMemoryReport::MallocMemInstrumentation

Description:
    Instrumentation for malloc

Input:
    size_t _Size - size of allocated memory

Output:
    None

\*****************************************************************************/
void CMemoryReport::MallocMemInstrumentation( size_t _Size )
{
    ++g_MemoryReport.m_Stat.NumAllocations;
    ++g_MemoryReport.m_Stat.NumSnapAllocations;
    ++g_MemoryReport.m_Stat.NumCurrSnapAllocationsPeak;
    ++g_MemoryReport.m_Stat.NumCurrAllocations;

    for (int i = 0; i < IGC::SMAT_NUM_OF_TYPES; i++)
    {
        if ( _Size <= IGC::g_cShaderMemoryAllocsType[ i ].max_size)
        {
            ++g_MemoryReport.m_Stat.NumSnapAllocationsType[ i ];
            break;
        }
    }

    g_MemoryReport.m_Stat.HeapUsed += reinterpret_cast<int&>(_Size);
    g_MemoryReport.m_Stat.NumCurrAllocationsPeak =
        iSTD::Max<DWORD>( g_MemoryReport.m_Stat.NumCurrAllocationsPeak,
                          g_MemoryReport.m_Stat.NumCurrAllocations );
    g_MemoryReport.m_Stat.NumCurrSnapAllocationsPeak =
        iSTD::Max<DWORD>( g_MemoryReport.m_Stat.NumCurrSnapAllocationsPeak,
                          g_MemoryReport.m_Stat.NumCurrAllocations );
    g_MemoryReport.m_Stat.HeapUsedPeak =
        iSTD::Max<DWORD>( g_MemoryReport.m_Stat.HeapUsedPeak,
                          g_MemoryReport.m_Stat.HeapUsed > 0 ? g_MemoryReport.m_Stat.HeapUsed : 0 );

    g_MemoryReport.m_Stat.SnapHeapUsed += reinterpret_cast<int&>(_Size);
    g_MemoryReport.m_Stat.SnapHeapUsedPeak =
        iSTD::Max<DWORD>( g_MemoryReport.m_Stat.SnapHeapUsedPeak,
                          g_MemoryReport.m_Stat.SnapHeapUsed > 0 ? g_MemoryReport.m_Stat.SnapHeapUsed : 0 );
}

/*****************************************************************************\

Function: CMemoryReport::FreeMemInstrumentation

Description:
    Instrumentation for free instruction

Input:
    size_t size - size of freed memory

Output: None

\*****************************************************************************/
void CMemoryReport::FreeMemInstrumentation( size_t size )
{
    ++g_MemoryReport.m_Stat.NumReleases;
    ++g_MemoryReport.m_Stat.NumSnapReleases;

    g_MemoryReport.m_Stat.HeapUsed -= reinterpret_cast<int&>(size);
    g_MemoryReport.m_Stat.SnapHeapUsed -= reinterpret_cast<int&>(size);

    if( g_MemoryReport.m_Stat.NumCurrAllocations != 0 )
    {
        --g_MemoryReport.m_Stat.NumCurrAllocations;
    }
}

/*****************************************************************************\

Function: CMemoryReport::UsageReset

Description:
    Resets statistics.

Input: None

Output: None

\*****************************************************************************/
void CMemoryReport::UsageReset()
{
    if( IGC::Debug::GetDebugFlag(IGC::Debug::DebugFlag::MEM_STATS ) )
    {
        MemStat cleanStat = {};
        m_Stat = cleanStat;

        memset( m_Snapshots, 0, sizeof( *m_Snapshots ) * IGC::MAX_SHADER_MEMORY_SNAPSHOT );
        m_SnapCnt = 1;   // reserve [0] for 0-based deltas
    }
}

/*****************************************************************************\

Function: CMemoryReport::UsageSnapshot

Description:
    Grab memory stat snapshot and save it under given phase.

Input: IGC::SHADER_MEMORY_SNAPSHOT phase

Output: None

\*****************************************************************************/
void CMemoryReport::UsageSnapshot(
    IGC::SHADER_MEMORY_SNAPSHOT phase )
{
    if( IGC::Debug::GetDebugFlag(IGC::Debug::DebugFlag::MEM_STATS ) )
    {
        if( m_GrabDetailed || IGC::g_cShaderMemorySnapshot[ phase ].IsMilestone )
        {
            m_SnapCnt++;
            if( phase < IGC::MAX_SHADER_MEMORY_SNAPSHOT )
            {
                m_LastSnapHeapUsed = m_LastSnapHeapUsed > 0 ? m_LastSnapHeapUsed : 0;
                // Calculate absolute peak in this snapshot.
                m_Stat.SnapHeapUsedAbsolutePeak = m_LastSnapHeapUsed + m_Stat.SnapHeapUsedPeak;

                m_Snapshots[ phase ] = m_Stat;

                m_LastSnapHeapUsed = m_Stat.HeapUsed;
                m_Stat.SnapHeapUsed = 0;
                m_Stat.SnapHeapUsedPeak = 0;
                m_Stat.NumCurrSnapAllocationsPeak = 0;
                m_Stat.NumSnapAllocations = 0;

                for (int i = 0; i < IGC::SMAT_NUM_OF_TYPES; i++)
                {
                    g_MemoryReport.m_Stat.NumSnapAllocationsType[ i ] = 0;
                }
                m_Stat.NumSnapReleases = 0;
            }
        }
    }
}

/*****************************************************************************\

Function: CMemoryReport::SetDetailed

Description:
    Enables or disables detailed stats aquisition.

Input: bool Enabled

Output: None

\*****************************************************************************/
void CMemoryReport::SetDetailed( bool Enabled )
{
    m_GrabDetailed = Enabled;
}

void CMemoryReport::CopyToSummary()
{
    m_SummaryDump[SMSUM_HeapUsedPeak].push_back( m_Stat.HeapUsedPeak/1024 );
    m_SummaryDump[SMSUM_NumAllocations].push_back( m_Stat.NumAllocations );
    for( int i = 0; i < IGC::MAX_SHADER_MEMORY_SNAPSHOT; i++ )
    {
        m_SummaryDump[ i + SMSUM_SnapHeapUsedAbsolutePeak ].push_back( m_Snapshots[ i ].SnapHeapUsedAbsolutePeak/1024 );
        m_SummaryDump[ i + SMSUM_NumSnapAllocations ].push_back( m_Snapshots[ i ].NumSnapAllocations );
    }
}

const char* CMemoryReport::ShaderTypeText()
{
    return IGC::Debug::GetShaderTypeAcronym(m_type);
}

void CMemoryReport::DumpSummaryStats()
{
    if( IGC::Debug::GetDebugFlag(IGC::Debug::DebugFlag::MEM_STATS ) )
    {

        bool fileExist = false;

        FILE* fileExistFP = fopen( m_CsvNameUsageSum, "r" );
        if( fileExistFP )
        {
            fileExist = true;
            fclose( fileExistFP );
        }

        FILE* csvSummary = fopen( m_CsvNameUsageSum, "a" );
        if( !fileExist )
        {
            // Write header
            fprintf( csvSummary, ",,Global mem. peak" );
            for( int i = 0; i < IGC::MAX_SHADER_MEMORY_SNAPSHOT; i++ )
            {
                if( m_GrabDetailed || IGC::g_cShaderMemorySnapshot[ i ].IsMilestone )
                {
                    fprintf( csvSummary, ",%s peak", IGC::g_cShaderMemorySnapshot[ i ].Name );
                }
            }
            fprintf( csvSummary, ",Shader Type\n" );
        }

        for( int i = 0; i < SMSUM_NumAllocations; i++ )
        {
            m_SummaryDump[ i ].sort();
        }

        fprintf(csvSummary, "%s,max,", IGC::Debug::GetShaderCorpusName());
        for (int i = 0; i < SMSUM_NumAllocations; i++)
        {
            fprintf(csvSummary, "%d,", m_SummaryDump[i].back());
        }
        fprintf(csvSummary, "%s\n", ShaderTypeText());

        fprintf( csvSummary, "%s,max,", IGC::Debug::GetShaderCorpusName() );
        for( int i = 0; i < SMSUM_NumAllocations; i++ )
        {
            fprintf( csvSummary, "%d,", m_SummaryDump[i].back() );
        }
        fprintf( csvSummary, "%s\n",  ShaderTypeText() );

        fprintf( csvSummary, "%s,average,", IGC::Debug::GetShaderCorpusName() );

        int shaderCount = m_SummaryDump[0].size();
        for( int i = 0; i < SMSUM_NumAllocations; i++ )
        {
            iter = m_SummaryDump[i].begin();
            int tempSum = 0;
            // find average
            for( int i=0;i<shaderCount;i++ )
            {
                tempSum += *iter;
                iter++;
            }
            fprintf( csvSummary, "%.02f,", (float)tempSum/shaderCount );

            // find median
            // for( int i=0;i<shaderCount/2;i++ )
            // {
            //     iter++;
            // }
            // fprintf( csvSummary, "%d,", *iter );
        }
        fprintf( csvSummary, "%s\n",  ShaderTypeText() );

        fprintf( csvSummary, "%s,median,", IGC::Debug::GetShaderCorpusName() );

        for( int i = 0; i < SMSUM_NumAllocations; i++ )
        {
            iter = m_SummaryDump[i].begin();
            // find median
            for( int i=0;i<shaderCount/2;i++ )
            {
                iter++;
            }
            fprintf( csvSummary, "%d,", *iter );
        }
        fprintf( csvSummary, "%s\n",  ShaderTypeText() );

        fprintf( csvSummary, "%s,sum,", IGC::Debug::GetShaderCorpusName() );
        for( int i = SMSUM_NumAllocations; i < MAX_MEMORY_SUMMARY_ITEM; i++ )
        {
            unsigned totalAllocs = 0;

            for( iter = m_SummaryDump[i].begin(); iter != m_SummaryDump[i].end(); iter++ )
            {
                totalAllocs += *iter;
            }
            fprintf( csvSummary, "%d,", totalAllocs );
        }
        fprintf( csvSummary, "%s\n",  ShaderTypeText() );

        fclose( csvSummary );
    }
}

#endif //GET_MEM_STATS