File: RegAlloc.cpp

package info (click to toggle)
intel-graphics-compiler2 2.24.13-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 113,504 kB
  • sloc: cpp: 812,849; lisp: 288,219; ansic: 102,423; python: 4,010; yacc: 2,588; lex: 1,666; pascal: 318; sh: 162; makefile: 38
file content (3100 lines) | stat: -rw-r--r-- 110,516 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
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2023 Intel Corporation

SPDX-License-Identifier: MIT

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

#include "RegAlloc.h"
#include "Assertions.h"
#include "DebugInfo.h"
#include "FlowGraph.h"
#include "GraphColor.h"
#include "PointsToAnalysis.h"
#include "Timer.h"
#include "VarSplit.h"

#include <bitset>
#include <climits>
#include <cmath>
#include <fstream>
#include <optional>
#include <vector>

using namespace vISA;

#define GRAPH_COLOR

#if defined (_DEBUG) || defined(_INTERNAL)
bool vISA::RATraceFlag = false;
#endif

bool LivenessAnalysis::isLocalVar(G4_Declare *decl) const {
  if ((decl->isInput() == true &&
       !(fg.builder->getFCPatchInfo()->getFCComposableKernel() &&
         !decl->isLiveIn())) &&
      !(fg.builder->isPreDefArg(decl) &&
        (fg.builder->getIsKernel() ||
         (fg.getIsStackCallFunc() && fg.builder->getArgSize() == 0))))
    return false;

  // FIXME: Why special check? Why can't we compute this correctly?
  if (!fg.builder->canReadR0() && decl == fg.builder->getBuiltinR0())
    return false;

  if (decl->isOutput() == true &&
      !(fg.builder->isPreDefRet(decl) &&
        (fg.builder->getIsKernel() ||
         (fg.getIsStackCallFunc() && fg.builder->getRetVarSize() == 0))))
    return false;

  LocalLiveRange *dclLR = gra.getLocalLR(decl);
  if (dclLR && dclLR->isLiveRangeLocal() &&
      decl->getRegFile() != G4_INPUT) {
    return true;
  }

  // Since variable split is done only for local variables, there is no need to
  // analysis for global variables.
  if (decl->getIsSplittedDcl() || decl->getIsPartialDcl()) {
    return true;
  }

  return false;
}

bool LivenessAnalysis::setVarIDs(bool verifyRA, bool areAllPhyRegAssigned) {
  bool phyRegAssigned = areAllPhyRegAssigned;
  bool hasStackCall = fg.getHasStackCalls() || fg.getIsStackCallFunc();
  bool flag = (selectedRF & G4_GRF) &&
              !fg.builder->getOption(vISA_GlobalSendVarSplit) && !hasStackCall;

  auto handleSplitId = [&](G4_Declare *decl) {
    if (decl->getIsSplittedDcl()) {
      decl->setSplitVarStartID(0);
    }
    if (decl->getIsPartialDcl()) {
      auto declSplitDcl = gra.getSplittedDeclare(decl);
      if (declSplitDcl && declSplitDcl->getIsSplittedDcl()) {
        if (numSplitStartID == 0) {
          numSplitStartID = numVarId;
        }

        if (declSplitDcl->getSplitVarStartID() == 0) {
          declSplitDcl->setSplitVarStartID(numVarId);
        }
        numSplitVar++;
      } else {
        vISA_ASSERT_UNREACHABLE("Found child declare without parent");
      }
    }
  };

  bool incRAVerify = false;
  auto incRACheck = gra.incRA.isEnabled();
  if (incRACheck) {
    // New variables get id assignment from numVarId whereas old
    // variables reuse their ids.
    numVarId = gra.incRA.getNextVarId(selectedRF);
    incRAVerify = gra.incRA.isEnabledWithVerification();
    gra.incRA.unassignedVars.clear();
  }
  for (G4_Declare *decl : gra.kernel.Declares) {
    if (livenessCandidate(decl, verifyRA) && decl->getAliasDeclare() == NULL) {
      // Flag that indicates whether old id was assigned to current decl or
      // a fresh id is assigned in current iteration.
      bool useOldId = false;
      unsigned int varId = numVarId;
      if (incRACheck) {
        // If incremental RA is enabled then:
        // 1. First, check whether dcl had an id assigned from earlier iteration.
        //    If it did, then reuse the id.
        // 2. If dcl wasn't seen in earlier iteration then assign a fresh id to
        //    it beginning from numVarId.
        auto prevIterId = gra.incRA.getIdFromPrevIter(decl);
        if (prevIterId.first) {
          varId = prevIterId.second;
          useOldId = true;
        }
        else
          gra.incRA.recordVarId(decl, varId);
      }
      if (flag) {
        bool isLocal = isLocalVar(decl);
        if (isLocal)
          handleSplitId(decl);
        else
          globalVars.set(varId);
      } else {
        handleSplitId(decl);
        // All variables are treated as global in stack call
        globalVars.set(varId);
      }

      if(incRACheck && !gra.incRA.getLRs().empty()) {
        // Incremental RA requires that variables preserve their
        // RA id. So this sanity check is crucial for incremental
        // RA correctness.
        auto id = decl->getRegVar()->getId();
        vISA_ASSERT(id == varId || id == UNDEFINED_VAL,
                    "different id assigned to G4_RegVar");
        if (gra.incRA.getLRs().size() > id) {
          vISA_ASSERT(gra.incRA.getLRs()[id]->getDcl() == decl,
                      "some other decl found for same id");
        }
      }

      if (!useOldId) {
        // Actual id assignment to G4_Declare::G4_RegVar is done
        // only for new variables. It's assumed that older variables
        // preserve their ids.
        decl->getRegVar()->setId(varId);
      }

      // If new id was assigned then increment numVarId for next fresh variable
      if (!useOldId)
        numVarId++;
      if (!decl->getRegVar()->getPhyReg() && !decl->getIsPartialDcl()) {
        numUnassignedVarId++;

        if (incRAVerify) {
          // Store list of unassigned variables. This list is pruned later in
          // determineColorOrdering() to verify that all unallocated ranges
          // are coloring candidates. Note this is only to aid debugging and
          // verification of incremental RA.
          gra.incRA.unassignedVars.insert(decl);
        }

      }
      if (decl->getRegVar()->isPhyRegAssigned() == false) {
        phyRegAssigned = false;
      }
    } else {
      decl->getRegVar()->setId(UNDEFINED_VAL);
    }
  }

  return phyRegAssigned;
}

LivenessAnalysis::LivenessAnalysis(GlobalRA &g, unsigned char kind,
                                   bool verifyRA, bool forceRun)
    : selectedRF(kind), pointsToAnalysis(g.pointsToAnalysis), gra(g),
      fg(g.kernel.fg) {
  //
  // NOTE:
  // The maydef sets are simply aliases to the mayuse sets, since their uses are
  // mutually exclusive.
  //
  // Go over each reg var if it's a liveness candidate, assign id for bitset.
  //
  bool areAllPhyRegAssigned = !forceRun;

  areAllPhyRegAssigned = setVarIDs(verifyRA, areAllPhyRegAssigned);

  // For Alias Dcl
  for (auto decl : gra.kernel.Declares) {
    if (livenessCandidate(decl, verifyRA) && decl->getAliasDeclare() != NULL) {
      // It is an alias declaration. Set its id = base declaration id
      decl->getRegVar()->setId(decl->getAliasDeclare()->getRegVar()->getId());
    }
    VISA_DEBUG_VERBOSE({
      decl->getRegVar()->emit(std::cout);
      std::cout << " id = " << decl->getRegVar()->getId() << "\n";
    });
  }

  //
  // if no chosen candidate for reg allocation return
  //
  if (numVarId == 0 || (verifyRA == false && areAllPhyRegAssigned == true)) {
    // If all variables have physical register assignments
    // there are no candidates for allocation
    numVarId = 0;
    return;
  }

  //
  // put selected reg vars into vars[]
  //
  vars.resize(numVarId);
  for (auto dcl : gra.kernel.Declares) {
    if (livenessCandidate(dcl, verifyRA) && dcl->getAliasDeclare() == NULL) {
      G4_RegVar *var = dcl->getRegVar();
      vars[var->getId()] = var;
    }
  }

  addr_taken = BitSet(numVarId, false);

  numBBId = (unsigned)fg.size();

  def_in.resize(numBBId);
  def_out.resize(numBBId);
  use_in.resize(numBBId);
  use_out.resize(numBBId);
  use_gen.resize(numBBId);
  use_kill.resize(numBBId);
  indr_use.resize(numBBId);
}

LivenessAnalysis::~LivenessAnalysis() {
  //
  // if no chosen candidate for reg allocation return
  //
  if (numVarId == 0) {
    return;
  }

  // Remove liveness inserted pseudo kills
  for (auto bb : fg) {
    for (auto instIt = bb->begin(); instIt != bb->end();) {
      auto inst = (*instIt);
      if (inst->isPseudoKill()) {
        auto src0 = inst->getSrc(0);
        vISA_ASSERT(src0 && src0->isImm(),
                    "expecting src0 immediate for pseudo kill");
        if (src0->asImm()->getImm() ==
            static_cast<int64_t>(PseudoKillType::FromLiveness)) {
          instIt = bb->erase(instIt);
          continue;
        }
      }
      ++instIt;
    }
  }
}

bool LivenessAnalysis::livenessCandidate(const G4_Declare *decl,
                                         bool verifyRA) const {
  const LocalLiveRange *declLR = nullptr;
  if (verifyRA == false && (declLR = gra.getLocalLR(decl)) &&
      declLR->getAssigned() && !declLR->isEOT()) {
    return false;
  } else if ((selectedRF & decl->getRegFile())) {
    if (selectedRF & G4_GRF) {
      if ((decl->getRegFile() & G4_INPUT) &&
          decl->getRegVar()->isPhyRegAssigned() &&
          !decl->getRegVar()->isGreg()) {
        return false;
      }
      if (decl->getByteSize() == 0) {
        // regrettably, this can happen for arg/retval pre-defined variable
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
}

void LivenessAnalysis::updateKillSetForDcl(
    G4_Declare *dcl, SparseBitVector *curBBGen, SparseBitVector *curBBKill,
    G4_BB *curBB, SparseBitVector *entryBBGen, SparseBitVector *entryBBKill,
    G4_BB *entryBB, unsigned scopeID) {
  if (scopeID != 0 && scopeID != UINT_MAX && dcl->getScopeID() == scopeID) {
    entryBBKill->set(dcl->getRegVar()->getId());
    entryBBGen->reset(dcl->getRegVar()->getId());
    VISA_DEBUG_VERBOSE(std::cout
                       << "Killed sub-routine scope " << dcl->getName()
                       << " at bb with id = " << entryBB->getId() << "\n");
  }
}

// Scoping info is stored per decl. A variable can be either global scope
// (default), sub-routine scope, or basic block scope. This function iterates
// over all instructions and their operands in curBB and if scoping for it is
// set in symbol table then it marks kills accordingly. A bb scope variable is
// killed in the bb it appears and a sub-routine local variable is killed in
// entry block of the sub-routine. No error check is performed currently so if
// variable scoping information is incorrect then generated code will be so too.
void LivenessAnalysis::performScoping(SparseBitVector *curBBGen,
                                      SparseBitVector *curBBKill, G4_BB *curBB,
                                      SparseBitVector *entryBBGen,
                                      SparseBitVector *entryBBKill,
                                      G4_BB *entryBB) {
  unsigned scopeID = curBB->getScopeID();
  for (G4_INST *inst : *curBB) {
    G4_DstRegRegion *dst = inst->getDst();

    if (dst && dst->getBase()->isRegAllocPartaker()) {
      G4_Declare *dcl = GetTopDclFromRegRegion(dst);
      updateKillSetForDcl(dcl, curBBGen, curBBKill, curBB, entryBBGen,
                          entryBBKill, entryBB, scopeID);
    }

    for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) {
      G4_Operand *src = inst->getSrc(i);
      if (src) {
        if (src->isSrcRegRegion() &&
            src->asSrcRegRegion()->getBase()->isRegAllocPartaker()) {
          G4_Declare *dcl = GetTopDclFromRegRegion(src);
          updateKillSetForDcl(dcl, curBBGen, curBBKill, curBB, entryBBGen,
                              entryBBKill, entryBB, scopeID);
        } else if (src->isAddrExp() &&
                   src->asAddrExp()->getRegVar()->isRegAllocPartaker()) {
          G4_Declare *dcl =
              src->asAddrExp()->getRegVar()->getDeclare()->getRootDeclare();

          updateKillSetForDcl(dcl, curBBGen, curBBKill, curBB, entryBBGen,
                              entryBBKill, entryBB, scopeID);
        }
      }
    }
  }
}

void LivenessAnalysis::detectNeverDefinedVarRows() {
  // This function records variables and its rows that are never defined
  // in the kernel. This information helps detect kills for partial
  // writes when VISA optimizer optimizes away some rows of a variable.
  // In interest of compile time we only look for full rows that are
  // not defined rather than sub-regs.
  std::unordered_map<G4_Declare *, BitSet> largeDefs;

  // Populate largeDefs map with dcls > 1 GRF size
  for (auto dcl : gra.kernel.Declares) {
    if (dcl->getAliasDeclare() || dcl->getIsPartialDcl() || dcl->getAddressed())
      continue;

    if (dcl->getRegFile() != G4_GRF)
      continue;

    unsigned int dclNumRows = dcl->getNumRows();

    if (dclNumRows < 2)
      continue;

    BitSet bitset(dclNumRows, false);

    largeDefs.insert(std::make_pair(dcl, std::move(bitset)));
  }

  if (largeDefs.empty())
    return;

  const unsigned bytesPerGRF = fg.builder->numEltPerGRF<Type_UB>();

  // Update row usage of each dcl in largeDefs
  for (auto bb : gra.kernel.fg) {
    for (auto inst : *bb) {
      auto dst = inst->getDst();
      if (!dst)
        continue;

      auto dstTopDcl = dst->getTopDcl();

      if (dstTopDcl) {
        auto it = largeDefs.find(dstTopDcl);

        if (it == largeDefs.end()) {
          continue;
        }

        unsigned int rowStart = dst->getLeftBound() / bytesPerGRF;
        unsigned int rowEnd = dst->getRightBound() / bytesPerGRF;

        it->second.set(rowStart, rowEnd);
      }
    }
  }

  // Propagate largeDefs to neverDefinedRows bit vector to later bitwise OR it
  for (const auto &it : largeDefs) {
    unsigned int numRows = it.first->getNumRows();
    BitSet *undefinedRows = nullptr;
    for (unsigned int i = 0; i < numRows; i++) {
      if (!it.second.isSet(i)) {
        if (undefinedRows == nullptr) {
          undefinedRows =
              &neverDefinedRows
                   .emplace(it.first, BitSet(it.first->getByteSize(), false))
                   .first->second;
        }
        undefinedRows->set(i * bytesPerGRF, i * bytesPerGRF + bytesPerGRF - 1);
      }
    }
  }
}

// #1 - (P166) sel (M1, 8) V2(0,0)<1> 0x1:d 0x0:d
// #2 - (W) mov(M1, 8) V1(0,0)<1> 0x0:ud
// #3 - (W) mov (M1, 1) V3 0x1:ud
// #4 - add (M1, 8) V1(0,0)<1> V2(0,0)<1;1,0> V3(0,0)<0;1,0>
//
// In above 3d program, V1 is written once using WriteEnable and and once without
// WriteEnable. A var must be treated as KILLED only for widest def. In this case,
// widest def of V1 is one with WriteEnable set. Although def of V1 in inst# 4
// writes all enabled channels, it may not be as wide as WriteEnable in inst#1.
// Marking #4 as KILL allows RA to use same register for V1 and V3 which can be
// incorrect if all but lowest channel are enabled. Because in this case lowest
// channel data would be overwritten by V3 def.
//
// In this method, we gather all variables written with WriteEnable and refer to
// this list when computing pseudo_kill. Note that WriteEnable takes effect only
// in divergent context. In other words, for ESIMD target, all channels are enabled
// at thread dispatch. Whereas for 3d, even entry BB is considered to be divergent.
void LivenessAnalysis::collectNoMaskVars() {
  for (auto bb : gra.kernel.fg) {
    for (auto inst : *bb) {
      if (!inst->isWriteEnableInst())
        continue;

      auto inDivergentContext = [&]() {
        // 3d is always in divergent context
        // ESIMD is divergent only in BBs that are explicitly divergent
        return fg.getKernel()->getInt32KernelAttr(Attributes::ATTR_Target) ==
                   VISA_3D ||
               !bb->isAllLaneActive();
      };

      G4_Operand *opnd = nullptr;
      if (livenessClass(G4_GRF))
        opnd = inst->getDst();
      else if (livenessClass(G4_FLAG))
        opnd = inst->getCondMod();

      if (opnd && opnd->getBase() && opnd->getBase()->isRegAllocPartaker() &&
          inDivergentContext()) {
        defWriteEnable.insert(opnd->getTopDcl());
      }
    }
  }
}

bool LivenessAnalysis::doesVarNeedNoMaskForKill(const G4_Declare* dcl) const {
  return defWriteEnable.count(dcl) == 0 ? false : true;
}

//
// compute liveness of reg vars
// Each reg var indicates a region within the register file. As such, the case
// in which two consecutive defs of a reg region without any use in between does
// not mean the second def overwrites the first one because the two defs may
// write different parts of the region. Def vectors are used to track which
// definitions of reg vars reach the entry and the end of a basic block, which
// tell us the first definitions of reg vars. Use vectors track which uses of
// reg vars are anticipated, which tell use the uses of reg vars.Def and Use
// vectors encapsulate the liveness of reg vars.
//
void LivenessAnalysis::computeLiveness() {
  //
  // no reg var is selected, then no need to compute liveness
  //
  if (getNumSelectedVar() == 0) {
    return;
  }

  startTimer(TimerID::LIVENESS);

  //
  // mark input arguments live at the entry of kernel
  // mark output arguments live at the exit of kernel
  //
  SparseBitVector inputDefs;
  SparseBitVector outputUses;

  for (unsigned i = 0; i < numVarId; i++) {
    bool setLiveIn = false;
    if (!vars[i])
      continue;

    G4_Declare *decl = vars[i]->getDeclare();

    if ((decl->isInput() == true &&
         !(fg.builder->getFCPatchInfo()->getFCComposableKernel() &&
           !decl->isLiveIn())) &&
        !(fg.builder->isPreDefArg(decl) &&
          (fg.builder->getIsKernel() ||
           (fg.getIsStackCallFunc() && fg.builder->getArgSize() == 0))))
      setLiveIn = true;

    // FIXME: Why make this liveIn? we are copying RealR0 to BuiltInR0 at kernel
    // entry, so by definition it's not live-in.
    if (!fg.builder->canReadR0() && decl == fg.builder->getBuiltinR0())
      setLiveIn = true;

    if (setLiveIn) {
      inputDefs.set(i);
      VISA_DEBUG_VERBOSE(std::cout << "First def input = " << decl->getName()
                                   << "\n");
    }

    bool setLiveOut = false;
    if (decl->isOutput() == true &&
        !(fg.builder->isPreDefRet(decl) &&
          (fg.builder->getIsKernel() ||
           (fg.getIsStackCallFunc() && fg.builder->getRetVarSize() == 0))))
      setLiveOut = true;

    // FIXME: Why do we need to force builtinR0 to be liveOut?
    if (!fg.builder->canReadR0() && decl == fg.builder->getBuiltinR0())
      setLiveOut = true;

    if (setLiveOut) {
      outputUses.set(i);
      VISA_DEBUG_VERBOSE(
          std::cout << "First def output    = " << decl->getName() << "\n");
    }
  }

  //
  // clean up def_in & def_out that are used in markFirstDef
  //
  for (unsigned i = 0; i < numBBId; i++) {
    def_in[i].clear();
    def_out[i].clear();
  }

  collectNoMaskVars();
  if (livenessClass(G4_GRF))
    detectNeverDefinedVarRows();

  //
  // compute def_out and use_in vectors for each BB
  //
  for (G4_BB *bb : fg) {
    unsigned id = bb->getId();

    computeGenKillandPseudoKill(bb, def_out[id], use_in[id], use_gen[id],
                                use_kill[id]);

    //
    // exit block: mark output parameters live
    //
    if (bb->Succs.empty()) {
      use_out[id] = outputUses;
    }
  }

  G4_BB *subEntryBB = NULL;
  SparseBitVector *subEntryKill = NULL;
  SparseBitVector *subEntryGen = NULL;

  if (fg.getKernel()->getInt32KernelAttr(Attributes::ATTR_Target) == VISA_CM) {
    //
    // Top-down order of BB list iteration guarantees that
    // entry BB of each sub-routine will be seen before any other
    // BBs belonging to that sub-routine. This assumes that BBs of
    // a sub-routine are laid out back to back in bb list.
    //
    for (auto bb : fg) {
      unsigned id = bb->getId();

      if (bb->getScopeID() != 0 && bb->getScopeID() != UINT_MAX) {
        subEntryBB = fg.sortedFuncTable[bb->getScopeID() - 1]->getInitBB();
        unsigned entryBBID = subEntryBB->getId();
        subEntryKill = &use_kill[entryBBID];
        subEntryGen = &use_gen[entryBBID];
      }

      //
      // Mark explicitly scoped variables as kills
      //
      performScoping(&use_gen[id], &use_kill[id], bb, subEntryGen, subEntryKill,
                     subEntryBB);
    }
  }

  //
  // compute indr accesses
  //
  if (selectedRF & G4_GRF) {
    // only GRF variables can have their address taken
    for (auto bb : fg) {
      const REGVAR_VECTOR &grfVec =
          pointsToAnalysis.getIndrUseVectorForBB(bb->getId());
      for (const pointInfo addrTaken : grfVec) {
        indr_use[bb->getId()].set(addrTaken.var->getId());
        addr_taken.set(addrTaken.var->getId(), true);
      }
    }
  }
  //
  // Perform inter-procedural context-sensitive flow analysis.
  // This is required when the CFG involves function calls with multiple calling
  // contexts for the same function, as peforming just a context-insensitive
  // analysis results in uses being propgated along paths that are not feasible
  // in the actual program.
  //
  if (performIPA()) {
    hierarchicalIPA(inputDefs, outputUses);
    stopTimer(TimerID::LIVENESS);
    return;
  }

  if (fg.getKernel()->getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D &&
      (selectedRF & G4_GRF || selectedRF & G4_FLAG) && (numFnId > 0)) {
    // compute the maydef for each subroutine
    maydefAnalysis();
  }

  auto getPostOrder = [](G4_BB *S, std::vector<G4_BB *> &PO) {
    std::stack<std::pair<G4_BB *, BB_LIST_ITER>> Stack;
    std::set<G4_BB *> Visited;

    Stack.push({S, S->Succs.begin()});
    Visited.insert(S);
    while (!Stack.empty()) {
      G4_BB *Curr = Stack.top().first;
      BB_LIST_ITER It = Stack.top().second;

      if (It != Curr->Succs.end()) {
        G4_BB *Child = *Stack.top().second++;
        if (Visited.insert(Child).second) {
          Stack.push({Child, Child->Succs.begin()});
        }
        continue;
      }
      PO.push_back(Curr);
      Stack.pop();
    }
  };

  std::vector<G4_BB *> PO;
  getPostOrder(fg.getEntryBB(), PO);

  bool change;

  //
  // backward flow analysis to propagate uses (locate last uses)
  //
  do {
    change = false;
    for (auto I = PO.begin(), E = PO.end(); I != E; ++I)
      change |= contextFreeUseAnalyze(*I, change);
  } while (change);

  //
  // initialize entry block with payload input
  //
  def_in[fg.getEntryBB()->getId()] = std::move(inputDefs);

  //
  // forward flow analysis to propagate defs (locate first defs)
  //
  do {
    change = false;
    for (auto I = PO.rbegin(), E = PO.rend(); I != E; ++I)
      change |= contextFreeDefAnalyze(*I, change);
  } while (change);

  //
  // dump vectors for debugging
  //
#if 0
    {
        dump_bb_vector("DEF IN", def_in);
        dump_bb_vector("DEF OUT", def_out);
        dump_bb_vector("USE IN", use_in);
        dump_bb_vector("USE OUT", use_out);
    }
#endif

  stopTimer(TimerID::LIVENESS);
}

//
// compute the maydef set for every subroutine
// This includes recursively all the variables that are defined by the
// subroutine, but does not include defs in the caller
// This means this must be called before we do fix-point on def_in/def_out
// and destroy their original values
// This is used by augmentation later to model all variables that may be defined
// by a call
// FIXME: we should use a separate def set to represent declares defined in each
// BB
//
void LivenessAnalysis::maydefAnalysis() {
  for (auto func : fg.sortedFuncTable) {
    unsigned fid = func->getId();
    if (fid == UINT_MAX) {
      // entry kernel
      continue;
    }

    auto &BV = subroutineMaydef[func];
    for (auto &&bb : func->getBBList()) {
      BV |= def_out[bb->getId()];
    }
    for (auto &&callee : func->getCallees()) {
      BV |= subroutineMaydef[callee];
    }
  }
}

//
// Use analysis for this subroutine only
// use_out[call-BB] = use_in[ret-BB]
// use_out[exit-BB] should be initialized by the caller
//
void LivenessAnalysis::useAnalysis(FuncInfo *subroutine) {
  bool changed = false;
  do {
    changed = false;
    for (auto BI = subroutine->getBBList().rbegin(),
              BE = subroutine->getBBList().rend();
         BI != BE; ++BI) {
      //
      // use_out = use_in(s1) + use_in(s2) + ...
      // where s1 s2 ... are the successors of bb
      // use_in  = use_gen + (use_out - use_kill)
      //
      G4_BB *bb = *BI;
      unsigned bbid = bb->getId();
      if (bb->getBBType() & G4_BB_EXIT_TYPE) {
        // use_out is set by caller
      } else if (bb->getBBType() & G4_BB_CALL_TYPE) {
        use_out[bbid] |= use_in[bb->getPhysicalSucc()->getId()];
      } else {
        for (auto succ : bb->Succs) {
          use_out[bbid] |= use_in[succ->getId()];
        }
      }

      if (changed) {
        // no need to update changed, save a copy
        use_in[bbid] = use_out[bbid];
        use_in[bbid] = use_in[bbid] - use_kill[bbid];
        use_in[bbid] |= use_gen[bbid];
      } else {
        SparseBitVector oldUseIn = use_in[bbid];

        use_in[bbid] = use_out[bbid];
        use_in[bbid] = use_in[bbid] - use_kill[bbid];
        use_in[bbid] |= use_gen[bbid];

        if (!(bb->getBBType() & G4_BB_INIT_TYPE) && oldUseIn != use_in[bbid]) {
          changed = true;
        }
      }
    }
  } while (changed);
}

//
// Use analysis for this subroutine only, considering both arg/retval of its
// callees use_out[call-BB] = (use_in[ret-BB] | arg[callee]) - retval[callee]
//
void LivenessAnalysis::useAnalysisWithArgRetVal(
    FuncInfo *subroutine,
    const std::unordered_map<FuncInfo *, SparseBitVector> &args,
    const std::unordered_map<FuncInfo *, SparseBitVector> &retVal) {
  bool changed = false;
  do {
    changed = false;
    for (auto BI = subroutine->getBBList().rbegin(),
              BE = subroutine->getBBList().rend();
         BI != BE; ++BI) {
      //
      // use_out = use_in(s1) + use_in(s2) + ...
      // where s1 s2 ... are the successors of bb
      // use_in  = use_gen + (use_out - use_kill)
      //
      G4_BB *bb = *BI;
      unsigned bbid = bb->getId();
      if (bb->getBBType() & G4_BB_EXIT_TYPE) {
        // use_out is set by previous analysis
      } else if (bb->getBBType() & G4_BB_CALL_TYPE) {
        use_out[bbid] = use_in[bb->getPhysicalSucc()->getId()];
        auto callee = bb->getCalleeInfo();
        auto BVIt = args.find(callee);
        vISA_ASSERT(BVIt != args.end(), "Missing entry in map");
        use_out[bbid] |= (*BVIt).second;
        BVIt = retVal.find(callee);
        vISA_ASSERT(BVIt != retVal.end(), "Missing entry in map");
        use_out[bbid] = use_out[bbid] - (*BVIt).second;
      } else {
        for (auto succ : bb->Succs) {
          use_out[bbid] |= use_in[succ->getId()];
        }
      }

      if (changed) {
        // no need to update changed, save a copy
        use_in[bbid] = use_out[bbid];
        use_in[bbid] = use_in[bbid] - use_kill[bbid];
        use_in[bbid] |= use_gen[bbid];
      } else {
        SparseBitVector oldUseIn = use_in[bbid];

        use_in[bbid] = use_out[bbid];
        use_in[bbid] = use_in[bbid] - use_kill[bbid];
        use_in[bbid] |= use_gen[bbid];

        if (!(bb->getBBType() & G4_BB_INIT_TYPE) && oldUseIn != use_in[bbid]) {
          changed = true;
        }
      }
    }
  } while (changed);
}

//
// Def analysis for each subroutine only
// at a call site, we do
// def_in[ret-BB] = def_out[call-BB] U def_out[callee exit-BB]
// callee's def_in/def_out is not modified
//
void LivenessAnalysis::defAnalysis(FuncInfo *subroutine) {

  // def_in[bb] = null (inputs for entry BB)
  // def_out[bb] is initialized to all defs in the bb
  bool changed = false;
  do {
    changed = false;
    for (auto &&bb : subroutine->getBBList()) {
      uint32_t bbid = bb->getId();
      std::optional<SparseBitVector> defInOrNull = std::nullopt;
      if (!changed) {
        defInOrNull = def_in[bbid];
      }
      auto phyPredBB =
          (bb == fg.getEntryBB()) ? nullptr : bb->getPhysicalPred();
      if (phyPredBB && (phyPredBB->getBBType() & G4_BB_CALL_TYPE)) {
        // this is the return BB, we take the def_out of the callBB + the
        // predecessors
        G4_BB *callBB = bb->getPhysicalPred();
        def_in[bbid] |= def_out[callBB->getId()];
        for (auto &&pred : bb->Preds) {
          def_in[bbid] |= def_out[pred->getId()];
        }
      } else if (bb->getBBType() & G4_BB_INIT_TYPE) {
        // do nothing as we don't want to propagate caller defs yet
      } else {
        for (auto &&pred : bb->Preds) {
          def_in[bbid] |= def_out[pred->getId()];
        }
      }

      if (!changed) {
        if (def_in[bbid] != defInOrNull.value()) {
          changed = true;
        }
      }
      def_out[bbid] |= def_in[bbid];
    }
  } while (changed);
}

void LivenessAnalysis::hierarchicalIPA(const SparseBitVector &kernelInput,
                                       const SparseBitVector &kernelOutput) {

  vISA_ASSERT(fg.sortedFuncTable.size() > 0,
              "topological sort must already be performed");

#ifdef _DEBUG
  auto verifyFuncTable = [&]() {
    auto accountedBBs = 0;
    for (auto &sub : fg.sortedFuncTable) {
      accountedBBs += sub->getBBList().size();
    }
    vISA_ASSERT(fg.getBBList().size() == accountedBBs, "unaccounted bbs");
  };
  verifyFuncTable();
#endif

  auto initKernelLiveOut = [this, &kernelOutput]() {
    for (auto &&bb : fg.kernelInfo->getBBList()) {
      if (bb->Succs.empty()) {
        // EOT BB
        use_out[bb->getId()] = kernelOutput;
      }
    }
  };
  // reset all live-in/out sets except for the kernel live-out
  auto clearLiveSets = [this]() {
    for (auto subroutine : fg.sortedFuncTable) {
      for (auto bb : subroutine->getBBList()) {
        use_in[bb->getId()].clear();
        use_out[bb->getId()].clear();
      }
    }
  };

  // top-down traversal to compute retval for each subroutine
  // retval[s] = live_out[s] - live_in[s],
  // where live_out[s] is the union of the live-in of the ret BB at each call
  // site (hence top-down traversal). this is not entirely accurate since we may
  // have pass-through retVals (e.g., A call B call C, C's retVal is
  // pass-through in B and used in A, which
  //  means it won't be killed in B if we do top-down)
  // But for now let's trade some loss of accuracy to save one more round of
  // fix-point
  initKernelLiveOut();
  for (auto FI = fg.sortedFuncTable.rbegin(), FE = fg.sortedFuncTable.rend();
       FI != FE; ++FI) {
    auto subroutine = *FI;
    useAnalysis(subroutine);
    if (subroutine != fg.kernelInfo) {
      retVal[subroutine] = use_out[subroutine->getExitBB()->getId()];
      retVal[subroutine] =
          retVal[subroutine] - use_in[subroutine->getInitBB()->getId()];
    }
    for (auto &&bb : subroutine->getBBList()) {
      if (bb->getBBType() & G4_BB_CALL_TYPE) {
        G4_BB *retBB = bb->getPhysicalSucc();
        G4_BB *exitBB = bb->getCalleeInfo()->getExitBB();
        vISA_ASSERT((exitBB->getBBType() & G4_BB_EXIT_TYPE),
                    "should be a subroutine's exit BB");
        use_out[exitBB->getId()] |= use_in[retBB->getId()];
      }
    }
  }

  // bottom-up traversal to compute arg for each subroutine
  // arg[s] = live-in[s], except retval of its callees are excluded as by
  // definition they will not be live-in The live-out of each subroutine is
  // initialized to null so that args are limited to variables actually used in
  // this subroutine (and its callees)
  clearLiveSets();
  initKernelLiveOut();
  for (auto subroutine : fg.sortedFuncTable) {
    useAnalysisWithArgRetVal(subroutine, args, retVal);
    if (subroutine != fg.kernelInfo) {
      args[subroutine] = use_in[subroutine->getInitBB()->getId()];
      args[subroutine] =
          args[subroutine] - use_out[subroutine->getExitBB()->getId()];
    }
  }

  // the real deal -- top-down traversal taking arg/retval/live-through all into
  // consideration again top-down traversal is needed to compute the live-out of
  // each subroutine.
  clearLiveSets();
  initKernelLiveOut();
  for (auto FI = fg.sortedFuncTable.rbegin(), FE = fg.sortedFuncTable.rend();
       FI != FE; ++FI) {
    auto subroutine = *FI;
    useAnalysisWithArgRetVal(subroutine, args, retVal);
    for (auto &&bb : subroutine->getBBList()) {
      if (bb->getBBType() & G4_BB_CALL_TYPE) {
        G4_BB *retBB = bb->getPhysicalSucc();
        G4_BB *exitBB = bb->getCalleeInfo()->getExitBB();
        vISA_ASSERT((exitBB->getBBType() & G4_BB_EXIT_TYPE),
                    "should be a subroutine's exit BB");
        use_out[exitBB->getId()] |= use_in[retBB->getId()];
      }
    }
  }

  maydefAnalysis(); // must be done before defAnalysis!

  // algorithm sketch for def-in/def-out:
  // In reverse topological order :
  //  -- Run def analysis on subroutine
  //  -- at each call site:
  //       def_in[ret-BB] |= def_out[call-BB] U def_out[exit-BB]
  // In topological order :
  //  -- At each call site:
  //       add def_out[call-BB] to all of callee's BBs
  def_in[fg.getEntryBB()->getId()] = kernelInput;
  for (auto subroutine : fg.sortedFuncTable) {
    defAnalysis(subroutine);
  }

  // FIXME: I assume we consider all caller's defs to be callee's defs too?
  for (auto FI = fg.sortedFuncTable.rbegin(), FE = fg.sortedFuncTable.rend();
       FI != FE; ++FI) {
    auto subroutine = *FI;
    if (subroutine->getCallees().size() == 0) {
      continue;
    }
    for (auto &&bb : subroutine->getBBList()) {
      if (bb->getBBType() & G4_BB_CALL_TYPE) {
        auto callee = bb->getCalleeInfo();
        for (auto &&calleeBB : callee->getBBList()) {
          def_in[calleeBB->getId()] |= def_out[bb->getId()];
          def_out[calleeBB->getId()] |= def_out[bb->getId()];
        }
      }
    }
  }
}

//
// determine if the dst writes the whole region of target declare
//
bool LivenessAnalysis::writeWholeRegion(const G4_BB *bb, const G4_INST *inst,
                                        G4_DstRegRegion *dst) const {
  unsigned execSize = inst->getExecSize();
  vISA_ASSERT(dst->getBase()->isRegVar(), ERROR_REGALLOC);

  if (!bb->isAllLaneActive() && !inst->isWriteEnableInst() &&
      fg.getKernel()->getInt32KernelAttr(Attributes::ATTR_Target) != VISA_3D) {
    // conservatively assume non-nomask instructions in simd control flow
    // may not write the whole region
    return false;
  }

  if (inst->getPredicate()) {
    return false;
  }

  if (inst->isFCall())
    return true;

  // Flags may be partially written when used as the destination
  // e.g., setp (M5_NM, 16) P11 V97(8,0)<0;1,0>
  // It can be only considered as a complete kill
  // if the computed bound diff matches with the number of flag elements
  if (dst->isFlag() == true) {
    if ((dst->getRightBound() - dst->getLeftBound() + 1) ==
        dst->getBase()->asRegVar()->getDeclare()->getNumberFlagElements()) {
      return true;
    } else {
      return false;
    }
  }

  //
  // Find Primary Variable Declare
  //

  const G4_Declare *decl = ((const G4_RegVar *)dst->getBase())->getDeclare();
  const G4_Declare *primaryDcl = decl->getRootDeclare();

  //
  //  Cannot write whole register if
  //     * alias offset in non zero
  //     * reg or sub-reg offset is non zero
  //     * horiz stride is non zero
  //     * predicate is non null
  //
  if (decl->getAliasOffset() != 0 || dst->getRegAccess() != Direct ||
      dst->getRegOff() != 0 || dst->getSubRegOff() != 0 ||
      dst->getHorzStride() != 1 || inst->isPartialWrite()) {
    return false;
  }

  //
  // For CISA3, pseudo-callee-save and pseudo-caller-save insts
  // are kills
  //
  if (fg.isPseudoDcl(primaryDcl)) {
    return true;
  }

  //
  // If the region does not cover the whole declare then it does not write the
  // whole region.
  //
  if ((dst->getTypeSize() * execSize != primaryDcl->getElemSize() *
                                            primaryDcl->getNumElems() *
                                            primaryDcl->getNumRows())) {
    return false;
  }

  if (doesVarNeedNoMaskForKill(primaryDcl) && !inst->isWriteEnableInst())
    return false;

  return true;
}

//
// determine if the dst writes the whole region of target declare
//
bool LivenessAnalysis::writeWholeRegion(const G4_BB *bb, const G4_INST *inst,
                                        const G4_VarBase *flagReg) const {
  if (!bb->isAllLaneActive() && !inst->isWriteEnableInst() &&
      gra.kernel.getKernelType() != VISA_3D) {
    // conservatively assume non-nomask instructions in simd control flow
    // may not write the whole region
    return false;
  }

  const G4_Declare *decl = flagReg->asRegVar()->getDeclare();
  if (inst->getExecSize() != G4_ExecSize(decl->getNumberFlagElements())) {
    return false;
  }

  return true;
}

// Set bits in dst footprint based on dst region's left/right bound
void LivenessAnalysis::footprintDst(const G4_BB *bb, const G4_INST *i,
                                    G4_Operand *opnd,
                                    BitSet *dstfootprint) const {
  if (dstfootprint && !(i->isPartialWrite()) &&
      ((bb->isAllLaneActive() || i->isWriteEnableInst() == true) ||
       (gra.kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D &&
        !doesVarNeedNoMaskForKill(opnd->getTopDcl())))) {
    // Bitwise OR left-bound/right-bound with dst footprint to indicate
    // bytes that are written in to
    opnd->updateFootPrint(*dstfootprint, true, *fg.builder);
  }
}

// Reset bits in srcfootprint based on src region's left/right bound
void LivenessAnalysis::footprintSrc(const G4_INST *i, G4_Operand *opnd,
                                    BitSet *srcfootprint) {
  // Reset bits in kill map footprint
  opnd->updateFootPrint(*srcfootprint, false, i->getBuilder());
}

void LivenessAnalysis::computeGenKillandPseudoKill(
    G4_BB *bb, SparseBitVector &def_out, SparseBitVector &use_in,
    SparseBitVector &use_gen, SparseBitVector &use_kill) const {
  //
  // Mark each fcall as using all globals and arg pre-defined var
  //
  if (bb->isEndWithFCall() && (selectedRF & G4_GRF)) {
    const G4_Declare *arg = fg.builder->getStackCallArg();
    const G4_Declare *ret = fg.builder->getStackCallRet();

    auto fcall = fg.builder->getFcallInfo(bb->back());
    vISA_ASSERT(fcall != std::nullopt, "fcall info not found");

    if (arg->getByteSize() != 0) {
      // arg var is a use and a kill at each fcall
      if (fcall->getArgSize() != 0) {
        use_gen.set(arg->getRegVar()->getId());
      }
      use_kill.set(arg->getRegVar()->getId());
    }

    if (ret->getByteSize() != 0) {
      // ret var is a kill at each fcall
      use_kill.set(ret->getRegVar()->getId());
      if (fcall->getRetSize() != 0) {
        def_out.set(ret->getRegVar()->getId());
      }
    }
  }

  std::map<unsigned, BitSet> footprints;
  std::vector<std::pair<G4_Declare *, INST_LIST_RITER>> pseudoKills;
  std::map<G4_Declare *, INST_LIST_RITER> pseudoKillsForSpills;

  for (INST_LIST::reverse_iterator rit = bb->rbegin(), rend = bb->rend();
       rit != rend; ++rit) {
    G4_INST *i = (*rit);
    if (i->isLifeTimeEnd()) {
      continue;
    }

    G4_DstRegRegion *dst = i->getDst();
    if (dst) {
      G4_DstRegRegion *dstrgn = dst;

      if (dstrgn->getBase()->isRegAllocPartaker()) {
        G4_Declare *topdcl = GetTopDclFromRegRegion(dstrgn);
        unsigned id = topdcl->getRegVar()->getId();
        if (i->isPseudoKill()) {
          // Mark kill, reset gen
          use_kill.set(id);
          use_gen.reset(id);

          continue;
        }

        BitSet *dstfootprint = &footprints[id];

        if (dstfootprint->getSize() == 0) {
          // Write for dst was not seen before, so insert in to map
          // bitsetSize is in bytes
          unsigned int bitsetSize = dstrgn->isFlag()
                                        ? topdcl->getNumberFlagElements()
                                        : topdcl->getByteSize();

          BitSet newBitSet(bitsetSize, false);

          auto it = neverDefinedRows.find(topdcl);
          if (it != neverDefinedRows.end()) {
            // Bitwise OR new bitset with never defined rows
            newBitSet |= it->second;
          }

          footprints[id] = std::move(newBitSet);
          if (gra.isBlockLocal(topdcl) && topdcl->getAddressed() == false &&
              dstrgn->getRegAccess() == Direct) {
            // Local live ranges are never live-out of the only
            // basic block they are defined. So in top-down order
            // the first lexical definition is a kill irrespective
            // of the footprint. In cases when local live-range
            // def and use have h-stride != 1, the footprint at this
            // lexically first definition will not have all bits set.
            // This prevents that def to be seen as a kill. A simple
            // solution to this is to set all bits when initializing
            // the bitvector while iterating in bottom-up order. As
            // we traverse further up uses will reset bits and defs
            // will set bits. So when we encounter the lexically first
            // def, we will be guaranteed to find all bits set, thus
            // interpreting that def as a kill.
            dstfootprint->setAll();
          }
        }

        if (dstrgn->getRegAccess() == Direct) {
          def_out.set(id);
          //
          // if the inst writes the whole region the var declared, we set
          // use_kill so that use of var will not pass through (i.e., var's
          // interval starts at this instruction.
          //
          if (writeWholeRegion(bb, i, dstrgn)) {
            use_kill.set(id);
            use_gen.reset(id);

            dstfootprint->setAll();
          } else {
            footprintDst(bb, i, dstrgn, dstfootprint);

            use_gen.set(id);
          }
        } else {
          use_gen.set(id);
        }
      } else if ((selectedRF & G4_GRF) && dst->isIndirect()) {
        // conservatively add each variable potentially accessed by dst to gen
        const REGVAR_VECTOR &pointsToSet =
            pointsToAnalysis.getAllInPointsToOrIndrUse(dst, bb);
        for (auto &pt : pointsToSet) {
          if (pt.var->isRegAllocPartaker()) {
            use_gen.set(pt.var->getId());
          }
        }
      }
    }

    //
    // process each source operand
    //
    for (unsigned j = 0, numSrc = i->getNumSrc(); j < numSrc; j++) {
      G4_Operand *src = i->getSrc(j);
      if (!src)
        continue;

      if (src->isSrcRegRegion()) {
        G4_Declare *topdcl = GetTopDclFromRegRegion(src);
        const G4_VarBase *base =
            (topdcl != nullptr ? topdcl->getRegVar()
                               : src->asSrcRegRegion()->getBase());
        if (base->isRegAllocPartaker()) {
          vASSERT(topdcl);
          unsigned id = topdcl->getRegVar()->getId();
          BitSet *srcfootprint = &footprints[id];

          if (srcfootprint->getSize() != 0) {
            footprintSrc(i, src->asSrcRegRegion(), srcfootprint);
          } else {
            unsigned int bitsetSize = (src->asSrcRegRegion()->isFlag())
                                          ? topdcl->getNumberFlagElements()
                                          : topdcl->getByteSize();

            BitSet newBitSet(bitsetSize, false);

            auto it = neverDefinedRows.find(topdcl);
            if (it != neverDefinedRows.end()) {
              // Bitwise OR new bitset with never defined rows
              newBitSet |= it->second;
            }

            footprints[id] = std::move(newBitSet);
            if (gra.isBlockLocal(topdcl) && topdcl->getAddressed() == false &&
                (topdcl->getRegFile() == G4_ADDRESS ||
                 src->asSrcRegRegion()->getRegAccess() == Direct)) {
              srcfootprint->setAll();
            }
            footprintSrc(i, src->asSrcRegRegion(), srcfootprint);
          }

          use_gen.set(static_cast<const G4_RegVar *>(base)->getId());
        }

        if ((selectedRF & G4_GRF) && src->isIndirect()) {
          int idx = 0;
          G4_RegVar *grf;
          G4_Declare *topdcl = GetTopDclFromRegRegion(src);

          while ((grf = pointsToAnalysis.getPointsTo(topdcl->getRegVar(),
                                                     idx++)) != NULL) {
            // grf is a variable that src potentially points to
            // since we dont know exactly which part of grf is sourced
            // assume entire grf is sourced
            // Also add grf to the gen set as it may be potentially used
            unsigned int id = grf->getId();
            use_gen.set(id);
            BitSet *srcfootprint = &footprints[id];

            if (srcfootprint->getSize() != 0) {
              srcfootprint->clear();

              DEBUG_VERBOSE("Found potential indirect use of "
                            << grf->getDeclare()->getName()
                            << " so resetting its footprint"
                            << "\n");
            }
          }
        }
      }
      //
      // treat the addr expr as both a use and a partial def
      //
      else if (src->isAddrExp()) {
        G4_RegVar *reg = static_cast<G4_AddrExp *>(src)->getRegVar();
        if (reg->isRegAllocPartaker() && !reg->isRegVarTmp()) {
          unsigned srcId = reg->getId();
          use_gen.set(srcId);
          def_out.set(srcId);
        }
      }
    }

    //
    // Process condMod
    //
    G4_CondMod *mod = i->getCondMod();
    if (mod) {
      G4_VarBase *flagReg = mod->getBase();
      if (flagReg) {
        if (flagReg->asRegVar()->isRegAllocPartaker()) {
          G4_Declare *topdcl = flagReg->asRegVar()->getDeclare();
          vISA_ASSERT(topdcl->getAliasDeclare() == nullptr,
                      "Invalid alias flag decl.");
          unsigned id = topdcl->getRegVar()->getId();

          BitSet *dstfootprint = &footprints[id];

          if (dstfootprint->getSize() == 0) {
            // Write for dst was not seen before, so insert in to map
            // bitsetSize is in bits for flag
            unsigned int bitsetSize = topdcl->getNumberFlagElements();

            BitSet newBitSet(bitsetSize, false);
            footprints[id] = std::move(newBitSet);

            if (gra.isBlockLocal(topdcl)) {
              dstfootprint->setAll();
            }
          }

          def_out.set(id);

          if (writeWholeRegion(bb, i, flagReg)) {
            use_kill.set(id);
            use_gen.reset(id);

            dstfootprint->setAll();
          } else {
            footprintDst(bb, i, mod, dstfootprint);
            use_gen.set(id);
          }
        }
      } else {
        vISA_ASSERT((i->opcode() == G4_sel || i->opcode() == G4_csel) &&
                        i->getCondMod() != nullptr,
                    "Invalid CondMod");
      }
    }

    //
    // Process predicate
    //
    G4_Predicate *predicate = i->getPredicate();
    if (predicate) {
      G4_VarBase *flagReg = predicate->getBase();
      vISA_ASSERT(flagReg->asRegVar()->getDeclare()->getAliasDeclare() ==
                      nullptr,
                  "Invalid alias flag decl.");
      if (flagReg->asRegVar()->isRegAllocPartaker()) {
        const G4_Declare *topdcl = flagReg->asRegVar()->getDeclare();
        unsigned id = topdcl->getRegVar()->getId();
        auto srcfootprint = &footprints[id];

        if (srcfootprint->getSize() != 0) {
          footprintSrc(i, predicate, srcfootprint);
        } else {
          unsigned int bitsetSize = topdcl->getNumberFlagElements();

          BitSet newBitSet(bitsetSize, false);
          footprints[id] = std::move(newBitSet);
          if (gra.isBlockLocal(topdcl)) {
            srcfootprint->setAll();
          }
          footprintSrc(i, predicate, srcfootprint);
        }

        use_gen.set(static_cast<const G4_RegVar *>(flagReg)->getId());
      }
    }

    //
    // Check whether dst can be killed at this point
    // A block of code is said to kill a variable when union
    // of all partial writes causes all elements to be written
    // into and any reads in the block can be sourced from
    // writes within that block itself
    //
    if (dst && dst->getBase()->isRegAllocPartaker()) {
      G4_Declare *topdcl = GetTopDclFromRegRegion(dst);
      vASSERT(topdcl);
      unsigned id = topdcl->getRegVar()->getId();
      auto dstfootprint = &footprints[id];

      if (dstfootprint->getSize() != 0) {
        // Found dst in map
        // Check whether all bits set
        // pseudo_kill for this dst was not found in this BB yet
        unsigned int first;
        LocalLiveRange *topdclLR = nullptr;

        if ((dstfootprint->isAllset() ||
             // Check whether the var is a spill and the inst does not write the
             // whole region
             topdcl->getRegVar()->isRegVarTransient() ||
             // Check whether local RA marked this range
             ((topdclLR = gra.getLocalLR(topdcl)) &&
              topdclLR->isLiveRangeLocal() && (!topdcl->isInput()) &&
              topdclLR->getFirstRef(first) == i)) &&
            // If single inst writes whole region then dont insert pseudo_kill
            writeWholeRegion(bb, i, dst) == false) {
          bool foundKill = false;
          INST_LIST::reverse_iterator nextIt = rit;
          ++nextIt;
          if (nextIt != bb->rend()) {
            const G4_INST *nextInst = (*nextIt);
            if (nextInst->isPseudoKill()) {
              G4_DstRegRegion *nextDst = nextInst->getDst();

              if (nextDst != NULL && nextDst->isDstRegRegion() &&
                  nextDst->getBase()->isRegAllocPartaker() &&
                  topdcl == GetTopDclFromRegRegion(nextDst)) {
                foundKill = true;
              }
            }
          }
          if (!foundKill) {
            // If the original spill is coalesced, then its
            // corresponding pseudo kill would be erased in the
            // cleaning pass. On the other hand, if a kill for the
            // spill is found, the spill is not the candidate for
            // coalescing, and the existing kill will be good.
            if (topdcl->getRegVar()->isRegVarTransient() ||
                topdcl->getRegVar()->isRegVarCoalesced()) {
              // Here we keep tracking the most favorable
              // position, i.e., the topmost, to insert the
              // pseudo kill for spilled and coalesced vars.
              pseudoKillsForSpills.insert_or_assign(topdcl, rit);
            } else {
              // All bytes of dst written at this point, so this is a good place
              // to insert pseudo kill inst
              pseudoKills.emplace_back(topdcl, rit);
            }
          }

          // Reset gen
          use_gen.reset(dst->getBase()->asRegVar()->getId());

          // Set kill
          use_kill.set(dst->getBase()->asRegVar()->getId());
          VISA_DEBUG_VERBOSE({
            std::cout << "Found kill at inst ";
            INST_LIST_ITER fwdIter = rit.base();
            fwdIter--;
            (*fwdIter)->emit(std::cout);
            std::cout << "\n";
          });
        }
      }
    }

    if (mod && mod->getBase() &&
        mod->getBase()->asRegVar()->isRegAllocPartaker()) {
      G4_VarBase *flagReg = mod->getBase();
      G4_Declare *topdcl = flagReg->asRegVar()->getDeclare();
      vASSERT(topdcl);
      unsigned id = topdcl->getRegVar()->getId();
      auto dstfootprint = &footprints[id];

      if (dstfootprint->getSize() != 0) {
        unsigned int first;
        const LocalLiveRange *topdclLR = nullptr;
        if ((dstfootprint->isAllset() ||
             // Check whether local RA marked this range
             // This may not be necessary as currently local RA is not performed
             // for flags.
             ((topdclLR = gra.getLocalLR(topdcl)) &&
              topdclLR->isLiveRangeLocal() &&
              topdclLR->getFirstRef(first) == i)) &&
            // If single inst writes whole region then dont insert pseudo_kill
            writeWholeRegion(bb, i, flagReg) == false) {
          // All bytes of dst written at this point, so this is a good place to
          // insert pseudo kill inst
          pseudoKills.emplace_back(topdcl, rit);

          // Reset gen
          use_gen.reset(flagReg->asRegVar()->getId());

          // Set kill
          use_kill.set(flagReg->asRegVar()->getId());
          VISA_DEBUG_VERBOSE({
            std::cout << "Found kill at inst ";
            INST_LIST_ITER fwdIter = rit.base();
            fwdIter--;
            (*fwdIter)->emit(std::cout);
            std::cout << "\n";
          });
        }
      }
    }
  }

  //
  // Insert pseudo_kill nodes in BB
  //
  for (auto &&pseudoKill : pseudoKills) {
    INST_LIST_ITER iterToInsert = pseudoKill.second.base();
    do {
      --iterToInsert;
    } while ((*iterToInsert)->isPseudoKill());
    G4_INST *killInst = fg.builder->createPseudoKill(
        pseudoKill.first, PseudoKillType::FromLiveness, false);
    bb->insertBefore(iterToInsert, killInst);
  }
  for (auto &pseudoKill : pseudoKillsForSpills) {
    INST_LIST_ITER iterToInsert = pseudoKill.second.base();
    do {
      --iterToInsert;
    } while ((*iterToInsert)->isPseudoKill());
    G4_INST *killInst = fg.builder->createPseudoKill(
        pseudoKill.first, PseudoKillType::FromLiveness, false);
    bb->insertBefore(iterToInsert, killInst);
  }

  //
  // initialize use_in
  //
  use_in = use_gen;
}

//
// use_out = use_in(s1) + use_in(s2) + ... where s1 s2 ... are the successors of
// bb use_in  = use_gen + (use_out - use_kill)
//
bool LivenessAnalysis::contextFreeUseAnalyze(G4_BB *bb, bool isChanged) {
  bool changed;

  unsigned bbid = bb->getId();

  if (bb->Succs.empty()) // exit block
  {
    changed = false;
  } else if (isChanged) {
    // no need to update changed. This saves a memcpy
    for (auto succBB : bb->Succs) {
      use_out[bbid] |= use_in[succBB->getId()];
    }
    changed = true;
  } else {
    SparseBitVector old = use_out[bbid];
    for (auto succBB : bb->Succs) {
      use_out[bbid] |= use_in[succBB->getId()];
    }

    changed = (old != use_out[bbid]);
  }

  //
  // in = gen + (out - kill)
  //
  use_in[bbid] = use_out[bbid];
  use_in[bbid] = use_in[bbid] - use_kill[bbid];
  use_in[bbid] |= use_gen[bbid];

  return changed;
}

//
// def_in = def_out(p1) + def_out(p2) + ... where p1 p2 ... are the predecessors
// of bb def_out |= def_in
//
bool LivenessAnalysis::contextFreeDefAnalyze(G4_BB *bb, bool isChanged) {
  bool changed = false;
  unsigned bbid = bb->getId();

  if (bb->Preds.empty()) {
    changed = false;
  } else if (isChanged) {
    // no need to update changed. This saves a memcpy
    for (auto predBB : bb->Preds) {
      def_in[bbid] |= def_out[predBB->getId()];
    }
    changed = true;
  } else {
    SparseBitVector old = def_in[bbid];
    for (auto predBB : bb->Preds) {
      def_in[bbid] |= def_out[predBB->getId()];
    }
    changed = (old != def_in[bbid]);
  }

  def_out[bb->getId()] |= def_in[bb->getId()];

  return changed;
}

void LivenessAnalysis::dump_bb_vector(char *vname, std::vector<BitSet> &vec) {
  std::cerr << vname << "\n";
  for (BB_LIST_ITER it = fg.begin(); it != fg.end(); it++) {
    G4_BB *bb = (*it);
    std::cerr << "    BB" << bb->getId() << "\n";
    const BitSet &in = vec[bb->getId()];
    std::cerr << "        ";
    for (unsigned i = 0; i < in.getSize(); i += 10) {
      //
      // dump 10 bits a group
      //
      for (unsigned j = i; j < in.getSize() && j < i + 10; j++) {
        std::cerr << (in.isSet(j) ? "1" : "0");
      }
      std::cerr << " ";
    }
    std::cerr << "\n";
  }
}

void LivenessAnalysis::dump_fn_vector(char *vname, std::vector<FuncInfo *> &fns,
                                      std::vector<BitSet> &vec) {
  DEBUG_VERBOSE(vname << "\n");
  for (std::vector<FuncInfo *>::iterator it = fns.begin(); it != fns.end();
       it++) {
    FuncInfo *funcInfo = (*it);

    DEBUG_VERBOSE("    FN" << funcInfo->getId() << "\n");
    const BitSet &in = vec[funcInfo->getId()];
    DEBUG_VERBOSE("        ");
    for (unsigned i = 0; i < in.getSize(); i += 10) {
      //
      // dump 10 bits a group
      //
      for (unsigned j = i; j < in.getSize() && j < i + 10; j++) {
        DEBUG_VERBOSE(in.isSet(j) ? "1" : "0");
      }
      DEBUG_VERBOSE(" ");
    }
    DEBUG_VERBOSE("\n");
  }
}

//
// dump which vars are live at the entry of BB
//
void LivenessAnalysis::dump() const {
  for (auto bb : fg) {
    std::cerr << "BB" << bb->getId() << "'s live in: ";
    unsigned total_size = 0;
    auto dumpVar = [&total_size](G4_RegVar *var) {
      int size =
          var->getDeclare()->getTotalElems() * var->getDeclare()->getElemSize();
      std::cerr << var->getName() << "(" << size << "), ";
      total_size += size;
    };

    unsigned count = 0;
    for (auto var : vars) {
      if (var->isRegAllocPartaker() && isLiveAtEntry(bb, var->getId())) {
        if (count++ % 10 == 0)
          std::cerr << "\n";
        dumpVar(var);
      }
    }
    std::cerr << "\nBB" << bb->getId() << "'s live in size: "
              << total_size / fg.builder->numEltPerGRF<Type_UB>() << "\n\n";
    std::cerr << "BB" << bb->getId() << "'s live out: ";
    total_size = 0;
    count = 0;
    for (auto var : vars) {
      if (var->isRegAllocPartaker() && isLiveAtExit(bb, var->getId())) {
        if (count++ % 10 == 0)
          std::cerr << "\n";
        dumpVar(var);
      }
    }
    std::cerr << "\nBB" << bb->getId() << "'s live out size: "
              << total_size / fg.builder->numEltPerGRF<Type_UB>() << "\n\n";
  }
}

void LivenessAnalysis::dumpBB(G4_BB *bb) const {
  std::cerr << "\n\nBB" << bb->getId() << "'s live in: ";
  unsigned total_size = 0;
  auto dumpVar = [&total_size](G4_RegVar *var) {
    int size =
        var->getDeclare()->getTotalElems() * var->getDeclare()->getElemSize();
    std::cerr << var->getName() << "(" << size << ")"
              << "[" << var->getRegAllocPartaker() << "], ";
    total_size += size;
  };

  unsigned count = 0;
  for (auto var : vars) {
    if (var->isRegAllocPartaker() && isLiveAtEntry(bb, var->getId())) {
      if (count++ % 10 == 0)
        std::cerr << "\n";
      dumpVar(var);
    }
  }
  std::cerr << "\n\nBB" << bb->getId() << "'s live out: ";
  total_size = 0;
  count = 0;
  for (auto var : vars) {
    if (var->isRegAllocPartaker() && isLiveAtExit(bb, var->getId())) {
      if (count++ % 10 == 0)
        std::cerr << "\n";
      dumpVar(var);
    }
  }
  std::cerr << "\n\nBB" << bb->getId() << "'s use through: ";
  total_size = 0;
  count = 0;
  for (auto var : vars) {
    if (var->isRegAllocPartaker() && isUseThrough(bb, var->getId())) {
      if (count++ % 10 == 0)
        std::cerr << "\n";
      dumpVar(var);
    }
  }
  std::cerr << "\n\nBB" << bb->getId() << "'s def through: ";
  total_size = 0;
  count = 0;
  for (auto var : vars) {
    if (var->isRegAllocPartaker() && isDefThrough(bb, var->getId())) {
      if (count++ % 10 == 0)
        std::cerr << "\n";
      dumpVar(var);
    }
  }
}

void LivenessAnalysis::dumpLive(BitSet &live) const {
  auto dumpVar = [](G4_RegVar *var) {
    int size =
        var->getDeclare()->getTotalElems() * var->getDeclare()->getElemSize();
    std::cerr << var->getName() << "(" << size << ")"
              << "[" << var->getRegAllocPartaker() << "], ";
  };

  unsigned count = 0;
  for (auto var : vars) {
    if (live.isSet(var->getId())) {
      if (count++ % 10 == 0)
        std::cerr << "\n";
      dumpVar(var);
    }
  }
}

//
// dump which vars are live at the entry of BB
//
void LivenessAnalysis::dumpGlobalVarNum() const {
  SparseBitVector global_def_out;
  SparseBitVector global_use_in;

  for (auto bb : fg) {
    SparseBitVector global_in = use_in[bb->getId()];
    SparseBitVector global_out = def_out[bb->getId()];
    global_in &= def_in[bb->getId()];
    global_use_in |= global_in;
    global_out &= use_out[bb->getId()];
    global_def_out |= global_out;
  }

  int global_var_num = 0;
  for (auto var : vars) {
    if (var->isRegAllocPartaker()) {
      if (global_use_in.test(var->getId()) ||
          global_def_out.test(var->getId())) {
        global_var_num++;
      }
    }
  }
  std::cerr << "total var num: " << numVarId
            << " global var num: " << global_var_num << "\n";
}

void LivenessAnalysis::reportUndefinedUses() const {
  auto dumpVar = [](G4_RegVar *var) {
    int size =
        var->getDeclare()->getTotalElems() * var->getDeclare()->getElemSize();
    std::cerr << var->getName() << "(" << size << "), ";
  };

  std::cerr << "\nPossible undefined uses in kernel "
            << fg.getKernel()->getName() << ":\n";
  unsigned count = 0;
  for (auto var : vars) {
    // Skip if the var is not involved in RA.
    if (!var->isRegAllocPartaker())
      continue;
    // Skip if the var is a AddrSpillLoc.
    if (var->isRegVarAddrSpillLoc())
      continue;
    // Skip if the var is not in use_in of BB0
    if (!isUseIn(fg.getEntryBB(), var->getId()))
      continue;
    // Skip if the var is in def_in of BB0
    if (def_in[fg.getEntryBB()->getId()].test(var->getId()))
      continue;

    if (count++ % 10 == 0)
      std::cerr << "\n";
    dumpVar(var);
  }
  std::cerr << "\n";
}

bool LivenessAnalysis::isEmptyLiveness() const { return numBBId == 0; }

SparseBitVector LivenessAnalysis::getLiveAtEntry(const G4_BB* bb) const {
  return use_in[bb->getId()] & def_in[bb->getId()];
}

SparseBitVector LivenessAnalysis::getLiveAtExit(const G4_BB *bb) const {
  return use_out[bb->getId()] & def_out[bb->getId()];
}
//
// return true if var is live at the entry of bb
// check both use_in and def_in, if one condition fails then var is not in the
// live range
//
bool LivenessAnalysis::isLiveAtEntry(const G4_BB *bb, unsigned var_id) const {
  return use_in[bb->getId()].test(var_id) && def_in[bb->getId()].test(var_id);
}
//
// return true if var is live at the exit of bb
//
bool LivenessAnalysis::isLiveAtExit(const G4_BB *bb, unsigned var_id) const {
  return use_out[bb->getId()].test(var_id) &&
         def_out[bb->getId()].test(var_id);
}

//
// return true if var is user through the bb
//
bool LivenessAnalysis::isUseOut(const G4_BB *bb, unsigned var_id) const {
  return use_out[bb->getId()].test(var_id);
}

//
// return true if var is user through the bb
//
bool LivenessAnalysis::isUseIn(const G4_BB *bb, unsigned var_id) const {
  return use_in[bb->getId()].test(var_id);
}

//
// return true if var is user through the bb
//
bool LivenessAnalysis::isUseThrough(const G4_BB *bb, unsigned var_id) const {
  return use_in[bb->getId()].test(var_id) &&
         use_out[bb->getId()].test(var_id);
}
//
// return true if var is live at the exit of bb
//
bool LivenessAnalysis::isDefThrough(const G4_BB *bb, unsigned var_id) const {
  return def_in[bb->getId()].test(var_id) &&
         def_out[bb->getId()].test(var_id);
}

void GlobalRA::markBlockLocalVar(G4_RegVar *var, unsigned bbId) {
  G4_Declare *dcl = var->getDeclare()->getRootDeclare();

  if (dcl->isInput() || dcl->isOutput()) {
    setBBId(dcl, UINT_MAX - 1);
  } else {
    if (getBBId(dcl) == bbId) {
      // Do nothing.
    } else if (getBBId(dcl) == UINT_MAX) {
      setBBId(dcl, bbId);
    } else {
      setBBId(dcl, UINT_MAX - 1);
    }
  }
}

void GlobalRA::markBlockLocalVars() {
  for (auto bb : kernel.fg) {
    for (std::list<G4_INST *>::iterator it = bb->begin(); it != bb->end();
         it++) {
      G4_INST *inst = *it;

      // Chjeck if there is undefine variable used in CMP instruction, which is
      // used to detect the execution mask.
      //     cmp.eq (M1, 16) P12 V0147(0,0)<0;1,0> V0147(0,0)<0;1,0>
      if (inst->opcode() == G4_cmp) {
        const bool isModEq =
            inst->getCondMod() && inst->getCondMod()->getMod() == Mod_e;
        const bool isNullDst = !inst->getDst() || inst->hasNULLDst();
        const bool isSrc0SameAsSrc1 = inst->getSrc(0)->asSrcRegRegion() &&
                                      inst->getSrc(1)->asSrcRegRegion() &&
                                      *inst->getSrc(0)->asSrcRegRegion() ==
                                          *inst->getSrc(1)->asSrcRegRegion();
        if (isModEq && isNullDst && isSrc0SameAsSrc1) {
          G4_Declare *topdcl = GetTopDclFromRegRegion(inst->getSrc(0));
          if (topdcl && topdcl->getRegFile() == G4_GRF) {
            addUndefinedCmpDcl(topdcl);
          }
        }
      }

      // Track direct dst references.

      G4_DstRegRegion *dst = inst->getDst();

      if (dst != NULL) {
        G4_DstRegRegion *dstRgn = dst->asDstRegRegion();

        if (dstRgn->getBase()->isRegVar()) {
          markBlockLocalVar(dstRgn->getBase()->asRegVar(), bb->getId());

          G4_Declare *topdcl = GetTopDclFromRegRegion(dst);
          if (topdcl) {
            if (inst->isSend()) {
              topdcl->setIsRefInSendDcl(true);
            }

            LocalLiveRange *lr = GetOrCreateLocalLiveRange(topdcl);
            unsigned int startIdx;
            if (lr->getFirstRef(startIdx) == NULL) {
              lr->setFirstRef(inst, 0);
            }
            lr->recordRef(bb);
            lr->markDefined();
            recordRef(topdcl);
          }
        }
      }

      G4_CondMod *condMod = inst->getCondMod();

      if (condMod != NULL && condMod->getBase() != NULL) {
        if (condMod->getBase() && condMod->getBase()->isRegVar()) {
          markBlockLocalVar(condMod->getBase()->asRegVar(), bb->getId());

          G4_Declare *topdcl = condMod->getBase()->asRegVar()->getDeclare();
          if (topdcl) {
            LocalLiveRange *lr = GetOrCreateLocalLiveRange(topdcl);
            unsigned int startIdx;
            if (lr->getFirstRef(startIdx) == NULL) {
              lr->setFirstRef(inst, 0);
            }
            lr->recordRef(bb);
            recordRef(topdcl);
          }
        }
      }

      // Track direct src references.
      for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
        G4_Operand *src = inst->getSrc(j);

        if (src == NULL) {
          // Do nothing.
        } else if (src->isSrcRegRegion() &&
                   src->asSrcRegRegion()->getBase()->isRegVar()) {
          G4_SrcRegRegion *srcRgn = src->asSrcRegRegion();

          if (srcRgn->getBase()->isRegVar()) {
            markBlockLocalVar(src->asSrcRegRegion()->getBase()->asRegVar(),
                              bb->getId());

            G4_Declare *topdcl = GetTopDclFromRegRegion(src);
            if (topdcl) {
              if (inst->isSend()) {
                topdcl->setIsRefInSendDcl(true);
              }

              LocalLiveRange *lr = GetOrCreateLocalLiveRange(topdcl);

              lr->recordRef(bb);
              recordRef(topdcl);
              if (inst->isEOT()) {
                lr->markEOT();
              }
            }
          }
        } else if (src->isAddrExp()) {
          G4_RegVar *addExpVar = src->asAddrExp()->getRegVar();
          markBlockLocalVar(addExpVar, bb->getId());

          G4_Declare *topdcl = addExpVar->getDeclare()->getRootDeclare();
          vISA_ASSERT(topdcl != NULL, "Top dcl was null for addr exp opnd");

          LocalLiveRange *lr = GetOrCreateLocalLiveRange(topdcl);
          lr->recordRef(bb);
          lr->markIndirectRef();
          recordRef(topdcl);
        }
      }

      G4_Operand *pred = inst->getPredicate();

      if (pred != NULL) {
        if (pred->getBase() && pred->getBase()->isRegVar()) {
          markBlockLocalVar(pred->getBase()->asRegVar(), bb->getId());
          G4_Declare *topdcl = pred->getBase()->asRegVar()->getDeclare();
          if (topdcl) {
            LocalLiveRange *lr = GetOrCreateLocalLiveRange(topdcl);
            lr->recordRef(bb);
            recordRef(topdcl);
          }
        }
      }

      // Track all indirect references.
      const REGVAR_VECTOR &grfVec =
          pointsToAnalysis.getIndrUseVectorForBB(bb->getId());
      for (pointInfo grf : grfVec) {
        markBlockLocalVar(grf.var, bb->getId());
      }
    }
  }
}

void GlobalRA::resetGlobalRAStates() {
  auto origDclSize = kernel.Declares.size();
  if (builder.getOption(vISA_LocalDeclareSplitInGlobalRA)) {
    incRA.resetPartialDcls();
    // remove partial decls
    auto isPartialDcl = [](G4_Declare *dcl) { return dcl->getIsPartialDcl(); };

    kernel.Declares.erase(std::remove_if(kernel.Declares.begin(),
                                         kernel.Declares.end(), isPartialDcl),
                          kernel.Declares.end());
  }

  incRA.reduceMaxDclId(origDclSize - kernel.Declares.size());

  for (auto dcl : kernel.Declares) {
    // Reset all the local live ranges
    resetLocalLR(dcl);

    if (builder.getOption(vISA_LocalDeclareSplitInGlobalRA)) {
      // Remove the split declares
      if (dcl->getIsSplittedDcl()) {
        dcl->setIsSplittedDcl(false);
        clearSubDcl(dcl);
        incRA.markForIntfUpdate(dcl);
      }
    }

    // Remove the bank assignment
    if (builder.getOption(vISA_LocalBankConflictReduction) &&
        builder.hasBankCollision()) {
      setBankConflict(dcl, BANK_CONFLICT_NONE);
    }
    clearBundleConflictDcl(dcl);
  }

  return;
}

// We emit FDE so that:
// 1. Debug information can easily point to previous frame state,
// 2. We can restore caller frame state before returning.
//
// -skipFDE option skips emission of store in stack call function prolog.
// As an optimization, it's okay to skip this store when the function is a
// leaf function. If it's not a leaf function then we emit the store,
// irrespective of -skipFDE. When the switch is not specified (default)
// we emit the store even for leaf functions (in case debugger connects).
bool GlobalRA::canSkipFDE() const {
  return !kernel.fg.getHasStackCalls() && kernel.getOption(vISA_skipFDE);
}

void GlobalRA::setUndefinedVarCmp() {
  // Iterate over all dcls and remove those with 0
  // ref count and not addressed. This is done only for
  // GRF dcls.

  // Propagate top dcl info to aliases
  for (auto dcl : UndefinedCmpVars) {
    LocalLiveRange *lr = getLocalLR(dcl);
    if (!lr->isDefined()) {
      dcl->setIsCmpUseOnly(true);
    }
  }
}

//
// Mark block local (temporary) variables.
//
void GlobalRA::markGraphBlockLocalVars() {
  // Clear stale LocalLiveRange* first to avoid double ref counting
  clearStaleLiveRanges();

  // Create live ranges and record the reference info
  markBlockLocalVars();

  // Set undefined variable used in cmp
  setUndefinedVarCmp();

  VISA_DEBUG_VERBOSE({
    std::cout << "\t--LOCAL VARIABLES--\n";
    for (auto dcl : kernel.Declares) {
      LocalLiveRange *topdclLR = getLocalLR(dcl);

      if (topdclLR && topdclLR->isLiveRangeLocal()) {
        std::cout << dcl->getName() << ",\t";
      }
    }
    std::cout << "\n";
  });
}

unsigned int IR_Builder::getCallRetOpndSize() const {
  unsigned int numElems = 2;
  return numElems;
}

//
// Pre-assign phy regs to stack call function return variable as per ABI.
//
void FlowGraph::setABIForStackCallFunctionCalls() {
  // For each G4_pseudo_fcall inst, create dst of GRF type
  // with physical register 1.0 pre-assigned to it.
  // Similarly, for G4_pseudo_fret create src of GRF type
  // with physical register 1.0 pre-assigned to it.
  // Each will use 2 dwords of r1.0.
  int call_id = 0, ret_id = 0;

  for (auto bb : *this) {
    if (bb->isEndWithFCall()) {
      const char *n = builder->getNameString(25, "FCALL_RET_LOC_%d", call_id++);

      G4_INST *fcall = bb->back();
      // Set call dst to fpspGRF
      G4_Declare *r1_dst = builder->createDeclare(
          n, G4_GRF, builder->getCallRetOpndSize(), 1, Type_UD);
      r1_dst->getRegVar()->setPhyReg(
          builder->phyregpool.getGreg(builder->kernel.stackCall.getFPSPGRF()),
          builder->kernel.stackCall.subRegs.Ret_IP);
      G4_DstRegRegion *dstRgn =
          builder->createDst(r1_dst->getRegVar(), 0, 0, 1, Type_UD);
      fcall->setDest(dstRgn);
    }

    if (bb->isEndWithFRet()) {
      const char *n = builder->getNameString(25, "FRET_RET_LOC_%d", ret_id++);
      G4_INST *fret = bb->back();
      const RegionDesc *rd = builder->createRegionDesc(2, 2, 1);
      G4_Declare *r1_src = builder->createDeclare(
          n, G4_INPUT, builder->getCallRetOpndSize(), 1, Type_UD);
      r1_src->getRegVar()->setPhyReg(
          builder->phyregpool.getGreg(builder->kernel.stackCall.getFPSPGRF()),
          builder->kernel.stackCall.subRegs.Ret_IP);
      G4_Operand *srcRgn =
          builder->createSrc(r1_src->getRegVar(), 0, 0, rd, Type_UD);
      fret->setSrc(srcRgn, 0);
      if (fret->getExecSize() == g4::SIMD1) {
        // due to <2;2,1> regioning we must update exec size as well
        fret->setExecSize(g4::SIMD2);
      }
      if (builder->getOption(vISA_GenerateDebugInfo)) {
        pKernel->getKernelDebugInfo()->setFretVar(
            GetTopDclFromRegRegion(fret->getSrc(0)));
      }
    }
  }
}

// Function to verify RA results
void GlobalRA::verifyRA(LivenessAnalysis &liveAnalysis) {
  for (auto bb : kernel.fg) {
    unsigned int numGRF = kernel.getNumRegTotal();

    // Verify PREG assignment
    for (auto inst : *bb) {
      G4_DstRegRegion *dst = inst->getDst();
      if (dst != nullptr && dst->getBase()->isRegAllocPartaker()) {
        vISA_ASSERT(dst->getBase()->asRegVar()->getPhyReg(),
                    "RA verification error: No PREG assigned for variable %s",
                    GetTopDclFromRegRegion(dst)->getName());
      }

      for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
        G4_Operand *src = inst->getSrc(j);
        if (src && src->isSrcRegRegion() &&
            src->asSrcRegRegion()->getBase()->isRegAllocPartaker()) {
          vISA_ASSERT(src->asSrcRegRegion()->getBase()->asRegVar()->getPhyReg(),
                      "RA verification error: No PREG assigned for variable %s",
                      GetTopDclFromRegRegion(src->asSrcRegRegion())->getName());
        }
      }

      if (inst->isSend()) {
        if (dst && dst->getBase()->isRegAllocPartaker()) {
          auto preg = dst->getBase()->asRegVar()->getPhyReg();
          if (preg && preg->isGreg()) {
            vISA_ASSERT(numGRF >=
                            (preg->asGreg()->getRegNum() +
                             inst->asSendInst()->getMsgDesc()->getDstLenRegs()),
                        "dst response length goes beyond last GRF");
          }
        }

        for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
          G4_Operand *src = inst->getSrc(j);
          if (src && src->isSrcRegRegion() &&
              src->getBase()->isRegAllocPartaker()) {
            auto preg = src->getBase()->asRegVar()->getPhyReg();
            if (preg && preg->isGreg()) {
              [[maybe_unused]] unsigned int srcLen = 0;
              if (j == 0)
                srcLen = inst->asSendInst()->getMsgDesc()->getSrc0LenRegs();
              else if (j == 1)
                srcLen = inst->asSendInst()->getMsgDesc()->getSrc1LenRegs();

              vISA_ASSERT(numGRF >= (preg->asGreg()->getRegNum() + srcLen),
                          "src payload length goes beyond last GRF");
            }
          }
        }
      }
    }

    // Verify Live-in
    std::map<uint32_t, G4_Declare *> LiveInRegMap;
    std::map<uint32_t, G4_Declare *>::iterator LiveInRegMapIt;
    std::vector<uint32_t> liveInRegVec(numGRF * kernel.numEltPerGRF<Type_UW>(),
                                       UINT_MAX);

    for (G4_Declare *dcl : kernel.Declares) {
      if (dcl->getAliasDeclare() != nullptr)
        continue;

      if (dcl->getRegVar()->isRegAllocPartaker()) {
        G4_RegVar *var = dcl->getRegVar();
        uint32_t varID = var->getId();
        if (liveAnalysis.isLiveAtEntry(bb, dcl->getRegVar()->getId())) {
          // Skip live-in that has no physical reg assigned.
          // Currently there might be some cases of a variable not
          // actually used but marked as live-in and live-out. For
          // example, spillHeader var is created for save/restore
          // spill/fill code in stack call case, and is not used when
          // expanding spill/fill using LSC.
          if (!var->isPhyRegAssigned())
            continue;

          vISA_ASSERT(
              var->getPhyReg()->isGreg(),
              "RA verification error: Invalid preg assignment for variable %s",
              dcl->getName());

          uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
          uint32_t regOff = var->getPhyRegOff();

          uint32_t idx = regNum * kernel.numEltPerGRF<Type_UW>() +
                         (regOff * dcl->getElemSize()) / G4_WSIZE;
          for (uint32_t i = 0; i < dcl->getWordSize(); ++i, ++idx) {
            LiveInRegMapIt = LiveInRegMap.find(idx);
            if (liveInRegVec[idx] != UINT_MAX) {
              vISA_ASSERT(
                  LiveInRegMapIt != LiveInRegMap.end(),
                  "RA verification error: Invalid entry in LiveInRegMap!");
              if (dcl->isInput()) {
                vISA_ASSERT(false,
                            "RA verification warning: Found  conflicting input "
                            "variables: %s and %s assigned to r%d.%d",
                            dcl->getName(), (*LiveInRegMapIt).second->getName(),
                            regNum, regOff);
                liveInRegVec[idx] = varID;
                LiveInRegMapIt->second = dcl;
              } else {
                // There's case that the 2 vars in outer scope are just live
                // through the subroutine, but IPA would mark 2 vars are live in
                // the subroutine. So, here we report error only if either var
                // has the same scope id as the current BB. If any var is used
                // in the subroutine, we can still catch the conflict when
                // verifying instructions later.
                //
                //     foo() {
                //         a = ...;
                //         bar();
                //         ... = a;
                //
                //         b = ...;
                //         bar();
                //         ... = b;
                //     }
                //     bar() {
                //         ...
                //     }
                vISA_ASSERT(bb->getScopeID() != dcl->getScopeID() &&
                                bb->getScopeID() !=
                                    LiveInRegMapIt->second->getScopeID(),
                            "RA verification error: Found conflicting live-in "
                            "variables: %s and %s assigned to r%d.%d",
                            dcl->getName(), LiveInRegMapIt->second->getName(),
                            regNum, regOff);
              }

            } else {
              liveInRegVec[idx] = varID;
              vISA_ASSERT(
                  LiveInRegMapIt == LiveInRegMap.end(),
                  "RA verification error: Invalid entry in LiveInRegMap!");
              LiveInRegMap.emplace(idx, dcl);
            }
          }
        }
      }
    }

    // Verify Live-out
    G4_Declare *ret = kernel.fg.builder->getStackCallRet();
    std::map<uint32_t, G4_Declare *> liveOutRegMap;
    std::map<uint32_t, G4_Declare *>::iterator liveOutRegMapIt;
    std::vector<uint32_t> liveOutRegVec(numGRF * kernel.numEltPerGRF<Type_UW>(),
                                        UINT_MAX);

    for (G4_Declare *dcl : kernel.Declares) {
      if (dcl->getAliasDeclare() != nullptr)
        continue;
      if (dcl->getRegVar()->isRegAllocPartaker()) {
        G4_RegVar *var = dcl->getRegVar();
        uint32_t varID = var->getId();
        if (liveAnalysis.isLiveAtExit(bb, varID)) {
          // Skip live-out w/o physical reg assigned as well.
          if (!var->isPhyRegAssigned())
            continue;

          vISA_ASSERT(
              var->getPhyReg()->isGreg(),
              "RA verification error: Invalid preg assignment for variable %s",
              dcl->getName());

          uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
          uint32_t regOff = var->getPhyRegOff();

          uint32_t idx = regNum * kernel.numEltPerGRF<Type_UW>() +
                         (regOff * dcl->getElemSize()) / G4_WSIZE;
          for (uint32_t i = 0; i < dcl->getWordSize(); ++i, ++idx) {
            liveOutRegMapIt = liveOutRegMap.find(idx);
            if (liveOutRegVec[idx] != UINT_MAX) {
              vISA_ASSERT(
                  liveOutRegMapIt != liveOutRegMap.end(),
                  "RA verification error: Invalid entry in liveOutRegMap!");
              if (dcl->isInput()) {
                vISA_ASSERT(false,
                            "RA verification error: Found conflicting input "
                            "variables %s and %s assigned to r%d.%d",
                            dcl->getName(), liveOutRegMapIt->second->getName(),
                            regNum, regOff);
                liveOutRegVec[idx] = varID;
                liveOutRegMapIt->second = dcl;
              } else {
                // Same as the case of live-in verification. Also report error
                // only if either var has the same scope id as the current BB.

                vISA_ASSERT(bb->getScopeID() != dcl->getScopeID() &&
                                bb->getScopeID() !=
                                    liveOutRegMapIt->second->getScopeID(),
                            "RA verification error: Found conflicting live out "
                            "variables: %s and %s assigned to r %d.%d",
                            dcl->getName(), liveOutRegMapIt->second->getName(),
                            regNum, regOff);
              }

            } else {
              liveOutRegVec[idx] = varID;
              vISA_ASSERT(
                  liveOutRegMapIt == liveOutRegMap.end(),
                  "RA verification error: Invalid entry in liveOutRegMap!");
              liveOutRegMap.emplace(idx, dcl);
            }
          }
        }
      }
    }

    std::set<G4_Declare *>
        spillFillVariableOverwriteSet; // the collection is used to check if
                                       // variables generated by spill/fill have
                                       // been overwrite
    for (INST_LIST::reverse_iterator rit = bb->rbegin(); rit != bb->rend();
         ++rit) {
      G4_INST *inst = (*rit);
      // Skip the special case that is used to get the execution mask.
      //
      //     cmp.eq (M1, 16) P12 V0147(0,0)<0;1,0> V0147(0,0)<0;1,0>
      //     cmp.eq (M5, 16) P12 V0147(0,0)<0;1,0> V0147(0,0)<0;1,0>
      //
      // FIXME: In the case, src0 and src1 are same and can be any
      // register. In addition, the var might not be defined by vISA user
      // resulting in imprecise liveness result. Some possible fix could
      // be using the pre-defined var like R0, but it's not clear if the
      // R0's live range would be affected a lot.
      if (inst->opcode() == G4_cmp) {
        const bool isModEq =
            inst->getCondMod() && inst->getCondMod()->getMod() == Mod_e;
        const bool isNullDst = !inst->getDst() || inst->hasNULLDst();
        const bool isSrc0SameAsSrc1 = inst->getSrc(0)->asSrcRegRegion() &&
                                      inst->getSrc(1)->asSrcRegRegion() &&
                                      *inst->getSrc(0)->asSrcRegRegion() ==
                                          *inst->getSrc(1)->asSrcRegRegion();
        if (isModEq && isNullDst && isSrc0SameAsSrc1)
          continue;
      }
      INST_LIST_RITER ritNext = rit;
      ritNext++;
      G4_INST *rNInst = nullptr;
      if (ritNext != bb->rend()) {
        rNInst = (*ritNext);
      }

      G4_DstRegRegion *dst = inst->getDst();
      G4_DstRegRegion *rNDst = nullptr;
      G4_Declare *rNDcl = nullptr;
      if (rNInst && rNInst->isPseudoKill()) {
        rNDst = rNInst->getDst();
        if (rNDst != nullptr) {
          rNDcl = GetTopDclFromRegRegion(rNDst);
        }
      }

      // verify dst operand
      if (dst != nullptr) {
        uint32_t varID = UINT_MAX;
        G4_Declare *dcl = nullptr;

        auto verifyDstRA = [&](uint32_t idx, uint32_t regNum, uint32_t regOff,
                               bool &suppressWarning) {
          vISA_ASSERT(dcl && dcl->getRegVar() &&
                          dcl->getRegVar()->isPhyRegAssigned(),
                      "RA verification error: Found dst variable without "
                      "physical register.");
          liveOutRegMapIt = liveOutRegMap.find(idx);
          if (liveOutRegVec[idx] == UINT_MAX) {
            vISA_ASSERT(
                liveOutRegMapIt == liveOutRegMap.end(),
                "RA verification error: Invalid entry in liveOutRegMap!");

            // Since we treat variables generated by spill/fill as whole region,
            // here need special handling for fill->modify->spill case that is
            // to skip dst check if it has been written. Take below case as
            // example, we should skip the dst(r13-r14) check of the fill
            // instruction since it has been written in mov instruction and has
            // been removed from liveOutRegMap.
            //
            // clang-format off
            // (W) send(16)    r13.0<1>:ud r25 0xA 0x22c1019:ud // $236:; scratch read, resLen=2, msgLen=1
            //     mov(8)      r13.1 < 2 > :d  r10.1 < 2; 1, 0 > : d // $236:&400:
            // (W) sends(16)   null : ud r25 r13 0x8a : ud 0x20f1019 : ud // $236:; scratch write, resLen=2, msgLen=1, extMsgLen=2
            // clang-format on
            if (!suppressWarning && !inst->isPseudoKill() &&
                !(dcl == rNDcl && rNInst->isPseudoKill()) &&
                spillFillVariableOverwriteSet.find(dcl) ==
                    spillFillVariableOverwriteSet.end()) {
              // This warning is possible as some variables are defined without
              // usage. TV5 is the example:
              // clang-format off
              // before RA:
              //     (W) send(8)  TV5(0,0)<1>:ud R0_Copy0(0,0) 0xA 0x219e0fe:ud // $130:&217:; memory fence, resLen=1, msgLen=1
              //     (W) and(8)   M7(0,0)<1>:ud  R0_Copy0(0,2)<0;1,0>:ud  0x7f000000:ud // $131:&218:
              // after RA:
              //     (W) send(8)  r2.0<1>:ud r10 0xA 0x219e0fe:ud // $130:&217:; memory fence, resLen=1, msgLen=1
              //     (W) and(8)   r2.0<1>:ud r10.2<0;1,0>:ud  0x7f000000 : ud // $131:&218:
              // clang-format on
              VISA_DEBUG(std::cout
                         << "RA verification warning: Found unused variable "
                         << dcl->getName() << ". Please double check!\n");
              suppressWarning = true;
            }
          } else {
            vISA_ASSERT(
                liveOutRegMapIt != liveOutRegMap.end(),
                "RA verification error: Invalid entry in liveOutRegMap!");
            if (liveOutRegVec[idx] != varID) {
              const SparseBitVector &indr_use = liveAnalysis.indr_use[bb->getId()];

              if (strstr(dcl->getName(), GlobalRA::StackCallStr) != nullptr) {
                vISA_ASSERT(false,
                            "RA verification error: Found conflicting "
                            "stackCall variable: %s and %s assigned to r%d.%d",
                            dcl->getName(), liveOutRegMapIt->second->getName(),
                            regNum, regOff);
              } else if (indr_use.test(liveOutRegVec[idx]) == true) {
                vISA_ASSERT(false,
                            "RA verification error: Found conflicting indirect "
                            "variables %s and %s assigned to r%d.%d",
                            dcl->getName(), liveOutRegMapIt->second->getName(),
                            regNum, regOff);
              } else {
                if (!inst->isPseudoKill()) {
                  vISA_ASSERT(false,
                              "RA verification error: Found conflicting "
                              "variables: %s and %s assigned to r%d.%d",
                              dcl->getName(),
                              liveOutRegMapIt->second->getName(), regNum,
                              regOff);
                }
              }
            } else {
              liveOutRegVec[idx] = UINT_MAX;
              liveOutRegMap.erase(liveOutRegMapIt);
            }
          }
        };

        if (dst->getBase()->isRegAllocPartaker()) {
          G4_DstRegRegion *dstrgn = dst;
          G4_RegVar *var = dstrgn->getBase()->asRegVar();
          varID = var->getId();
          dcl = GetTopDclFromRegRegion(dstrgn);
          vISA_ASSERT(dcl != nullptr, "Null declare found");
          var = dcl->getRegVar();

          vISA_ASSERT(var->getId() == varID,
                      "RA verification error: Invalid regVar ID!");
          vISA_ASSERT(var->getPhyReg()->isGreg(),
                      "RA verification error: Invalid dst reg!");

          uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
          uint32_t regOff = var->getPhyRegOff();
          bool suppressWarning =
              false; // used to suppress warning per word since each operand
                     // crosses multiple words

          // For spill/fill variable, should check whole region size
          if (var->isRegVarTransient()) {
            uint32_t idx = regNum * kernel.numEltPerGRF<Type_UW>() +
                           (regOff * dcl->getElemSize()) / G4_WSIZE;

            for (uint32_t i = 0; i < dcl->getWordSize(); ++i, ++idx) {
              verifyDstRA(idx, regNum, regOff, suppressWarning);
            }

            if (spillFillVariableOverwriteSet.find(dcl) ==
                spillFillVariableOverwriteSet.end()) {
              spillFillVariableOverwriteSet.insert(dcl);
            }
          }
          // For non spill/fill variables, should check operand size
          else {
            auto dstLB = dst->getLinearizedStart();
            auto dstRB = dst->getLinearizedEnd();

            for (unsigned int dstOffset = dstLB; dstOffset <= dstRB;
                 dstOffset += G4_WSIZE) {
              uint32_t idx = dstOffset / G4_WSIZE;
              verifyDstRA(idx, regNum, regOff, suppressWarning);
            }
          }
        } else if (dst->getRegAccess() == IndirGRF) {
          G4_DstRegRegion *dstrgn = dst;
          G4_Declare *addrdcl = GetTopDclFromRegRegion(dstrgn);
          G4_RegVar *ptvar = nullptr;
          int vid = 0;

          while ((ptvar = pointsToAnalysis.getPointsTo(addrdcl->getRegVar(),
                                                       vid++)) != nullptr) {
            varID = ptvar->getId();
            dcl = ptvar->getDeclare();
            vISA_ASSERT(dcl != nullptr, "Null declare found");
            while (dcl->getAliasDeclare()) {
              dcl = dcl->getAliasDeclare();
            }
            G4_RegVar *var = dcl->getRegVar();

            vISA_ASSERT(var->getId() == varID,
                        "RA verification error: Invalid regVar ID!");
            vISA_ASSERT(var->getPhyReg()->isGreg(),
                        "RA verification error: Invalid dst reg!");

            uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
            uint32_t regOff = var->getPhyRegOff();
            auto dstLB = regNum * kernel.numEltPerGRF<Type_UB>() +
                         regOff * TypeSize(dcl->getElemType());
            auto dstRB = dstLB + dcl->getByteSize() - 1;
            uint32_t idx = dstLB / G4_WSIZE;

            bool suppressWarning = false;
            for (unsigned int dstOffset = dstLB; dstOffset <= dstRB;
                 dstOffset += std::max((unsigned int)dst->getExecTypeSize(),
                                       (unsigned int)G4_WSIZE)) {
              for (unsigned int elementOffset = 0;
                   elementOffset < dst->getElemSize();
                   elementOffset += G4_WSIZE) {
                idx = (dstOffset + elementOffset) / G4_WSIZE;

                verifyDstRA(idx, regNum, regOff, suppressWarning);
              }
            }
          }
        }
      }

      if (inst->opcode() == G4_pseudo_fcall) {
        if (ret != nullptr && ret->getRegVar() != nullptr) {
          G4_RegVar *var = ret->getRegVar();
          [[maybe_unused]] uint32_t varID = var->getId();
          vISA_ASSERT(var->getId() == varID,
                      "RA verification error: Invalid regVar ID!");
          vISA_ASSERT(var->getPhyReg()->isGreg(),
                      "RA verification error: Invalid dst reg!");

          uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
          uint32_t regOff = var->getPhyRegOff();

          uint32_t idx = regNum * kernel.numEltPerGRF<Type_UW>() +
                         regOff * ret->getElemSize() / G4_WSIZE;
          for (uint32_t i = 0; i < ret->getWordSize(); ++i, ++idx) {
            liveOutRegMapIt = liveOutRegMap.find(idx);
            liveOutRegVec[idx] = UINT_MAX;
            vISA_ASSERT(
                liveOutRegMapIt != liveOutRegMap.end(),
                "RA verification error: Invalid entry in liveOutRegMap!");
            liveOutRegMap.erase(liveOutRegMapIt);
          }
        }
      }

      // verify each source operand
      for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
        G4_Operand *src = inst->getSrc(j);
        if (!src)
          continue;

        uint32_t varID = UINT_MAX;
        G4_Declare *dcl = nullptr;
        auto verifySrcRA = [&](uint32_t idx, uint32_t regNum, uint32_t regOff) {
          vISA_ASSERT(dcl && dcl->getRegVar() &&
                          dcl->getRegVar()->isPhyRegAssigned(),
                      "RA verification error: Found src variable without "
                      "physical register.");
          liveOutRegMapIt = liveOutRegMap.find(idx);
          if (liveOutRegVec[idx] == UINT_MAX) {
            liveOutRegVec[idx] = varID;
            vISA_ASSERT(
                liveOutRegMapIt == liveOutRegMap.end(),
                "RA verification error: Invalid entry in liveOutRegMap!");
            liveOutRegMap.emplace(idx, dcl);
          } else {
            if (liveOutRegVec[idx] != varID) {
              const SparseBitVector &indr_use = liveAnalysis.indr_use[bb->getId()];

              if (dcl->isInput()) {
                vISA_ASSERT(false,
                            "RA verification error: Found conflicting input "
                            "variables: %s and %s assigned to r%d.%d",
                            dcl->getName(), liveOutRegMapIt->second->getName(),
                            regNum, regOff);
                liveOutRegVec[idx] = varID;
                liveOutRegMapIt->second = dcl;
              } else if (strstr(dcl->getName(), GlobalRA::StackCallStr) !=
                         nullptr) {
                vISA_ASSERT(false,
                            "RA verification error: Found conflicting "
                            "stackCall variables: %s and %s assigned to r%d.%d",
                            dcl->getName(), liveOutRegMapIt->second->getName(),
                            regNum, regOff);
              } else if (indr_use.test(liveOutRegVec[idx]) == true) {
                vISA_ASSERT(false,
                            "RA verification error: Found conflicting indirect "
                            "variables: %s and %s assigned to r %d.%d",
                            dcl->getName(), liveOutRegMapIt->second->getName(),
                            regNum, regOff);
              } else {
                INST_LIST::reverse_iterator succ = rit;
                ++succ;
                bool idMismatch = false;
                G4_Declare *topdcl = GetTopDclFromRegRegion((*succ)->getDst());
                if (topdcl != nullptr &&
                    liveOutRegVec[idx] != topdcl->getRegVar()->getId()) {
                  idMismatch = true;
                }
                if (succ == bb->rbegin() || !(*succ)->isPseudoKill() ||
                    (*succ)->getDst() == nullptr || idMismatch) {
                  vISA_ASSERT(
                      false, "RA verification error: Found conflicting \
                      variables: %s and %s assigned to r%d.%d",
                      dcl->getName(), liveOutRegMapIt->second->getName(),
                      regNum, regOff);
                }
              }
            }
          }
        };

        if (src->isSrcRegRegion() &&
            src->asSrcRegRegion()->getBase()->isRegAllocPartaker()) {
          G4_SrcRegRegion *srcrgn = src->asSrcRegRegion();
          G4_RegVar *var = srcrgn->getBase()->asRegVar();
          varID = var->getId();
          dcl = GetTopDclFromRegRegion(srcrgn);
          var = dcl->getRegVar();
          vISA_ASSERT(var->getId() == varID,
                      "RA verification error: Invalid regVar ID!");
          vISA_ASSERT(var->getPhyReg()->isGreg(),
                      "RA verification error: Invalid dst reg!");

          if (!inst->isLifeTimeEnd()) {
            uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
            uint32_t regOff = var->getPhyRegOff();

            // For spill/fill variable, should check whole region size
            if (var->isRegVarTransient()) {
              uint32_t idx = regNum * kernel.numEltPerGRF<Type_UW>() +
                             (regOff * dcl->getElemSize()) / G4_WSIZE;
              for (uint32_t i = 0; i < dcl->getWordSize(); ++i, ++idx) {
                verifySrcRA(idx, regNum, regOff);
              }
            }
            // For non spill/fill variables, should check operand size
            else {
              auto srcLB = src->getLinearizedStart();
              auto srcRB = src->getLinearizedEnd();
              for (unsigned int srcOffset = srcLB; srcOffset <= srcRB;
                   srcOffset += G4_WSIZE) {
                unsigned idx = srcOffset / G4_WSIZE;
                verifySrcRA(idx, regNum, regOff);
              }
            }
          } else {
            uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
            uint32_t regOff = var->getPhyRegOff();

            uint32_t idx = regNum * kernel.numEltPerGRF<Type_UW>() +
                           (regOff * dcl->getElemSize()) / G4_WSIZE;
            for (uint32_t i = 0; i < dcl->getWordSize(); ++i, ++idx) {
              if (liveOutRegVec[idx] != UINT_MAX) {
                liveOutRegMapIt = liveOutRegMap.find(idx);
                vISA_ASSERT(
                    liveOutRegMapIt != liveOutRegMap.end(),
                    "RA verification error: Invalid entry in liveOutRegMap!");
                vISA_ASSERT(false,
                            "RA verification error: Found live variable: %s "
                            "after lifetime_end assigned to r %d.%d",
                            dcl->getName(), regNum, regOff);
              }
            }
          }

          // verify EOT source
          if (inst->isEOT() && kernel.fg.builder->hasEOTGRFBinding()) {
            [[maybe_unused]] uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
            vISA_ASSERT(
                regNum >= 112,
                "RA verification error: EOT source: %s is assigned to r.%d",
                dcl->getName(), regNum);
          }
        } else if (src->isSrcRegRegion() && src->isIndirect()) {
          G4_SrcRegRegion *srcrgn = src->asSrcRegRegion();
          G4_Declare *addrdcl = GetTopDclFromRegRegion(srcrgn);
          G4_RegVar *ptvar = nullptr;
          int vid = 0;

          while ((ptvar = pointsToAnalysis.getPointsTo(addrdcl->getRegVar(),
                                                       vid++)) != nullptr) {
            varID = ptvar->getId();
            dcl = ptvar->getDeclare()->getRootDeclare();
            G4_RegVar *var = dcl->getRegVar();

            uint32_t regNum = var->getPhyReg()->asGreg()->getRegNum();
            uint32_t regOff = var->getPhyRegOff();

            uint32_t idx = regNum * kernel.numEltPerGRF<Type_UW>() +
                           (regOff * dcl->getElemSize()) / G4_WSIZE;
            for (uint32_t i = 0; i < dcl->getWordSize(); ++i, ++idx) {
              liveOutRegMapIt = liveOutRegMap.find(idx);
              if (liveOutRegVec[idx] == UINT_MAX) {
                liveOutRegVec[idx] = varID;
                vISA_ASSERT(
                    liveOutRegMapIt == liveOutRegMap.end(),
                    "RA verification error: Invalid entry in liveOutRegMap!");
                liveOutRegMap.emplace(idx, dcl);
              } else {
                if (liveOutRegVec[idx] != varID) {
                  const SparseBitVector &indr_use =
                      liveAnalysis.indr_use[bb->getId()];

                  if (dcl->isInput()) {
                    vISA_ASSERT(false,
                                "RA verification error: Found conflicting "
                                "input variables: %s and %s assigned to r%d.%d",
                                dcl->getName(),
                                liveOutRegMapIt->second->getName(), regNum,
                                regOff);
                    liveOutRegVec[idx] = varID;
                    liveOutRegMapIt->second = dcl;
                  } else if (indr_use.test(liveOutRegVec[idx]) == true) {
                    vISA_ASSERT(
                        false,
                        "RA verification error: Found conflicting indirect "
                        "variables: %s and %s assigned to r%d.%d",
                        dcl->getName(), liveOutRegMapIt->second->getName(),
                        regNum, regOff);
                  } else {
                    vISA_ASSERT(
                        false,
                        "RA verification error: Found conflicting variables: "
                        "%s and %s assigned to r %d.%s and %s assigned to "
                        "r%d.%d",
                        dcl->getName(), liveOutRegMapIt->second->getName(),
                        regNum, dcl->getName(),
                        liveOutRegMapIt->second->getName(), regNum, regOff);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

void GlobalRA::verifySpillFill() {
  // Verify that whenever LSC or OW is used for spill in divergent CF, it is
  // preceeded by corresponding fill.
  for (auto *BB : kernel.fg.getBBList()) {
    auto InstIter = BB->begin();
    while (InstIter != BB->end()) {
      auto *Inst = (*InstIter);
      if (!Inst->isSpillIntrinsic()) {
        ++InstIter;
        continue;
      }

      bool UsesLSC =
          useLscForNonStackCallSpillFill || spillFillIntrinUsesLSC(Inst);
      bool UsesOW = (Inst->asSpillIntrinsic()->getOffset() ==
                     G4_SpillIntrinsic::InvalidOffset);
      bool UsesHW = !UsesLSC && !UsesOW;

      auto Offset = Inst->asSpillIntrinsic()->getOffset();
      auto Rows = Inst->asSpillIntrinsic()->getNumRows();

      auto CheckRMWFill = [&]() {
        // InstIter points to spill. Check for preceeding fill.
        bool FillFound = false;
        auto PrevInstIter = InstIter;
        --PrevInstIter;
        while (PrevInstIter != BB->begin()) {
          auto PrevInst = (*PrevInstIter);

          if (PrevInst->isFillIntrinsic()) {
            // If we see same Offset/Rows combination, we're safe
            auto OffsetPrev = PrevInst->asFillIntrinsic()->getOffset();
            auto RowsPrev = PrevInst->asFillIntrinsic()->getNumRows();

            if (OffsetPrev == Offset && RowsPrev == Rows) {
              FillFound = true;
              break;
            }
          }
          --PrevInstIter;
        }

        if (!FillFound) {
          std::cerr << "Didn't find RMW fill corresponding to spill at $"
                    << Inst->getVISAId() << std::endl;
          Inst->dump();
          std::cerr << std::endl;
        }
      };

      auto CheckWriteEnable = [&]() {
        if (!Inst->isWriteEnableInst()) {
          Inst->dump();
          std::cerr << "Expecting WriteEnable to be set on spill at $"
                    << Inst->getVISAId() << std::endl;
          std::cerr << std::endl;
        }
      };

      if (!UsesHW) {
        // For OW and LSC, RMW fill should exist, unless RMW opt in
        // spill insertion (correctly) decided otherwise. We cannot
        // lookup decision of RMW opt here, so we may see some false
        // positives.
        CheckRMWFill();
        // OW and LSC must use WriteEnable
        CheckWriteEnable();
      }
      ++InstIter;
    }
  }
}

static void replaceSSO(G4_Kernel &kernel) {
  // Invoke function only for XeHP_SDV and later
  // Replace SSO with r126.7:ud (scratch reg) up to VISA ABI v2
  if (!kernel.fg.builder->getSpillSurfaceOffset())
    return;

  auto dst = kernel.fg.builder->createDst(
      kernel.fg.getScratchRegDcl()->getRegVar(), 0, 7, 1, Type_UD);
  for (auto bb : kernel.fg) {
    for (auto instIt = bb->begin(); instIt != bb->end(); instIt++) {
      auto inst = (*instIt);
      if (inst->getDst() && inst->getDst()->getTopDcl() ==
                                kernel.fg.builder->getSpillSurfaceOffset()) {
        if (kernel.fg.getIsStackCallFunc()) {
          instIt = bb->erase(instIt);
          --instIt;
        } else
          inst->setDest(dst);

        // if an earlier pass inserted pseudokill for SSO dcl, remove it
        // but our final target is the instruction actually defining SSO.
        if (inst->isPseudoKill())
          continue;

        // Also update scratch msg dcl to be an alias
        kernel.fg.builder->getSpillSurfaceOffset()->setAliasDeclare(
            kernel.fg.getScratchRegDcl(), 7 * TypeSize(Type_UD));

        return;
      }
    }
  }
}

// Entry point for all RA flavors.
int regAlloc(IR_Builder &builder, PhyRegPool &regPool, G4_Kernel &kernel) {
  kernel.fg.callerSaveAreaOffset = kernel.fg.calleeSaveAreaOffset =
      kernel.fg.frameSizeInOWord = 0;

#if defined(_DEBUG) || defined(_INTERNAL)
  vISA::RATraceFlag = builder.getOption(vISA_RATrace);
#endif

  // This must be done before Points-to analysis as it may modify CFG and add
  // new BB!
  if (kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc()) {
    kernel.fg.setABIForStackCallFunctionCalls();
    kernel.fg.addFrameSetupDeclares(builder, regPool);
    kernel.fg.normalizeFlowGraph();
    if (builder.getPlatform() >= Xe_XeHPSDV)
      replaceSSO(kernel);
  }

  if (kernel.getOption(vISA_DoSplitOnSpill)) {
    // loop computation is done here because we may need to add
    // new preheader BBs. later parts of RA assume no change
    // to CFG structure.
    kernel.fg.getLoops().computePreheaders();
  }

  kernel.fg.reassignBlockIDs();
  // do it once for whole RA pass. Assumption is RA should not modify CFG at all
  kernel.fg.setPhysicalPredSucc();

  if (kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D) {
    kernel.fg.findNaturalLoops();
  }

  //
  // Perform flow-insensitive points-to-analysis.
  //
  PointsToAnalysis pointsToAnalysis(kernel.Declares, kernel.fg.getNumBB());
  pointsToAnalysis.doPointsToAnalysis(kernel.fg);
  GlobalRA gra(kernel, regPool, pointsToAnalysis);

  //
  // insert pseudo save/restore return address so that reg alloc
  // can assign registers to hold the return addresses
  //
  gra.assignLocForReturnAddr();


  //
  // Mark block local variables for the whole graph prior to performing liveness
  // analysis.
  // 1. Is required for flag/address register allocation
  // 2. We must make sure the reference number, reference BB(which will be
  // identified in local RA as well) happens only one time. Otherwise, there
  // will be correctness issue
  gra.markGraphBlockLocalVars();

  // Remove the un-referenced declares
  gra.removeUnreferencedDcls();

  if (kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_CM) {
    kernel.fg.markScope();
  }

  //
  // perform graph coloring for whole program
  //

  if (kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc()) {
    kernel.fg.addSaveRestorePseudoDeclares(builder);
    gra.fixSrc0IndirFcall();
  }

  int status = gra.coloringRegAlloc();

  if (auto jitInfo = builder.getJitInfo()) {
    jitInfo->numBytesScratchGtpin =
        kernel.getGTPinData()->getNumBytesScratchUse();
    // verify that spill memory used is within platform's acceptable limit
    unsigned int totalScratchUsed =
        jitInfo->stats.spillMemUsed +
        kernel.getInt32KernelAttr(Attributes::ATTR_SpillMemOffset);
    if (totalScratchUsed > builder.getMaxPTSS()) {
      builder.criticalMsgStream()
          << "Total scratch size used by shader exceeds platform capability: "
          << totalScratchUsed << "\n";
      return VISA_SPILL;
    }
  }

  // propagate address takens to gtpin info
  std::unordered_map<const G4_Declare *, std::vector<G4_Declare *>> addrTakenMap;
  pointsToAnalysis.getPointsToMap(addrTakenMap);
  auto gtpinData = kernel.getGTPinData();
  for (auto &indirRef : addrTakenMap) {
    for (auto target : indirRef.second)
      gtpinData->addIndirRef(indirRef.first, target);
  }

  if (status != VISA_SUCCESS) {
    return status;
  }

  if (builder.getOption(vISA_VerifyRA)) {
    // Mark local variables to improve the liveness analysis on partially
    // written local variables.
    // For example, for some payload decls, the region is not completely
    // written in the setup. That may cause gen is not blocked by the setup
    // inst, and the verifier might wrongly report a conflict assignment.
    //
    // clang-format off
    //   .declare M9 (2547)  rf=r size=32 type=ud align=16 words
    //
    //   (W) mov (1)              M9(0,2)<1>:ud  0xe0:uw // $211:
    //   (W) send (8)             V0173(0,0)<1>:d M9(0,0) 0x2184200:ud unaligned oword block read, dstLen=1, src0Len=1
    // clang-format on
    gra.markGraphBlockLocalVars();
    LivenessAnalysis liveAnalysis(gra, G4_GRF | G4_INPUT, true);
    liveAnalysis.computeLiveness();
    // Mark scope so that verifier can leverage the scope information to
    // verify live-in and live-out.
    kernel.fg.markScope();
    gra.verifyRA(liveAnalysis);
  }

  // printf("EU Fusion WA insts for func: %s\n", kernel.getName());
  for (auto inst : gra.getEUFusionCallWAInsts()) {
    kernel.setMaskOffset(inst, InstOpt_M16);
  }

#if defined(_DEBUG)
  for (auto inst : gra.getEUFusionNoMaskWAInsts()) {
    if (inst->getPredicate() != nullptr || inst->getCondMod() != nullptr) {
      vISA_ASSERT(false,
                  "Don't expect either predicate nor condmod for WA insts!");
    }
  }
#endif

  return status;
}