File: ConsumeOperatorCopyableAddressesChecker.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (2683 lines) | stat: -rw-r--r-- 105,486 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
//===--- ConsumeOperatorCopyableAddressChecker.cpp ------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// NOTE: This pass is assumed to run before all memory optimizations that
/// manipulate the lifetimes of values in memory such as any of the -Onone
/// predictable memory optimizations. allocbox to stack is ok since it doesn't
/// effect the actual memory itself, just whether the memory is boxed or not.
///
/// In this file, we implement a checker that for memory objects in SIL checks
/// that after a call to _move, one can no longer use a var or a let with an
/// address only type. If you use it after that point, but before a known
/// destroy point, you get an error. Example:
///
///   var x = Class()
///   let y = _move(x)
///   _use(x) // error!
///   x = Class()
///   _use(x) // Ok, we reinitialized the memory.
///
/// Below, I describe in detail the algorithm. NOTE: The design below will be
/// updated to support inits once we actually support vars. Currently, we only
/// support lets.
///
/// # Design
///
/// ## Introduction
///
/// At its heart this checker is a dataflow checker that first understands the
/// lifetime of a specific address and then optimizes based off of that
/// information. It uses AccessUseVisitor to reliably get all users of an
/// address. Then it partitions those uses into three sets:
///
///  * A set of mark_unresolved_move_addr. A mark_unresolved_move_addr is an
///    instruction that marks an invocation by _move on a value. Since we have
///    not yet proven using dataflow that it can be a move, semantically this
///    instruction is actually a copy_addr [init] so we maintain a valid IR if
///    we have uses later that we want to error upon. This is where we always
///    begin tracking dataflow.
///
///  * A set of destroy_value operations. These are points where we stop
///    tracking dataflow.
///
///  * A set of misc uses that just require liveness, We call the last category
///    "livenessUses". These are the uses that can not exist in between the move
///    and the destroy_addr operation and if we see any, we emit an error to the
///    user.
///
/// ## Gathering information to prepare for the Dataflow
///
/// We perform several different dataflow operations:
///
/// 1. First mark_unresolved_move_addr are propagated downwards to determine if
///    they propagate downwards out of blocks. When this is done, we perform the
///    single basic block form of this diagnostic. If we emit a diagnostic while
///    doing that, we exit. Otherwise, we know that there must not be any uses
///    or consumes in the given block, so it propagates move out.
///
/// 2. Then mark_unresolved_move_addr and all liveness uses are propagated up to
///    determine if a block propagates liveness up. We always use the earliest
///    user in the block. Once we find that user, we insert it into a
///    DenseMap<SILBasicBlock *, SILInstruction *>. This is so we can emit a
///    nice diagnostic.
///
/// 3. Then we propagate destroy_addr upwards stopping if we see an init. If we
///    do not see an init, then we know that we propagated that destroy upward
///    out of the block. We then insert that into a DenseMap<SILBasicBlock *,
///    DestroyAddrInst *> we are maintaining. NOTE: We do not need to check for
///    moves here since any move in our block would have either resulted in the
///    destroy_addr being eliminated earlier by the single block form of the
///    diagnostic and us exiting early or us emitting an error diagnostic and
///    exiting early.
///
/// NOTE: The reason why we do not track init information on a per block is that
/// in our dataflow, we are treating inits as normal uses and if we see an init
/// without seeing a destroy_addr, we will error on the use and bail. Once we
/// decide to support vars, this will change.
///
/// NOTE: The reason why we do not track all consuming operations, just destroy
/// operations is that instead we are treating a consuming operation as a
/// liveness use. Since we are always going to just exit on the first error for
/// any specific move (all moves will be checked individually of course), we
/// know that we will stop processing blocks at that point.
///
/// ## Performing the Global Dataflow
///
/// Finally using this information we gathered above, for each markMoveAddrOut
/// block individually, we walk the CFG downwards starting with said block's
/// successors looking for liveness uses and destroy_addr blocks.
///
/// 1. If we visit any "liveness block", immediately emit an error diagnostic as
///    the user requested and return. We can not convert the
///    mark_unresolved_move_addr into a move safely.
///
/// 2. If we visit a DestroyAddr block instead, we mark the destroy_addr as
///    being a destroy_addr that is associated with a move. This is done a per
///    address basis.
///
/// Once we have finished visiting mark_unresolved_move_addr, if we found /any/
/// mark_unresolved_move_addr that were safe to convert to a take (and that we
/// did convert to a take), we need to then cleanup destroys.
///
/// ## Cleaning up Destroys
///
/// We do this simultaneously for all of the mark_unresolved_move_addr applied
/// to a single address. Specifically, we place into a worklist all of the
/// predecessor blocks of all destroy_addr blocks that we found while performing
/// global dataflow. Then for each block b until we run out of blocks:
///
/// 1. If b is a block associated with one of our converted
///    mark_unresolved_move_addr, continue. Along that path, we are shortening
///    the lifetime of the address as requested by the user.
///
/// 2. Then we check if b is a block that was not visited when processing the
///    new moves. In such a case, we have found the dominance frontier of one or
///    many of the moves and insert a destroy_addr at the end of the b and
///    continue.
///
/// 3. Finally, if b is not on our dominance frontier and isn't a stopping
///    point, we add its predecessors to the worklist and continue.
///
/// Once these steps have been completed, we delete all of the old destroy_addr
/// since the lifetime of the address has now been handled appropriately along
/// all paths through the program.
///
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-consume-operator-copyable-addresses-checker"

#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Types.h"
#include "swift/Basic/BlotSetVector.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/Basic/GraphNodeWorklist.h"
#include "swift/Basic/SmallBitVector.h"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/Consumption.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILCloner.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILLinkage.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h"
#include "swift/SILOptimizer/Analysis/ClosureScope.h"
#include "swift/SILOptimizer/Analysis/LoopAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/CanonicalizeOSSALifetime.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "swift/SILOptimizer/Utils/SpecializationMangler.h"
#include "llvm/ADT/PointerEmbeddedInt.h"
#include "llvm/ADT/PointerSumType.h"

using namespace swift;

static llvm::cl::opt<bool> DisableUnhandledConsumeOperator(
    "sil-consume-operator-disable-unknown-moveaddr-diagnostic");

//===----------------------------------------------------------------------===//
//                                 Utilities
//===----------------------------------------------------------------------===//

template <typename... T, typename... U>
static void diagnose(ASTContext &Context, SourceLoc loc, Diag<T...> diag,
                     U &&...args) {
  Context.Diags.diagnose(loc, diag, std::forward<U>(args)...);
}

static SourceLoc getSourceLocFromValue(SILValue value) {
  if (auto *defInst = value->getDefiningInstruction())
    return defInst->getLoc().getSourceLoc();
  if (auto *arg = dyn_cast<SILFunctionArgument>(value))
    return arg->getDecl()->getLoc();
  llvm_unreachable("Do not know how to get source loc for value?!");
}

#ifndef NDEBUG
static void dumpBitVector(llvm::raw_ostream &os, const SmallBitVector &bv) {
  for (unsigned i = 0; i < bv.size(); ++i) {
    os << (bv[i] ? '1' : '0');
  }
}
#endif

/// Returns true if a value has one or zero debug uses.
static bool hasMoreThanOneDebugUse(SILValue v) {
  auto Range = getDebugUses(v);
  auto i = Range.begin(), e = Range.end();
  if (i == e)
    return false;
  ++i;
  return i != e;
}

//===----------------------------------------------------------------------===//
//                            Forward Declarations
//===----------------------------------------------------------------------===//

namespace {

enum class DownwardScanResult {
  Invalid,
  Destroy,
  Reinit,
  // NOTE: We use UseForDiagnostic both for defer uses and normal uses.
  UseForDiagnostic,
  MoveOut,
  ClosureConsume,
  ClosureUse,
};

struct ClosureOperandState {
  /// This is the downward scan result that visiting a full applysite of this
  /// closure will effect on the address being analyzed.
  DownwardScanResult result = DownwardScanResult::Invalid;

  /// Instructions that act as consumes in the closure callee. This is the set
  /// of earliest post dominating consumes that should be eliminated in the
  /// cloned callee. Only set if state is upwards consume.
  TinyPtrVector<SILInstruction *> pairedConsumingInsts;

  /// The set of instructions in the callee that are uses that require the move
  /// to be alive. Only set if state is upwards use.
  TinyPtrVector<SILInstruction *> pairedUseInsts;

  /// The single debug value in the closure callee that we sink to the reinit
  /// points.
  DebugValueInst *singleDebugValue = nullptr;

  bool isUpwardsUse() const { return result == DownwardScanResult::ClosureUse; }

  bool isUpwardsConsume() const {
    return result == DownwardScanResult::ClosureConsume;
  }
};

} // namespace

/// Is this a reinit instruction that we know how to convert into its init form.
static bool isReinitToInitConvertibleInst(Operand *memUse) {
  auto *memInst = memUse->getUser();
  switch (memInst->getKind()) {
  default:
    return false;

  case SILInstructionKind::CopyAddrInst: {
    auto *cai = cast<CopyAddrInst>(memInst);
    return !cai->isInitializationOfDest();
  }
  case SILInstructionKind::StoreInst: {
    auto *si = cast<StoreInst>(memInst);
    return si->getOwnershipQualifier() == StoreOwnershipQualifier::Assign;
  }
  }
}

static void convertMemoryReinitToInitForm(SILInstruction *memInst) {
  switch (memInst->getKind()) {
  default:
    llvm_unreachable("unsupported?!");

  case SILInstructionKind::CopyAddrInst: {
    auto *cai = cast<CopyAddrInst>(memInst);
    cai->setIsInitializationOfDest(IsInitialization_t::IsInitialization);
    return;
  }
  case SILInstructionKind::StoreInst: {
    auto *si = cast<StoreInst>(memInst);
    si->setOwnershipQualifier(StoreOwnershipQualifier::Init);
    return;
  }
  }
}

//===----------------------------------------------------------------------===//
//                               Use State
//===----------------------------------------------------------------------===//

namespace {

struct UseState {
  SILValue address;
  SmallVector<MarkUnresolvedMoveAddrInst *, 1> markMoves;
  SmallPtrSet<SILInstruction *, 1> seenMarkMoves;
  llvm::SmallSetVector<SILInstruction *, 2> inits;
  llvm::SmallSetVector<SILInstruction *, 4> livenessUses;
  SmallBlotSetVector<DestroyAddrInst *, 4> destroys;
  llvm::SmallDenseMap<SILInstruction *, unsigned, 4> destroyToIndexMap;
  SmallBlotSetVector<SILInstruction *, 4> reinits;
  llvm::SmallDenseMap<SILInstruction *, unsigned, 4> reinitToIndexMap;
  llvm::SmallMapVector<Operand *, ClosureOperandState, 1> closureUses;
  llvm::SmallDenseMap<Operand *, unsigned, 1> closureOperandToIndexMap;

  void insertMarkUnresolvedMoveAddr(MarkUnresolvedMoveAddrInst *inst) {
    if (!seenMarkMoves.insert(inst).second)
      return;
    markMoves.emplace_back(inst);
  }

  void insertDestroy(DestroyAddrInst *dai) {
    destroyToIndexMap[dai] = destroys.size();
    destroys.insert(dai);
  }

  void insertReinit(SILInstruction *inst) {
    reinitToIndexMap[inst] = reinits.size();
    reinits.insert(inst);
  }

  void insertClosureOperand(Operand *op) {
    closureOperandToIndexMap[op] = closureUses.size();
    closureUses[op] = {};
  }

  void clear() {
    address = SILValue();
    markMoves.clear();
    seenMarkMoves.clear();
    inits.clear();
    livenessUses.clear();
    destroys.clear();
    destroyToIndexMap.clear();
    reinits.clear();
    reinitToIndexMap.clear();
    closureUses.clear();
    closureOperandToIndexMap.clear();
  }

  SILFunction *getFunction() const { return address->getFunction(); }
};

} // namespace

//===----------------------------------------------------------------------===//
//                                  Dataflow
//===----------------------------------------------------------------------===//

/// Returns true if we are move out, false otherwise. If we find an interesting
/// inst, we return it in foundInst. If no inst is returned, one must continue.
static DownwardScanResult
downwardScanForMoveOut(MarkUnresolvedMoveAddrInst *mvi, UseState &useState,
                       SILInstruction **foundInst, Operand **foundOperand,
                       TinyPtrVector<SILInstruction *> &foundClosureInsts) {
  // Forward scan looking for uses or reinits.
  for (auto &next : llvm::make_range(std::next(mvi->getIterator()),
                                     mvi->getParent()->end())) {
    LLVM_DEBUG(llvm::dbgs() << "DownwardScan. Checking: " << next);

    // If we hit a non-destroy_addr, then we immediately know that we found an
    // error. Return the special result with the next stashed within it.
    if (useState.livenessUses.count(&next) ||
        useState.seenMarkMoves.count(&next) || useState.inits.count(&next)) {
      // Emit a diagnostic error and process the next mark_unresolved_move_addr.
      LLVM_DEBUG(llvm::dbgs() << "SingleBlock liveness user: " << next);
      *foundInst = &next;
      return DownwardScanResult::UseForDiagnostic;
    }

    {
      auto iter = useState.reinitToIndexMap.find(&next);
      if (iter != useState.reinitToIndexMap.end()) {
        LLVM_DEBUG(llvm::dbgs() << "DownwardScan: reinit: " << next);
        *foundInst = &next;
        return DownwardScanResult::Reinit;
      }
    }

    // If we see a destroy_addr, then stop processing since it pairs directly
    // with our move.
    {
      auto iter = useState.destroyToIndexMap.find(&next);
      if (iter != useState.destroyToIndexMap.end()) {
        auto *dai = cast<DestroyAddrInst>(iter->first);
        LLVM_DEBUG(llvm::dbgs() << "DownwardScan: Destroy: " << *dai);
        *foundInst = dai;
        return DownwardScanResult::Destroy;
      }
    }

    // Finally check if we have a closure user that we were able to handle.
    if (auto fas = FullApplySite::isa(&next)) {
      LLVM_DEBUG(llvm::dbgs() << "DownwardScan: ClosureCheck: " << **fas);
      for (auto &op : fas.getArgumentOperands()) {
        auto iter = useState.closureUses.find(&op);
        if (iter == useState.closureUses.end()) {
          continue;
        }

        LLVM_DEBUG(llvm::dbgs()
                   << "DownwardScan: ClosureCheck: Matching Operand: "
                   << fas.getAppliedArgIndex(op));
        *foundInst = &next;
        *foundOperand = &op;
        switch (iter->second.result) {
        case DownwardScanResult::Invalid:
        case DownwardScanResult::Destroy:
        case DownwardScanResult::Reinit:
        case DownwardScanResult::UseForDiagnostic:
        case DownwardScanResult::MoveOut:
          llvm_unreachable("unhandled");
        case DownwardScanResult::ClosureConsume:
          LLVM_DEBUG(llvm::dbgs() << ". ClosureConsume.\n");
          llvm::copy(iter->second.pairedConsumingInsts,
                     std::back_inserter(foundClosureInsts));
          break;
        case DownwardScanResult::ClosureUse:
          LLVM_DEBUG(llvm::dbgs() << ". ClosureUse.\n");
          llvm::copy(iter->second.pairedUseInsts,
                     std::back_inserter(foundClosureInsts));
          break;
        }
        return iter->second.result;
      }
    }
  }

  // We are move out!
  LLVM_DEBUG(llvm::dbgs() << "DownwardScan. We are move out!\n");
  return DownwardScanResult::MoveOut;
}

/// Scan backwards from \p inst to the beginning of its parent block looking for
/// uses. We return true if \p inst is the first use that we are tracking for
/// the given block. This means it propagates liveness upwards through the CFG.
///
/// This works only for an instruction expected to be a normal use.
static bool upwardScanForUseOut(SILInstruction *inst, UseState &useState) {
  // We scan backwards from the instruction before \p inst to the beginning of
  // the block.
  for (auto &iter : llvm::make_range(std::next(inst->getReverseIterator()),
                                     inst->getParent()->rend())) {
    // If we hit another liveness use, then this isn't the first use in the
    // block. We want to store only the first use in the block. In such a case,
    // we bail since when we visit that earlier instruction, we will do the
    // appropriate check.
    if (useState.livenessUses.contains(&iter))
      // If we are not tracking a destroy, we stop at liveness uses. If we have
      // a destroy_addr, we use the destroy blocks to ignore the liveness uses
      // since we use the destroy_addr to signal we should stop tracking when we
      // use dataflow and to pair/delete with a move.
      return false;
    if (useState.destroyToIndexMap.count(&iter))
      return false;
    if (auto *mmai = dyn_cast<MarkUnresolvedMoveAddrInst>(&iter))
      if (useState.seenMarkMoves.count(mmai))
        return false;
    if (useState.inits.contains(&iter))
      return false;
    if (useState.reinitToIndexMap.count(&iter))
      return false;
    if (auto fas = FullApplySite::isa(&iter)) {
      for (auto &op : fas.getArgumentOperands()) {
        if (useState.closureUses.find(&op) != useState.closureUses.end())
          return false;
      }
    }
  }
  return true;
}

/// Scan backwards from \p inst to the beginning of its parent block looking for
/// uses. We return true if \p inst is the first use that we are tracking for
/// the given block. This means it propagates liveness upwards through the CFG.
static bool upwardScanForDestroys(SILInstruction *inst, UseState &useState) {
  // We scan backwards from the instruction before \p inst to the beginning of
  // the block.
  for (auto &iter : llvm::make_range(std::next(inst->getReverseIterator()),
                                     inst->getParent()->rend())) {
    // If we find a destroy_addr earlier in the block, do not mark this block as
    // being associated with this destroy. We always want to associate the move
    // with the earliest destroy_addr.
    if (useState.destroyToIndexMap.count(&iter))
      return false;
    if (useState.reinitToIndexMap.count(&iter))
      return false;
    // If we see an init, then we return found other use to not track this
    // destroy_addr up since it is balanced by the init.
    if (useState.inits.contains(&iter))
      return false;
    if (auto fas = FullApplySite::isa(&iter)) {
      for (auto &op : fas.getArgumentOperands()) {
        if (useState.closureUses.find(&op) != useState.closureUses.end())
          return false;
      }
    }

    // Otherwise, we have a normal use, just ignore it.
  }

  // Ok, this instruction is the first use in the block of our value. So return
  // true so we track it as such.
  return true;
}

/// Search for the first init in the block.
static bool upwardScanForInit(SILInstruction *inst, UseState &useState) {
  // We scan backwards from the instruction before \p inst to the beginning of
  // the block.
  for (auto &iter : llvm::make_range(std::next(inst->getReverseIterator()),
                                     inst->getParent()->rend())) {
    if (useState.inits.contains(&iter))
      return false;
    if (auto fas = FullApplySite::isa(&iter)) {
      for (auto &op : fas.getArgumentOperands()) {
        if (useState.closureUses.find(&op) != useState.closureUses.end())
          return false;
      }
    }
  }
  return true;
}

//===----------------------------------------------------------------------===//
//                      Closure Argument Global Dataflow
//===----------------------------------------------------------------------===//

namespace {

/// A utility class that analyzes a closure that captures a moved value. It is
/// used to perform move checking within the closure as well as to determine a
/// set of reinit/destroys that we will need to convert to init and or eliminate
/// while cloning the closure.
///
/// NOTE: We do not need to consider if the closure reinitializes the memory
/// since there must be some sort of use for the closure to even reference it
/// and the compiler emits assigns when it reinitializes vars this early in the
/// pipeline.
struct ClosureArgDataflowState {
  ASTContext &C;
  SmallVector<SILInstruction *, 32> livenessWorklist;
  SmallVector<SILInstruction *, 32> consumingWorklist;
  MultiDefPrunedLiveness livenessForConsumes;
  UseState &useState;

public:
  ClosureArgDataflowState(SILFunction *function, UseState &useState)
      : C(function->getASTContext()),
        livenessForConsumes(function), useState(useState) {}

  bool process(
      SILArgument *arg, ClosureOperandState &state,
      SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers);

private:

  /// Perform our liveness dataflow. Returns true if we found any liveness uses
  /// at all. These we will need to error upon.
  bool performLivenessDataflow(const BasicBlockSet &initBlocks,
                               const BasicBlockSet &livenessBlocks,
                               const BasicBlockSet &consumingBlocks);

  /// Perform our consuming dataflow. Returns true if we found an earliest set
  /// of consuming uses that we can handle that post-dominate the argument.
  /// Returns false otherwise.
  bool performConsumingDataflow(const BasicBlockSet &initBlocks,
                                const BasicBlockSet &consumingBlocks);

  void classifyUses(BasicBlockSet &initBlocks, BasicBlockSet &livenessBlocks,
                    BasicBlockSet &consumingBlocks);

  bool handleSingleBlockCase(SILArgument *address, ClosureOperandState &state);
};

} // namespace

bool ClosureArgDataflowState::handleSingleBlockCase(
    SILArgument *address, ClosureOperandState &state) {
  // Walk the instructions from the beginning of the block to the end.
  for (auto &inst : *address->getParent()) {
    assert(!useState.inits.count(&inst) &&
           "Shouldn't see an init before a destroy or reinit");

    // If we see a destroy, then we know we are upwards consume... stash it so
    // that we can destroy it
    if (auto *dvi = dyn_cast<DestroyAddrInst>(&inst)) {
      if (useState.destroyToIndexMap.count(dvi)) {
        LLVM_DEBUG(llvm::dbgs()
                   << "ClosureArgDataflow: Found Consume: " << *dvi);

        if (hasMoreThanOneDebugUse(address))
          return false;

        state.pairedConsumingInsts.push_back(dvi);
        state.result = DownwardScanResult::ClosureConsume;
        return true;
      }
    }

    // Same for reinits.
    if (useState.reinits.count(&inst)) {
      LLVM_DEBUG(llvm::dbgs() << "ClosureArgDataflow: Found Reinit: " << inst);

      if (hasMoreThanOneDebugUse(address))
        return false;

      state.pairedConsumingInsts.push_back(&inst);
      state.result = DownwardScanResult::ClosureConsume;
      return true;
    }

    // Finally, if we have a liveness use, report it for a diagnostic.
    if (useState.livenessUses.count(&inst)) {
      LLVM_DEBUG(llvm::dbgs()
                 << "ClosureArgDataflow: Found liveness use: " << inst);
      state.pairedUseInsts.push_back(&inst);
      state.result = DownwardScanResult::ClosureUse;
      return true;
    }
  }

  LLVM_DEBUG(
      llvm::dbgs() << "ClosureArgDataflow: Did not find interesting uses.\n");
  return false;
}

bool ClosureArgDataflowState::performLivenessDataflow(
    const BasicBlockSet &initBlocks, const BasicBlockSet &livenessBlocks,
    const BasicBlockSet &consumingBlocks) {
  LLVM_DEBUG(llvm::dbgs() << "ClosureArgLivenessDataflow. Start!\n");
  bool foundSingleLivenessUse = false;
  auto *fn = useState.getFunction();
  auto *frontBlock = &*fn->begin();
  BasicBlockWorklist worklist(fn);

  for (unsigned i : indices(livenessWorklist)) {
    auto *&user = livenessWorklist[i];

    // If our use is in the first block, then we are done with this user. Set
    // the found single liveness use flag and continue!
    if (frontBlock == user->getParent()) {
      foundSingleLivenessUse = true;
      continue;
    }

    bool success = false;
    for (auto *predBlock : user->getParent()->getPredecessorBlocks()) {
      worklist.pushIfNotVisited(predBlock);
    }
    while (auto *next = worklist.pop()) {
      if (livenessBlocks.contains(next) || initBlocks.contains(next) ||
          consumingBlocks.contains(next)) {
        continue;
      }

      if (frontBlock == next) {
        success = true;
        foundSingleLivenessUse = true;
        break;
      }

      for (auto *predBlock : next->getPredecessorBlocks()) {
        worklist.pushIfNotVisited(predBlock);
      }
    }
    if (!success) {
      user = nullptr;
    }
  }
  return foundSingleLivenessUse;
}

bool ClosureArgDataflowState::performConsumingDataflow(
    const BasicBlockSet &initBlocks, const BasicBlockSet &consumingBlocks) {
  auto *fn = useState.getFunction();
  auto *frontBlock = &*fn->begin();

  bool foundSingleConsumingUse = false;
  BasicBlockWorklist worklist(fn);
  for (unsigned i : indices(consumingWorklist)) {
    auto *&user = consumingWorklist[i];

    if (frontBlock == user->getParent())
      continue;

    bool success = false;
    for (auto *predBlock : user->getParent()->getPredecessorBlocks()) {
      worklist.pushIfNotVisited(predBlock);
    }
    while (auto *next = worklist.pop()) {
      if (initBlocks.contains(next) || consumingBlocks.contains(next)) {
        continue;
      }

      if (frontBlock == next) {
        success = true;
        foundSingleConsumingUse = true;
        break;
      }

      for (auto *predBlock : next->getPredecessorBlocks()) {
        worklist.pushIfNotVisited(predBlock);
      }
    }
    if (!success) {
      user = nullptr;
    }
  }
  return foundSingleConsumingUse;
}

void ClosureArgDataflowState::classifyUses(BasicBlockSet &initBlocks,
                                           BasicBlockSet &livenessBlocks,
                                           BasicBlockSet &consumingBlocks) {

  for (auto *user : useState.inits) {
    if (upwardScanForInit(user, useState)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found init block during classifyUses at: " << *user);
      livenessForConsumes.initializeDef(user);
      initBlocks.insert(user->getParent());
    }
  }

  for (auto *user : useState.livenessUses) {
    if (upwardScanForUseOut(user, useState)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found use block during classifyUses at: " << *user);
      livenessBlocks.insert(user->getParent());
      livenessWorklist.push_back(user);
    }
  }

  for (auto destroyOpt : useState.destroys) {
    assert(destroyOpt);

    auto *destroy = *destroyOpt;

    auto iter = useState.destroyToIndexMap.find(destroy);
    assert(iter != useState.destroyToIndexMap.end());

    if (upwardScanForDestroys(destroy, useState)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found destroy block during classifyUses at: " << *destroy);
      consumingBlocks.insert(destroy->getParent());
      consumingWorklist.push_back(destroy);
    }
  }

  for (auto reinitOpt : useState.reinits) {
    assert(reinitOpt);

    auto *reinit = *reinitOpt;
    auto iter = useState.reinitToIndexMap.find(reinit);
    assert(iter != useState.reinitToIndexMap.end());

    // TODO: Reinitialization analysis is currently incomplete and leads
    // to miscompiles. Treat reinitializations as regular uses for now.
    if (!C.LangOpts.hasFeature(Feature::ReinitializeConsumeInMultiBlockDefer)) {
      LLVM_DEBUG(llvm::dbgs() << "    Treating reinit as use block during classifyUses at: " << *reinit);
      livenessBlocks.insert(reinit->getParent());
      livenessWorklist.push_back(reinit);
      continue;
    }

    if (upwardScanForDestroys(reinit, useState)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found reinit block during classifyUses at: " << *reinit);
      consumingBlocks.insert(reinit->getParent());
      consumingWorklist.push_back(reinit);
    }
  }
}

bool ClosureArgDataflowState::process(
    SILArgument *address, ClosureOperandState &state,
    SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers) {
  SILFunction *fn = address->getFunction();
  assert(fn);

  // First see if our function only has a single block. In such a case,
  // summarize using the single processing routine.
  if (address->getParent()->getTerminator()->isFunctionExiting()) {
    LLVM_DEBUG(llvm::dbgs() << "ClosureArgDataflow: Single Block Case.\n");
    return handleSingleBlockCase(address, state);
  }

  LLVM_DEBUG(llvm::dbgs() << "ClosureArgDataflow: Multiple Block Case.\n");

  // At this point, we begin by classifying the uses of our address into init
  // blocks, liveness blocks, consuming blocks. We also seed the worklist for
  // our two dataflows.
  SWIFT_DEFER {
    livenessWorklist.clear();
    consumingWorklist.clear();
  };
  BasicBlockSet initBlocks(fn);
  BasicBlockSet livenessBlocks(fn);
  BasicBlockSet consumingBlocks(fn);
  classifyUses(initBlocks, livenessBlocks, consumingBlocks);

  // Liveness Dataflow:
  //
  // The way that we do this is that for each such instruction:
  //
  // 1. If the instruction is in the entrance block, then it is our only answer.
  //
  // 2. If the user is not in the entrance block, visit recursively its
  //    predecessor blocks until one either hits the entrance block (in which
  //    case this is the result) /or/ one hits a block in one of our basic block
  //    sets which means there is an earlier use. Consuming blocks only stop for
  //    consuming blocks and init blocks. Liveness blocks stop for all other
  //    blocks.
  //
  // The result is what remains in our set. Thus we start by processing
  // liveness.
  if (performLivenessDataflow(initBlocks, livenessBlocks, consumingBlocks)) {
    for (unsigned i : indices(livenessWorklist)) {
      if (auto *ptr = livenessWorklist[i]) {
        LLVM_DEBUG(llvm::dbgs()
                   << "ClosureArgLivenessDataflow. Final: Liveness User: "
                   << *ptr);
        state.pairedUseInsts.push_back(ptr);
      }
    }
    state.result = DownwardScanResult::ClosureUse;
    return true;
  }

  // Then perform the consuming use dataflow. In this case, we think we may have
  // found a set of post-dominating consuming uses for our inout_aliasable
  // parameter. We are going to change it to be an out parameter and eliminate
  // these when we clone the closure.
  if (performConsumingDataflow(initBlocks, consumingBlocks)) {
    LLVM_DEBUG(llvm::dbgs() << "found single consuming use!\n");
    
    // Before we do anything, make sure our argument has at least one single
    // debug_value user. If we have many we can't handle it since something in
    // SILGen is emitting weird code. Our tests will ensure that SILGen does not
    // diverge by mistake. So we are really just being careful.
    if (hasMoreThanOneDebugUse(address)) {
      // Failing b/c more than one debug use!
      LLVM_DEBUG(llvm::dbgs() << "...but argument has more than one debug use!\n");
      return false;
    }

    //!!! FIXME: Why?
    //auto *frontBlock = &*fn->begin();
    //livenessForConsumes.initializeDef(address);

    for (unsigned i : indices(consumingWorklist)) {
      if (auto *ptr = consumingWorklist[i]) {
        LLVM_DEBUG(llvm::dbgs() << "liveness for consume: " << *ptr);
        state.pairedConsumingInsts.push_back(ptr);
        //livenessForConsumes.updateForUse(ptr, true /*is lifetime ending*/);
      }
    }

    // If our consumes do not have a linear lifetime, bail. We will error on the
    // move being unknown.
    for (auto *ptr : state.pairedConsumingInsts) {
      /*if (livenessForConsumes.isWithinBoundary(ptr)) {
        LLVM_DEBUG(llvm::dbgs() << "consuming inst within boundary; bailing: "
                                << *ptr);
        return false;
      }*/
      postDominatingConsumingUsers.insert(ptr);
    }
    state.result = DownwardScanResult::ClosureConsume;
    return true;
  }

  return true;
}

//===----------------------------------------------------------------------===//
//                            Closure Use Gatherer
//===----------------------------------------------------------------------===//

namespace {

/// Visit all of the uses of a closure argument, initializing useState as we go.
struct GatherClosureUseVisitor : public AccessUseVisitor {
  UseState &useState;

  GatherClosureUseVisitor(UseState &useState)
      : AccessUseVisitor(AccessUseType::Overlapping,
                         NestedAccessType::IgnoreAccessBegin),
        useState(useState) {}

  bool visitUse(Operand *op, AccessUseType useTy) override;
  void reset(SILValue address) { useState.address = address; }
  void clear() { useState.clear(); }
};

} // end anonymous namespace

// Filter out recognized uses that do not write to memory.
//
// TODO: Ensure that all of the conditional-write logic below is encapsulated in
// mayWriteToMemory and just call that instead. Possibly add additional
// verification that visitAccessPathUses recognizes all instructions that may
// propagate pointers (even though they don't write).
bool GatherClosureUseVisitor::visitUse(Operand *op, AccessUseType useTy) {
  // If this operand is for a dependent type, then it does not actually access
  // the operand's address value. It only uses the metatype defined by the
  // operation (e.g. open_existential).
  if (op->isTypeDependent()) {
    return true;
  }

  // Ignore debug_values. We should leave them on the argument so that later in
  // the function the user can still access the out parameter once it is
  // updated.
  if (isa<DebugValueInst>(op->getUser()))
    return true;

  // Ignore end_access. For our purposes, they are irrelevant and we do not want
  // to treat them like liveness uses.
  if (isa<EndAccessInst>(op->getUser()))
    return true;

  if (memInstMustInitialize(op)) {
    if (stripAccessMarkers(op->get()) != useState.address) {
      LLVM_DEBUG(llvm::dbgs()
                 << "!!! Error! Found init use not on base address: "
                 << *op->getUser());
      return false;
    }

    LLVM_DEBUG(llvm::dbgs() << "ClosureUse: Found init: " << *op->getUser());
    useState.inits.insert(op->getUser());
    return true;
  }

  if (isReinitToInitConvertibleInst(op)) {
    if (stripAccessMarkers(op->get()) != useState.address) {
      LLVM_DEBUG(llvm::dbgs()
                 << "!!! Error! Found reinit use not on base address: "
                 << *op->getUser());
      return false;
    }

    LLVM_DEBUG(llvm::dbgs() << "ClosureUse: Found reinit: " << *op->getUser());
    useState.insertReinit(op->getUser());
    return true;
  }

  if (auto *dvi = dyn_cast<DestroyAddrInst>(op->getUser())) {
    // If we see a destroy_addr not on our base address, bail! Just error and
    // say that we do not understand the code.
    if (dvi->getOperand() != useState.address) {
      LLVM_DEBUG(llvm::dbgs()
                 << "!!! Error! Found destroy_addr no on base address: "
                 << *dvi);
      return false;
    }
    LLVM_DEBUG(llvm::dbgs() << "ClosureUse: Found destroy_addr: " << *dvi);
    useState.insertDestroy(dvi);
    return true;
  }

  LLVM_DEBUG(llvm::dbgs() << "ClosureUse: Found liveness use: "
                          << *op->getUser());
  useState.livenessUses.insert(op->getUser());

  return true;
}

//===----------------------------------------------------------------------===//
//                          Closure Argument Cloner
//===----------------------------------------------------------------------===//

namespace {

struct ClosureArgumentInOutToOutCloner
    : SILClonerWithScopes<ClosureArgumentInOutToOutCloner> {
  friend class SILInstructionVisitor<ClosureArgumentInOutToOutCloner>;
  friend class SILCloner<ClosureArgumentInOutToOutCloner>;

  SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers;
  SILFunction *orig;
  const SmallBitVector &argsToConvertIndices;
  SmallPtrSet<SILValue, 8> oldArgSet;

  // Map from clonedArg -> oldArg.
  llvm::SmallMapVector<SILValue, SILValue, 4> clonedArgToOldArgMap;

public:
  ClosureArgumentInOutToOutCloner(
      SILOptFunctionBuilder &funcBuilder, SILFunction *orig,
      SerializedKind_t serializedKind,
      SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers,
      const SmallBitVector &argsToConvertIndices, StringRef name);

  void populateCloned();

  SILFunction *getCloned() { return &getBuilder().getFunction(); }

  void visitDebugValueInst(DebugValueInst *inst) {
    // Do not clone if our inst argument is one of our cloned arguments. In such
    // a case, we are going to handle the debug_value when we visit a post
    // dominating consuming reinit.
    if (oldArgSet.count(inst->getOperand())) {
      LLVM_DEBUG(llvm::dbgs()
                 << "    Visiting debug value that is in the old arg set!\n");
      return;
    }
    LLVM_DEBUG(llvm::dbgs()
               << "    Visiting debug value that we will clone!\n");
    SILCloner<ClosureArgumentInOutToOutCloner>::visitDebugValueInst(inst);
  }

  void visitDestroyValueInst(DestroyValueInst *inst) {
    if (!postDominatingConsumingUsers.count(inst)) {
      SILCloner<ClosureArgumentInOutToOutCloner>::visitDestroyValueInst(inst);
    }

    // Don't do anything if we have a destroy.
  }

  void visitCopyAddrInst(CopyAddrInst *inst) {
    if (!postDominatingConsumingUsers.count(inst)) {
      return SILCloner<ClosureArgumentInOutToOutCloner>::visitCopyAddrInst(
          inst);
    }

    // If this copy_addr is one of the copies that we need to fixup, convert it
    // to an init from a reinit. We also insert a debug_value
    assert(!inst->isInitializationOfDest() && "Should be a reinit");
    getBuilder().setCurrentDebugScope(getOpScope(inst->getDebugScope()));
    recordClonedInstruction(
        inst, getBuilder().createCopyAddr(
                  getOpLocation(inst->getLoc()), getOpValue(inst->getSrc()),
                  getOpValue(inst->getDest()), inst->isTakeOfSrc(),
                  IsInitialization_t::IsInitialization));

    // Then if in our caller we had a debug_value on our dest, add it here.
    auto base = AccessPathWithBase::compute(inst->getDest()).base;
    if (oldArgSet.count(base)) {
      if (auto *op = getSingleDebugUse(base)) {
        if (auto *dvi = dyn_cast<DebugValueInst>(op->getUser())) {
          SILCloner<ClosureArgumentInOutToOutCloner>::visitDebugValueInst(dvi);
        }
      }
    }
  }

  void visitStoreInst(StoreInst *inst) {
    if (!postDominatingConsumingUsers.count(inst)) {
      return SILCloner<ClosureArgumentInOutToOutCloner>::visitStoreInst(inst);
    }

    // If this store is one of the copies that we need to fixup, convert it
    // to an init from being an assign.
    assert(inst->getOwnershipQualifier() == StoreOwnershipQualifier::Assign);
    getBuilder().setCurrentDebugScope(getOpScope(inst->getDebugScope()));
    recordClonedInstruction(
        inst, getBuilder().createStore(
                  getOpLocation(inst->getLoc()), getOpValue(inst->getSrc()),
                  getOpValue(inst->getDest()), StoreOwnershipQualifier::Init));

    auto base = AccessPathWithBase::compute(inst->getDest()).base;
    if (oldArgSet.count(base)) {
      if (auto *op = getSingleDebugUse(base)) {
        if (auto *dvi = dyn_cast<DebugValueInst>(op->getUser())) {
          SILCloner<ClosureArgumentInOutToOutCloner>::visitDebugValueInst(dvi);
        }
      }
    }
  }

private:
  static SILFunction *initCloned(
      SILOptFunctionBuilder &funcBuilder, SILFunction *orig,
      SerializedKind_t serializedKind,
      SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers,
      const SmallBitVector &argsToConvertIndices, StringRef cloneName);
};

} // namespace

static std::string getClonedName(SILFunction *func, SerializedKind_t serialized,
                                 const SmallBitVector &argsToConvertIndices) {
  auto kind = Demangle::SpecializationPass::MoveDiagnosticInOutToOut;
  Mangle::FunctionSignatureSpecializationMangler Mangler(kind, serialized,
                                                         func);
  for (int i = argsToConvertIndices.find_first(); i != -1;
       i = argsToConvertIndices.find_next(i)) {
    Mangler.setArgumentInOutToOut(i);
  }
  return Mangler.mangle();
}

ClosureArgumentInOutToOutCloner::ClosureArgumentInOutToOutCloner(
    SILOptFunctionBuilder &funcBuilder, SILFunction *orig,
    SerializedKind_t serializedKind,
    SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers,
    const SmallBitVector &argsToConvertIndices, StringRef name)
    : SILClonerWithScopes<ClosureArgumentInOutToOutCloner>(*initCloned(
          funcBuilder, orig, serializedKind, postDominatingConsumingUsers,
          argsToConvertIndices, name)),
      postDominatingConsumingUsers(postDominatingConsumingUsers), orig(orig),
      argsToConvertIndices(argsToConvertIndices) {
  assert(orig->getDebugScope()->getParentFunction() !=
         getCloned()->getDebugScope()->getParentFunction());
}

/// Create the function corresponding to the clone of the
/// original closure with the signature modified to reflect promoted
/// parameters (which are specified by PromotedArgIndices).
SILFunction *ClosureArgumentInOutToOutCloner::initCloned(
    SILOptFunctionBuilder &funcBuilder, SILFunction *orig,
    SerializedKind_t serialized,
    SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers,
    const SmallBitVector &argsToConvertIndices, StringRef clonedName) {
  SILModule &mod = orig->getModule();
  SmallVector<SILParameterInfo, 4> clonedInterfaceArgTys;
  SmallVector<SILResultInfo, 4> clonedResultInfos;
  SILFunctionType *origFTI = orig->getLoweredFunctionType();

  // First initialized cloned result infos with the old results.
  for (auto result : origFTI->getResults())
    clonedResultInfos.push_back(result);

  // Generate a new parameter list with deleted parameters removed...
  unsigned initArgIndex = orig->getConventions().getSILArgIndexOfFirstParam();
  LLVM_DEBUG(llvm::dbgs() << "CLONER: initArgIndex: " << initArgIndex << '\n');
  for (auto state :
       llvm::enumerate(origFTI->getParameters().drop_front(initArgIndex))) {
    unsigned index = state.index();
    auto paramInfo = state.value();

    // If we are supposed to convert this, add the parameter to the result list.
    if (argsToConvertIndices.test(index)) {
      LLVM_DEBUG(llvm::dbgs() << "CLONER: Converting: " << index << "\n");
      clonedResultInfos.emplace_back(paramInfo.getInterfaceType(),
                                     ResultConvention::Indirect);
      continue;
    }

    LLVM_DEBUG(llvm::dbgs() << "CLONER: Letting through: " << index << "\n");
    // Otherwise, just let it through.
    clonedInterfaceArgTys.push_back(paramInfo);
    ++index;
  }

  // Create the new function type for the cloned function with some of
  // the parameters moved to be results.
  auto clonedTy = SILFunctionType::get(
      origFTI->getInvocationGenericSignature(), origFTI->getExtInfo(),
      origFTI->getCoroutineKind(), origFTI->getCalleeConvention(),
      clonedInterfaceArgTys, origFTI->getYields(), clonedResultInfos,
      origFTI->getOptionalErrorResult(), origFTI->getPatternSubstitutions(),
      origFTI->getInvocationSubstitutions(), mod.getASTContext(),
      origFTI->getWitnessMethodConformanceOrInvalid());
  LLVM_DEBUG(llvm::dbgs() << "CLONER: clonedTy: " << clonedTy << "\n");
  assert((orig->isTransparent() || orig->isBare() || orig->getLocation()) &&
         "SILFunction missing location");
  assert((orig->isTransparent() || orig->isBare() || orig->getDebugScope()) &&
         "SILFunction missing DebugScope");
  assert(!orig->isGlobalInit() && "Global initializer cannot be cloned");
  auto *Fn = funcBuilder.createFunction(
      swift::getSpecializedLinkage(orig, orig->getLinkage()), clonedName,
      clonedTy, orig->getGenericEnvironment(), orig->getLocation(),
      orig->isBare(), orig->isTransparent(), serialized, IsNotDynamic,
      IsNotDistributed, IsNotRuntimeAccessible, orig->getEntryCount(),
      orig->isThunk(), orig->getClassSubclassScope(), orig->getInlineStrategy(),
      orig->getEffectsKind(), orig, orig->getDebugScope());
  for (auto &Attr : orig->getSemanticsAttrs()) {
    Fn->addSemanticsAttr(Attr);
  }

  return Fn;
}

/// Populate the body of the cloned closure, modifying instructions as
/// necessary to take into consideration the removed parameters.
void ClosureArgumentInOutToOutCloner::populateCloned() {
  SILFunction *cloned = getCloned();

  // Create arguments for the entry block
  SILBasicBlock *origEntryBlock = &*orig->begin();
  SILBasicBlock *clonedEntryBlock = cloned->createBasicBlock();

  SmallVector<SILValue, 4> entryArgs;
  entryArgs.reserve(origEntryBlock->getArguments().size());

  // First process all of the indirect results and add our new results after
  // them.
  auto oldArgs = origEntryBlock->getArguments();
  auto origConventions = orig->getConventions();
  for (unsigned i : range(origConventions.getSILArgIndexOfFirstIndirectResult(),
                          origConventions.getSILArgIndexOfFirstParam())) {
    LLVM_DEBUG(llvm::dbgs() << "Have indirect result\n");
    auto *arg = oldArgs[i];
    // Create a new argument which copies the original argument.
    auto *newArg = clonedEntryBlock->createFunctionArgument(arg->getType(),
                                                            arg->getDecl());
    clonedArgToOldArgMap[newArg] = arg;
    entryArgs.push_back(newArg);
  }

  // To avoid needing to mess with types, just go through our original arguments
  // in the entry block to get the right types.
  for (auto state : llvm::enumerate(origEntryBlock->getArguments())) {
    unsigned argNo = state.index();
    LLVM_DEBUG(llvm::dbgs() << "Testing Old Arg Number: " << argNo << "\n");
    if (!argsToConvertIndices.test(argNo))
      continue;

    auto *arg = state.value();
    auto *newArg = clonedEntryBlock->createFunctionArgument(arg->getType(),
                                                            arg->getDecl());
    clonedArgToOldArgMap[newArg] = arg;
    oldArgSet.insert(arg);
    entryArgs.push_back(newArg);
    LLVM_DEBUG(llvm::dbgs() << "Mapping From: " << *arg);
    LLVM_DEBUG(llvm::dbgs()
               << "   of function: " << arg->getFunction()->getName() << '\n');
    LLVM_DEBUG(llvm::dbgs() << "Mapping To: " << *newArg);
    LLVM_DEBUG(llvm::dbgs() << "   of function: "
                            << newArg->getFunction()->getName() << '\n');
  }

  // Finally, recreate the rest of the arguments which we did not specialize.
  for (auto state : llvm::enumerate(origEntryBlock->getArguments())) {
    unsigned argNo = state.index();
    if (argsToConvertIndices.test(argNo))
      continue;

    auto *arg = state.value();
    auto *newArg = clonedEntryBlock->createFunctionArgument(arg->getType(),
                                                            arg->getDecl());

    clonedArgToOldArgMap[newArg] = arg;
    entryArgs.push_back(newArg);
  }

  // Visit original BBs in depth-first preorder, starting with the
  // entry block, cloning all instructions and terminators.
  cloneFunctionBody(
      orig, clonedEntryBlock, entryArgs, [&](SILValue clonedArg) -> SILValue {
        LLVM_DEBUG(llvm::dbgs() << "Searching for: " << *clonedArg);
        auto iter = clonedArgToOldArgMap.find(clonedArg);
        assert(iter != clonedArgToOldArgMap.end() &&
               "Should map all cloned args to an old arg");
        LLVM_DEBUG(llvm::dbgs() << "Found it! Mapping to : " << *iter->second);
        return iter->second;
      });
}

/////////////////////////////////////
// Caller Lexical Lifetime Visitor //
/////////////////////////////////////

namespace {

/// Visit all of the uses of a lexical lifetime, initializing useState as we go.
struct GatherLexicalLifetimeUseVisitor : public AccessUseVisitor {
  UseState &useState;

  GatherLexicalLifetimeUseVisitor(UseState &useState)
      : AccessUseVisitor(AccessUseType::Overlapping,
                         NestedAccessType::IgnoreAccessBegin),
        useState(useState) {}

  bool visitUse(Operand *op, AccessUseType useTy) override;
  void reset(SILValue address) { useState.address = address; }
  void clear() { useState.clear(); }
};

} // end anonymous namespace

// Filter out recognized uses that do not write to memory.
//
// TODO: Ensure that all of the conditional-write logic below is encapsulated in
// mayWriteToMemory and just call that instead. Possibly add additional
// verification that visitAccessPathUses recognizes all instructions that may
// propagate pointers (even though they don't write).
bool GatherLexicalLifetimeUseVisitor::visitUse(Operand *op,
                                               AccessUseType useTy) {
  // If this operand is for a dependent type, then it does not actually access
  // the operand's address value. It only uses the metatype defined by the
  // operation (e.g. open_existential).
  if (op->isTypeDependent()) {
    return true;
  }

  // If we have a move from src, this is a mark_move we want to visit.
  if (auto *move = dyn_cast<MarkUnresolvedMoveAddrInst>(op->getUser())) {
    if (move->getSrc() == op->get()) {
      LLVM_DEBUG(llvm::dbgs() << "Found move: " << *move);
      useState.insertMarkUnresolvedMoveAddr(move);
      return true;
    }
  }

  if (memInstMustInitialize(op)) {
    if (stripAccessMarkers(op->get()) != useState.address) {
      LLVM_DEBUG(llvm::dbgs()
                 << "!!! Error! Found init use not on base address: "
                 << *op->getUser());
      return false;
    }

    LLVM_DEBUG(llvm::dbgs() << "Found init: " << *op->getUser());
    useState.inits.insert(op->getUser());
    return true;
  }

  if (isReinitToInitConvertibleInst(op)) {
    if (stripAccessMarkers(op->get()) != useState.address) {
      LLVM_DEBUG(llvm::dbgs()
                 << "!!! Error! Found reinit use not on base address: "
                 << *op->getUser());
      return false;
    }

    LLVM_DEBUG(llvm::dbgs() << "Found reinit: " << *op->getUser());
    useState.insertReinit(op->getUser());
    return true;
  }

  if (auto *dvi = dyn_cast<DestroyAddrInst>(op->getUser())) {
    // If we see a destroy_addr not on our base address, bail! Just error and
    // say that we do not understand the code.
    if (dvi->getOperand() != useState.address) {
      LLVM_DEBUG(llvm::dbgs()
                 << "!!! Error! Found destroy_addr no on base address: "
                 << *dvi);
      return false;
    }
    LLVM_DEBUG(llvm::dbgs() << "Found destroy_addr: " << *dvi);
    useState.insertDestroy(dvi);
    return true;
  }

  // Then see if we have a inout_aliasable full apply site use. In that case, we
  // are going to try and extend move checking into the partial apply using
  // cloning to eliminate destroys or reinits.
  if (auto fas = FullApplySite::isa(op->getUser())) {
    if (stripAccessMarkers(op->get()) != useState.address) {
      LLVM_DEBUG(
          llvm::dbgs()
          << "!!! Error! Found consuming closure use not on base address: "
          << *op->getUser());
      return false;
    }

    if (fas.getCaptureConvention(*op) ==
        SILArgumentConvention::Indirect_InoutAliasable) {
      // If we don't find the function, we can't handle this, so bail.
      auto *func = fas.getCalleeFunction();
      if (!func || !func->isDefer())
        return false;
      LLVM_DEBUG(llvm::dbgs() << "Found closure use: " << *op->getUser());
      useState.insertClosureOperand(op);
      return true;
    }
  }

  // Ignore dealloc_stack.
  if (isa<DeallocStackInst>(op->getUser()))
    return true;

  // Ignore end_access.
  if (isa<EndAccessInst>(op->getUser()))
    return true;

  LLVM_DEBUG(llvm::dbgs() << "Found liveness use: " << *op->getUser());
  useState.livenessUses.insert(op->getUser());

  return true;
}

//===----------------------------------------------------------------------===//
//                              Global Dataflow
//===----------------------------------------------------------------------===//

namespace {

struct DataflowState {
  llvm::DenseMap<SILBasicBlock *, SILInstruction *> useBlocks;
  llvm::DenseSet<SILBasicBlock *> initBlocks;
  llvm::DenseMap<SILBasicBlock *, SILInstruction *> destroyBlocks;
  llvm::DenseMap<SILBasicBlock *, SILInstruction *> reinitBlocks;
  llvm::DenseMap<SILBasicBlock *, Operand *> closureConsumeBlocks;
  llvm::DenseMap<SILBasicBlock *, ClosureOperandState *> closureUseBlocks;
  SmallVector<MarkUnresolvedMoveAddrInst *, 8> markMovesThatPropagateDownwards;

  SILOptFunctionBuilder &funcBuilder;
  UseState &useState;
  llvm::SmallMapVector<FullApplySite, SmallBitVector, 8>
      &applySiteToPromotedArgIndices;
  SmallBlotSetVector<SILInstruction *, 8> &closureConsumes;

  DataflowState(SILOptFunctionBuilder &funcBuilder, UseState &useState,
                llvm::SmallMapVector<FullApplySite, SmallBitVector, 8>
                    &applySiteToPromotedArgIndices,
                SmallBlotSetVector<SILInstruction *, 8> &closureConsumes)
      : funcBuilder(funcBuilder), useState(useState),
        applySiteToPromotedArgIndices(applySiteToPromotedArgIndices),
        closureConsumes(closureConsumes) {}
  void init();
  bool process(
      SILValue address, DebugVarCarryingInst addressDebugInst,
      SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers);
  bool handleSingleBlockClosure(SILArgument *address,
                                ClosureOperandState &state);
  bool cleanupAllDestroyAddr(
      SILValue address, DebugVarCarryingInst addressDebugInst, SILFunction *fn,
      SmallBitVector &destroyIndices, SmallBitVector &reinitIndices,
      SmallBitVector &consumingClosureIndices,
      BasicBlockSet &blocksVisitedWhenProcessingNewTakes,
      BasicBlockSet &blocksWithMovesThatAreNowTakes,
      SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers);
  void clear() {
    useBlocks.clear();
    initBlocks.clear();
    destroyBlocks.clear();
    reinitBlocks.clear();
    markMovesThatPropagateDownwards.clear();
    closureConsumeBlocks.clear();
    closureUseBlocks.clear();
  }
};

} // namespace

bool DataflowState::cleanupAllDestroyAddr(
    SILValue address, DebugVarCarryingInst addressDebugInst, SILFunction *fn,
    SmallBitVector &destroyIndices, SmallBitVector &reinitIndices,
    SmallBitVector &consumingClosureIndices,
    BasicBlockSet &blocksVisitedWhenProcessingNewTakes,
    BasicBlockSet &blocksWithMovesThatAreNowTakes,
    SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers) {
  bool madeChange = false;
  BasicBlockWorklist worklist(fn);

  LLVM_DEBUG(llvm::dbgs() << "Cleanup up destroy addr!\n");
  LLVM_DEBUG(llvm::dbgs() << "    Visiting destroys!\n");
  LLVM_DEBUG(llvm::dbgs() << "    Destroy Indices: " << destroyIndices << "\n");
  for (int index = destroyIndices.find_first(); index != -1;
       index = destroyIndices.find_next(index)) {
    LLVM_DEBUG(llvm::dbgs() << "    Index: " << index << "\n");
    auto dai = useState.destroys[index];
    if (!dai)
      continue;
    LLVM_DEBUG(llvm::dbgs() << "    Destroy: " << *dai);
    for (auto *predBlock : (*dai)->getParent()->getPredecessorBlocks()) {
      worklist.pushIfNotVisited(predBlock);
    }
  }

  LLVM_DEBUG(llvm::dbgs() << "    Visiting reinit!\n");
  for (int index = reinitIndices.find_first(); index != -1;
       index = reinitIndices.find_next(index)) {
    auto reinit = useState.reinits[index];
    if (!reinit)
      continue;
    LLVM_DEBUG(llvm::dbgs() << "  Reinit: " << **reinit);
    for (auto *predBlock : (*reinit)->getParent()->getPredecessorBlocks()) {
      worklist.pushIfNotVisited(predBlock);
    }
  }

  LLVM_DEBUG(llvm::dbgs() << "    Visiting consuming closures!\n");
  for (int index = consumingClosureIndices.find_first(); index != -1;
       index = consumingClosureIndices.find_next(index)) {
    auto &pair = *std::next(useState.closureUses.begin(), index);
    auto *op = pair.first;
    LLVM_DEBUG(llvm::dbgs() << "  Consuming closure: " << *op->getUser());
    for (auto *predBlock : op->getUser()->getParent()->getPredecessorBlocks()) {
      worklist.pushIfNotVisited(predBlock);
    }
  }

  LLVM_DEBUG(llvm::dbgs() << "Processing worklist!\n");
  while (auto *next = worklist.pop()) {
    LLVM_DEBUG(llvm::dbgs()
               << "Looking at block: bb" << next->getDebugID() << "\n");

    // Any blocks that contained processed moves are stop points.
    if (blocksWithMovesThatAreNowTakes.contains(next)) {
      LLVM_DEBUG(llvm::dbgs()
                 << "    Block contained a move that is now a true take.\n");
      continue;
    }

    // Then if we find that we have a block that was never visited when we
    // walked along successor edges from the move, then we know that we need to
    // insert a destroy_addr.
    //
    // This is safe to do since this block lives along the dominance frontier
    // and we do not allow for critical edges, so as we walk along predecessors,
    // given that any such block must also have a successor that was reachable
    // from our move, we know that this unprocessed block must only have one
    // successor, a block reachable from our move and thus must not have any
    // unhandled uses.
    if (!blocksVisitedWhenProcessingNewTakes.contains(next)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found a block that was not visited when "
                                 "we processed takes of the given move.\n");
      // Insert a destroy_addr here since the block isn't reachable from any of
      // our moves.
      SILBasicBlock::iterator iter;
      if (!isa<TermInst>(next->front())) {
        iter = std::prev(next->getTerminator()->getIterator());
      } else {
        iter = next->begin();
      }
      SILBuilderWithScope builder(iter);
      auto *dvi = builder.createDestroyAddr(
          RegularLocation::getAutoGeneratedLocation(), address);
      // Create a debug_value undef if we have debug info to stop the async dbg
      // info propagation from creating debug info for an already destroyed
      // value. We use a separate builder since we need to control the debug
      // scope/location to get llvm to do the right thing.
      if (addressDebugInst) {
        if (auto varInfo = addressDebugInst.getVarInfo()) {
          // We need to always insert /after/ the reinit since the value will
          // not be defined before the value.
          SILBuilderWithScope dbgValueInsertBuilder(dvi);
          dbgValueInsertBuilder.setCurrentDebugScope(
              addressDebugInst->getDebugScope());
          dbgValueInsertBuilder.createDebugValue(
              (*addressDebugInst)->getLoc(), SILUndef::get(address), *varInfo,
              false, UsesMoveableValueDebugInfo);
        }
      }
      useState.destroys.insert(dvi);
      continue;
    }

    // Otherwise, this block is reachable from one of our move blocks, visit
    // further predecessors.
    for (auto *predBlock : next->getPredecessorBlocks()) {
      worklist.pushIfNotVisited(predBlock);
    }
  }

  for (int index = destroyIndices.find_first(); index != -1;
       index = destroyIndices.find_next(index)) {
    auto destroy = useState.destroys[index];
    if (!destroy)
      continue;
    LLVM_DEBUG(llvm::dbgs() << "Erasing destroy_addr: " << *destroy);
    (*destroy)->eraseFromParent();
    madeChange = true;
  }

  for (int index = reinitIndices.find_first(); index != -1;
       index = reinitIndices.find_next(index)) {
    auto reinit = useState.reinits[index];
    if (!reinit)
      continue;
    LLVM_DEBUG(llvm::dbgs() << "Converting reinit to init: " << *reinit);
    convertMemoryReinitToInitForm(*reinit);

    // Make sure to create a new debug_value for the reinit value.
    if (addressDebugInst) {
      if (auto varInfo = addressDebugInst.getVarInfo()) {
        // We need to always insert /after/ the reinit since the value will not
        // be defined before the value.
        SILBuilderWithScope reinitBuilder((*reinit)->getNextInstruction());
        reinitBuilder.setCurrentDebugScope(addressDebugInst->getDebugScope());
        reinitBuilder.createDebugValue((*addressDebugInst)->getLoc(), address,
                                       *varInfo, false,
                                       UsesMoveableValueDebugInfo);
      }
    }
    madeChange = true;
  }

  // Check for consuming closures. If we find such a consuming closure, track
  // that this full apply site needs to have some parameters converted when we
  // are done processing.
  //
  // NOTE: We do this late to ensure that we only clone a defer exactly once
  // rather than multiple times for multiple vars.
  for (int index = consumingClosureIndices.find_first(); index != -1;
       index = consumingClosureIndices.find_next(index)) {
    auto &pair = *std::next(useState.closureUses.begin(), index);
    auto *closureUse = pair.first;
    if (!closureUse)
      continue;

    // This is correct today due to us only supporting defer. When we handle
    // partial apply, we will need to do more work ehre.
    FullApplySite fas(closureUse->getUser());
    assert(fas);
    unsigned appliedArgIndex = fas.getAppliedArgIndex(*closureUse);
    LLVM_DEBUG(llvm::dbgs() << "Processing closure use: " << **fas);
    LLVM_DEBUG(llvm::dbgs() << "AppliedArgIndex: " << appliedArgIndex << '\n');
    auto &bitVector = applySiteToPromotedArgIndices[fas];
    auto conventions = fas.getSubstCalleeConv();
    unsigned numNonResultArgs = conventions.getNumSILArguments();
    if (bitVector.size() < numNonResultArgs)
      bitVector.resize(numNonResultArgs);
    bitVector.set(appliedArgIndex);
    for (auto *user : pair.second.pairedConsumingInsts) {
      closureConsumes.insert(user);
    }
  }

  return madeChange;
}

bool DataflowState::process(
    SILValue address, DebugVarCarryingInst addressDebugInst,
    SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers) {
  SILFunction *fn = address->getFunction();
  assert(fn);

  bool madeChange = false;
  SmallBitVector indicesOfPairedDestroys;
  auto getIndicesOfPairedDestroys = [&]() -> SmallBitVector & {
    if (indicesOfPairedDestroys.size() != useState.destroys.size())
      indicesOfPairedDestroys.resize(useState.destroys.size());
    return indicesOfPairedDestroys;
  };
  SmallBitVector indicesOfPairedReinits;
  auto getIndicesOfPairedReinits = [&]() -> SmallBitVector & {
    if (indicesOfPairedReinits.size() != useState.reinits.size())
      indicesOfPairedReinits.resize(useState.reinits.size());
    return indicesOfPairedReinits;
  };
  SmallBitVector indicesOfPairedConsumingClosureUses;
  auto getIndicesOfPairedConsumingClosureUses = [&]() -> SmallBitVector & {
    if (indicesOfPairedConsumingClosureUses.size() !=
        useState.closureUses.size())
      indicesOfPairedConsumingClosureUses.resize(useState.closureUses.size());
    return indicesOfPairedConsumingClosureUses;
  };

  BasicBlockSet blocksVisitedWhenProcessingNewTakes(fn);
  BasicBlockSet blocksWithMovesThatAreNowTakes(fn);
  bool convertedMarkMoveToTake = false;

  for (auto *mvi : markMovesThatPropagateDownwards) {
    bool emittedSingleDiagnostic = false;

    LLVM_DEBUG(llvm::dbgs() << "Checking Multi Block Dataflow for: " << *mvi);
    LLVM_DEBUG(llvm::dbgs() << "    Parent Block: bb"
                            << mvi->getParent()->getDebugID() << "\n");

    BasicBlockWorklist worklist(fn);
    BasicBlockSetVector visitedBlocks(fn);
    for (auto *succBlock : mvi->getParent()->getSuccessorBlocks()) {
      LLVM_DEBUG(llvm::dbgs()
                 << "    SuccBlocks: bb" << succBlock->getDebugID() << "\n");
      worklist.pushIfNotVisited(succBlock);
      visitedBlocks.insert(succBlock);
    }

    while (auto *next = worklist.pop()) {
      LLVM_DEBUG(llvm::dbgs() << "Visiting: bb" << next->getDebugID() << "\n");

      // Before we check if we are supposed to stop processing here, check if we
      // have a use block. In such a case, emit an error.
      //
      // NOTE: We do this before since we could have a use before a destroy_addr
      // in this block. We would like to error in such a case.
      auto iter = useBlocks.find(next);
      if (iter != useBlocks.end()) {
        LLVM_DEBUG(llvm::dbgs() << "    Is Use Block! Emitting Error!\n");
        // We found one! Emit the diagnostic and continue and see if we can get
        // more diagnostics.
        auto &astContext = fn->getASTContext();
        {
          auto diag =
              diag::sil_movechecking_value_used_after_consume;
          StringRef name = getDebugVarName(address);
          diagnose(astContext, getSourceLocFromValue(address), diag, name);
        }

        {
          auto diag = diag::sil_movechecking_consuming_use_here;
          if (auto sourceLoc = mvi->getLoc().getSourceLoc()) {
            diagnose(astContext, sourceLoc, diag);
          }
        }

        {
          auto diag = diag::sil_movechecking_nonconsuming_use_here;
          if (auto sourceLoc = iter->second->getLoc().getSourceLoc()) {
            diagnose(astContext, sourceLoc, diag);
          }
        }

        emittedSingleDiagnostic = true;
        break;
      }

      // Now see if we have a closure use.
      {
        auto iter = closureUseBlocks.find(next);
        if (iter != closureUseBlocks.end()) {
          LLVM_DEBUG(llvm::dbgs()
                     << "    Is Use Block From Closure! Emitting Error!\n");
          // We found one! Emit the diagnostic and continue and see if we can
          // get more diagnostics.
          auto &astContext = fn->getASTContext();
          {
            auto diag =
                diag::sil_movechecking_value_used_after_consume;
            StringRef name = getDebugVarName(address);
            diagnose(astContext, getSourceLocFromValue(address), diag, name);
          }

          {
            auto diag = diag::sil_movechecking_consuming_use_here;
            if (auto sourceLoc = mvi->getLoc().getSourceLoc()) {
              diagnose(astContext, sourceLoc, diag);
            }
          }

          {
            auto diag = diag::sil_movechecking_nonconsuming_use_here;
            for (auto *user : iter->second->pairedUseInsts) {
              if (auto sourceLoc = user->getLoc().getSourceLoc()) {
                diagnose(astContext, sourceLoc, diag);
              }
            }
          }

          emittedSingleDiagnostic = true;
          break;
        }
      }

      // Then see if this is a destroy block. If so, do not add successors and
      // continue. This is because we stop processing at destroy_addr. This
      // destroy_addr is paired with the mark_unresolved_move_addr.
      {
        auto iter = destroyBlocks.find(next);
        if (iter != destroyBlocks.end()) {
          LLVM_DEBUG(llvm::dbgs() << "    Is Destroy Block! Setting up for "
                                     "later deletion if possible!\n");
          auto indexIter = useState.destroyToIndexMap.find(iter->second);
          assert(indexIter != useState.destroyToIndexMap.end());
          getIndicesOfPairedDestroys().set(indexIter->second);
          continue;
        }
      }

      {
        auto iter = reinitBlocks.find(next);
        if (iter != reinitBlocks.end()) {
          LLVM_DEBUG(llvm::dbgs() << "    Is reinit Block! Setting up for "
                                     "later deletion if possible!\n");
          auto indexIter = useState.reinitToIndexMap.find(iter->second);
          assert(indexIter != useState.reinitToIndexMap.end());
          getIndicesOfPairedReinits().set(indexIter->second);
          continue;
        }
      }

      {
        auto iter = closureConsumeBlocks.find(next);
        if (iter != closureConsumeBlocks.end()) {
          LLVM_DEBUG(llvm::dbgs() << "    Is reinit Block! Setting up for "
                                     "later deletion if possible!\n");
          auto indexIter = useState.closureOperandToIndexMap.find(iter->second);
          assert(indexIter != useState.closureOperandToIndexMap.end());
          getIndicesOfPairedConsumingClosureUses().set(indexIter->second);
          continue;
        }
      }

      // Then see if this is an init block. If so, do not add successors and
      // continue. We already checked that we are not destroy up in this block
      // by the check a few lines up. So we know that we are in one of the
      // following situations:
      //
      // 1. We are the only use in the block. In this case, we must have
      //    consumed the value with a non-destroy_addr earlier (e.x.: apply). In
      //    such a case, we need to just stop processing since we are re-initing
      //    memory for a var.
      //
      // 2. There is a consuming use that is treated as a consuming use before
      //    us. In that case, we will have already errored upon it.
      if (initBlocks.count(next)) {
        LLVM_DEBUG(llvm::dbgs() << "    Is Init Block!\n");
        continue;
      }

      LLVM_DEBUG(
          llvm::dbgs()
          << "    No match! Pushing unvisited successors onto the worklist!\n");
      // Otherwise, add successors if we haven't visited them to the worklist.
      for (auto *succBlock : next->getSuccessorBlocks()) {
        worklist.pushIfNotVisited(succBlock);
        visitedBlocks.insert(succBlock);
      }
    }

    // At this point, we know that if we emitted a diagnostic, we need to
    // convert the move to a copy_addr [init] since we found a use that violates
    // the move. We just want to emit correct IR without the
    // mark_unresolved_move_addr within it.
    blocksWithMovesThatAreNowTakes.insert(mvi->getParent());
    SILBuilderWithScope builder(mvi);
    if (emittedSingleDiagnostic) {
      builder.createCopyAddr(mvi->getLoc(), mvi->getSrc(), mvi->getDest(),
                             IsNotTake, IsInitialization);
    } else {
      builder.createCopyAddr(mvi->getLoc(), mvi->getSrc(), mvi->getDest(),
                             IsTake, IsInitialization);

      // Now that we have processed all of our mark_moves, eliminate all of the
      // destroy_addr and set our debug value as being moved.
      if (addressDebugInst) {
        addressDebugInst.markAsMoved();
        if (auto varInfo = addressDebugInst.getVarInfo()) {
          SILBuilderWithScope undefBuilder(builder);
          undefBuilder.setCurrentDebugScope(addressDebugInst->getDebugScope());
          undefBuilder.createDebugValue(
              addressDebugInst->getLoc(), SILUndef::get(address), *varInfo,
              false /*poison*/, UsesMoveableValueDebugInfo);
        }
      }

      // Flush our SetVector into the visitedByNewMove.
      for (auto *block : visitedBlocks) {
        blocksVisitedWhenProcessingNewTakes.insert(block);
      }
      convertedMarkMoveToTake = true;
    }

    mvi->eraseFromParent();
    madeChange = true;
  }

  if (!convertedMarkMoveToTake)
    return madeChange;

  // Now that we have processed all of our mark_moves, eliminate all of the
  // destroy_addr.
  madeChange |= cleanupAllDestroyAddr(
      address, addressDebugInst, fn, getIndicesOfPairedDestroys(),
      getIndicesOfPairedReinits(), getIndicesOfPairedConsumingClosureUses(),
      blocksVisitedWhenProcessingNewTakes, blocksWithMovesThatAreNowTakes,
      postDominatingConsumingUsers);

  return madeChange;
}

void DataflowState::init() {
  // Go through all init uses and if we don't see any other of our uses, then
  // mark this as an "init block".
  for (auto *init : useState.inits) {
    if (upwardScanForInit(init, useState)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found use block during DataflowState::init at: " << *init);
      initBlocks.insert(init->getParent());
    }
  }

  // Then go through all normal uses and do upwardScanForUseOut.
  for (auto *user : useState.livenessUses) {
    if (upwardScanForUseOut(user, useState)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found liveness block during DataflowState::init at: " << *user);
      useBlocks[user->getParent()] = user;
    }
  }

  for (auto destroyOpt : useState.destroys) {
    // Any destroys we eliminated when processing single basic blocks will be
    // nullptr. Skip them!
    if (!destroyOpt)
      continue;

    auto *destroy = *destroyOpt;

    auto iter = useState.destroyToIndexMap.find(destroy);
    assert(iter != useState.destroyToIndexMap.end());

    if (upwardScanForDestroys(destroy, useState)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found destroy block during DataflowState::init at: " << *destroy);
      destroyBlocks[destroy->getParent()] = destroy;
    }
  }

  for (auto reinitOpt : useState.reinits) {
    // Any destroys we eliminated when processing single basic blocks will be
    // nullptr. Skip them!
    if (!reinitOpt)
      continue;

    auto *reinit = *reinitOpt;
    auto iter = useState.reinitToIndexMap.find(reinit);
    assert(iter != useState.reinitToIndexMap.end());

    if (upwardScanForDestroys(reinit, useState)) {
      LLVM_DEBUG(llvm::dbgs() << "    Found reinit block during DataflowState::init at: " << *reinit);
      reinitBlocks[reinit->getParent()] = reinit;
    }
  }

  for (auto &closureUse : useState.closureUses) {
    auto *use = closureUse.first;
    auto &state = closureUse.second;
    auto *user = use->getUser();

    switch (state.result) {
    case DownwardScanResult::Invalid:
    case DownwardScanResult::Destroy:
    case DownwardScanResult::Reinit:
    case DownwardScanResult::UseForDiagnostic:
    case DownwardScanResult::MoveOut:
      llvm_unreachable("unhandled");
    case DownwardScanResult::ClosureUse:
      if (upwardScanForUseOut(user, useState)) {
        LLVM_DEBUG(llvm::dbgs()
                   << "    Found closure liveness block during DataflowState::init at: " << *user);
        closureUseBlocks[user->getParent()] = &state;
      }
      break;
    case DownwardScanResult::ClosureConsume:
      if (upwardScanForDestroys(user, useState)) {
        LLVM_DEBUG(llvm::dbgs()
                   << "    Found closure consuming block during DataflowState::init at: " << *user);
        closureConsumeBlocks[user->getParent()] = use;
      }
      break;
    }
  }
}

//===----------------------------------------------------------------------===//
//                              Address Checker
//===----------------------------------------------------------------------===//

namespace {

struct ConsumeOperatorCopyableAddressesChecker {
  SILFunction *fn;
  UseState useState;
  DataflowState dataflowState;
  UseState closureUseState;
  SILOptFunctionBuilder &funcBuilder;
  llvm::SmallMapVector<FullApplySite, SmallBitVector, 8>
      applySiteToPromotedArgIndices;
  SmallBlotSetVector<SILInstruction *, 8> closureConsumes;

  ConsumeOperatorCopyableAddressesChecker(SILFunction *fn,
                                          SILOptFunctionBuilder &funcBuilder)
      : fn(fn), useState(),
        dataflowState(funcBuilder, useState, applySiteToPromotedArgIndices,
                      closureConsumes),
        closureUseState(), funcBuilder(funcBuilder) {}

  void cloneDeferCalleeAndRewriteUses(
      SmallVectorImpl<SILValue> &temporaryStorage,
      const SmallBitVector &bitVector, FullApplySite oldApplySite,
      SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers);

  bool check(SILValue address);
  bool performClosureDataflow(Operand *callerOperand,
                              ClosureOperandState &calleeOperandState);

  void emitDiagnosticForMove(SILValue borrowedValue,
                             StringRef borrowedValueName, MoveValueInst *mvi);
  bool performSingleBasicBlockAnalysis(SILValue address,
                                       DebugVarCarryingInst addressDebugInst,
                                       MarkUnresolvedMoveAddrInst *mvi);

  ASTContext &getASTContext() const { return fn->getASTContext(); }
};

} // namespace

void ConsumeOperatorCopyableAddressesChecker::cloneDeferCalleeAndRewriteUses(
    SmallVectorImpl<SILValue> &newArgs, const SmallBitVector &bitVector,
    FullApplySite oldApplySite,
    SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers) {
  auto *origCallee = oldApplySite.getReferencedFunctionOrNull();
  assert(origCallee);

  auto name =
      getClonedName(origCallee, origCallee->getSerializedKind(), bitVector);

  SILFunction *newCallee = nullptr;
  if (auto *fn = origCallee->getModule().lookUpFunction(name)) {
    newCallee = fn;
  } else {
    ClosureArgumentInOutToOutCloner cloner(
        funcBuilder, origCallee, origCallee->getSerializedKind(),
        postDominatingConsumingUsers, bitVector, name);
    cloner.populateCloned();
    newCallee = cloner.getCloned();
  }
  assert(newCallee);

  // Ok, we now have populated our new callee. We need to create a new full
  // apply site that calls the new function appropriately.
  SWIFT_DEFER { newArgs.clear(); };

  // First add all of our old results to newArgs.
  auto oldConv = oldApplySite.getSubstCalleeConv();
  for (unsigned i : range(oldConv.getSILArgIndexOfFirstIndirectResult(),
                          oldConv.getSILArgIndexOfFirstParam())) {
    newArgs.push_back(oldApplySite->getOperand(i));
  }

  // Now add all of our new out params.
  for (int i = bitVector.find_first(); i != -1; i = bitVector.find_next(i)) {
    unsigned appliedArgIndex =
        oldApplySite.getOperandIndexOfFirstArgument() + i;
    newArgs.push_back(oldApplySite->getOperand(appliedArgIndex));
  }

  // Finally, add all of the rest of our arguments, skipping our new out
  // parameters.
  for (unsigned i : range(oldConv.getSILArgIndexOfFirstParam(),
                          oldConv.getNumSILArguments())) {
    if (bitVector.test(i))
      continue;
    unsigned appliedArgIndex =
        oldApplySite.getOperandIndexOfFirstArgument() + i;
    newArgs.push_back(oldApplySite->getOperand(appliedArgIndex));
  }

  // Then create our new apply.
  SILBuilderWithScope builder(*oldApplySite);
  auto *newCalleeRef =
      builder.createFunctionRef(oldApplySite->getLoc(), newCallee);
  auto *newApply =
      builder.createApply(oldApplySite->getLoc(), newCalleeRef,
                          oldApplySite.getSubstitutionMap(), newArgs);
  oldApplySite->replaceAllUsesPairwiseWith(newApply);
  oldApplySite->eraseFromParent();
}

bool ConsumeOperatorCopyableAddressesChecker::performClosureDataflow(
    Operand *callerOperand, ClosureOperandState &calleeOperandState) {
  auto fas = FullApplySite::isa(callerOperand->getUser());
  auto *callee = fas.getCalleeFunction();
  auto *address =
      callee->begin()->getArgument(fas.getCalleeArgIndex(*callerOperand));

  LLVM_DEBUG(llvm::dbgs() << "Performing closure dataflow on caller use: "
                          << *callerOperand->getUser());
  LLVM_DEBUG(llvm::dbgs() << "    Callee: " << callee->getName() << '\n');
  LLVM_DEBUG(llvm::dbgs() << "    Callee Argument: " << *address);
  // We emit an end closure dataflow to make it easier when reading debug output
  // to make it easy to see when we have returned to analyzing the caller.
  SWIFT_DEFER {
    LLVM_DEBUG(llvm::dbgs()
                   << "Finished performing closure dataflow on Callee: "
                   << callee->getName() << '\n';);
  };
  auto accessPathWithBase = AccessPathWithBase::compute(address);
  auto accessPath = accessPathWithBase.accessPath;

  // Bail on an invalid AccessPath.
  //
  // AccessPath completeness is verified independently--it may be invalid in
  // extraordinary situations. When AccessPath is valid, we know all its uses
  // are recognizable.
  //
  // NOTE: If due to an invalid access path we fail here, we will just error
  // on the _move since the _move would not have been handled.
  if (!accessPath.isValid())
    return false;

  // TODO: Hoist this useState into an ivar that we can reuse in between closure
  // operands?
  GatherClosureUseVisitor visitor(closureUseState);
  SWIFT_DEFER { visitor.clear(); };
  visitor.reset(address);
  if (!visitAccessPathUses(visitor, accessPath, callee))
    return false;

  ClosureArgDataflowState closureUseDataflowState(callee, closureUseState);
  return closureUseDataflowState.process(address, calleeOperandState,
                                         closureConsumes);
}

struct MoveConstraint {
  enum Value : uint8_t {
    None,
    RequiresReinit,
    Illegal,
  } value;

  operator Value() { return value; }
  MoveConstraint(Value value) : value(value) {}

  static MoveConstraint forGuaranteed(bool guaranteed) {
    return guaranteed ? Illegal : None;
  }

  bool isIllegal() { return value == Illegal; }
};

static MoveConstraint getMoveConstraint(SILValue addr) {
  assert(addr->getType().isAddress());
  auto access = AccessPathWithBase::computeInScope(addr);
  auto base = access.getAccessBase();
  switch (access.accessPath.getStorage().getKind()) {
  case AccessRepresentation::Kind::Box:
    // Even if the box is guaranteed, it may be permitted to consume its
    // storage.
    return MoveConstraint::None;
  case AccessRepresentation::Kind::Stack: {
    // An alloc_stack is guaranteed if it's a "store_borrow destination".
    auto *asi = cast<AllocStackInst>(base.getBaseAddress());
    return MoveConstraint::forGuaranteed(
        !asi->getUsersOfType<StoreBorrowInst>().empty());
  }
  case AccessRepresentation::Kind::Global:
    // A global can be consumed if it's reinitialized.
    return MoveConstraint::RequiresReinit;
  case AccessRepresentation::Kind::Class:
    // A class field can be consumed if it's reinitialized.
    return MoveConstraint::RequiresReinit;
  case AccessRepresentation::Kind::Tail:
    // A class field can be consumed if it's reinitialized.
    return MoveConstraint::RequiresReinit;
  case AccessRepresentation::Kind::Argument: {
    // An indirect argument is guaranteed if it's @in_guaranteed.
    auto *arg = base.getArgument();
    return MoveConstraint::forGuaranteed(
        arg->getArgumentConvention().isGuaranteedConvention());
  }
  case AccessRepresentation::Kind::Yield: {
    auto baseAddr = base.getBaseAddress();
    auto *bai = cast<BeginApplyInst>(
        cast<MultipleValueInstructionResult>(baseAddr)->getParent());
    auto index = *bai->getIndexOfResult(baseAddr);
    auto info = bai->getSubstCalleeConv().getYieldInfoForOperandIndex(index);
    return MoveConstraint::forGuaranteed(!info.isConsumed());
  }
  case AccessRepresentation::Kind::Nested: {
    auto *bai = cast<BeginAccessInst>(base.getBaseAddress());
    if (bai->getAccessKind() == SILAccessKind::Init ||
        bai->getAccessKind() == SILAccessKind::Read)
      return MoveConstraint::Illegal;
    // Allow moves from both modify and deinit.
    return MoveConstraint::None;
  }
  case AccessRepresentation::Kind::Unidentified:
    // Conservatively reject for now.
    return MoveConstraint::Illegal;
  }
}

// Returns true if we emitted a diagnostic and handled the single block
// case. Returns false if we visited all of the uses and seeded the UseState
// struct with the information needed to perform our interprocedural dataflow.
bool ConsumeOperatorCopyableAddressesChecker::performSingleBasicBlockAnalysis(
    SILValue address, DebugVarCarryingInst addressDebugInst,
    MarkUnresolvedMoveAddrInst *mvi) {
  if (getMoveConstraint(mvi->getSrc()).isIllegal()) {
    auto &astCtx = mvi->getFunction()->getASTContext();
    StringRef name = getDebugVarName(address);
    diagnose(astCtx, getSourceLocFromValue(address),
             diag::sil_movechecking_guaranteed_value_consumed, name);
    diagnose(astCtx, mvi->getLoc().getSourceLoc(),
             diag::sil_movechecking_consuming_use_here);

    // Replace the marker instruction with a copy_addr to avoid subsequent
    // diagnostics.
    SILBuilderWithScope builder(mvi);
    builder.createCopyAddr(mvi->getLoc(), mvi->getSrc(), mvi->getDest(),
                           IsNotTake, IsInitialization);
    mvi->eraseFromParent();

    return true;
  }
  // First scan downwards to make sure we are move out of this block.
  auto &useState = dataflowState.useState;
  auto &applySiteToPromotedArgIndices =
      dataflowState.applySiteToPromotedArgIndices;
  auto &closureConsumes = dataflowState.closureConsumes;

  SILInstruction *interestingUser = nullptr;
  Operand *interestingUse = nullptr;
  TinyPtrVector<SILInstruction *> interestingClosureUsers;
  switch (downwardScanForMoveOut(mvi, useState, &interestingUser,
                                 &interestingUse, interestingClosureUsers)) {
  case DownwardScanResult::Invalid:
    llvm_unreachable("invalid");
  case DownwardScanResult::Destroy: {
    assert(!interestingUse);
    assert(interestingUser);

    // If we found a destroy, then we found a single block case that we can
    // handle. Remove the destroy and convert the mark_unresolved_move_addr
    // into a true move.
    auto *dvi = cast<DestroyAddrInst>(interestingUser);
    SILBuilderWithScope builder(mvi);
    builder.createCopyAddr(mvi->getLoc(), mvi->getSrc(), mvi->getDest(), IsTake,
                           IsInitialization);
    // Also, mark the alloc_stack as being moved at some point.
    if (addressDebugInst) {
      if (auto varInfo = addressDebugInst.getVarInfo()) {
        SILBuilderWithScope undefBuilder(builder);
        undefBuilder.setCurrentDebugScope(addressDebugInst->getDebugScope());
        undefBuilder.createDebugValue(addressDebugInst->getLoc(),
                                      SILUndef::get(address), *varInfo, false,
                                      UsesMoveableValueDebugInfo);
      }
      addressDebugInst.markAsMoved();
    }

    useState.destroys.erase(dvi);
    mvi->eraseFromParent();
    dvi->eraseFromParent();
    return false;
  }
  case DownwardScanResult::ClosureUse: {
    assert(interestingUse);
    assert(interestingUser);

    // Then check if we found a user that violated our dataflow rules. In such
    // a case, emit an error, cleanup our mark_unresolved_move_addr, and
    // finally continue.
    auto &astCtx = mvi->getFunction()->getASTContext();
    {
      auto diag =
          diag::sil_movechecking_value_used_after_consume;
      StringRef name = getDebugVarName(address);
      diagnose(astCtx, getSourceLocFromValue(address), diag, name);
    }

    auto diag = diag::sil_movechecking_consuming_use_here;
    if (auto sourceLoc = mvi->getLoc().getSourceLoc()) {
      diagnose(astCtx, sourceLoc, diag);
    }

    {
      auto diag = diag::sil_movechecking_nonconsuming_use_here;
      for (auto *user : interestingClosureUsers) {
        if (auto sourceLoc = user->getLoc().getSourceLoc()) {
          diagnose(astCtx, sourceLoc, diag);
        }
      }
    }

    // We purposely continue to see if at least in simple cases, we can flag
    // mistakes from other moves. Since we are setting emittedDiagnostic to
    // true, we will not perform the actual dataflow due to a check after
    // the loop.
    //
    // We also clean up mvi by converting it to a copy_addr init so we do not
    // emit fail errors later.
    //
    // TODO: Can we handle multiple errors in the same block for a single
    // move?
    SILBuilderWithScope builder(mvi);
    builder.createCopyAddr(mvi->getLoc(), mvi->getSrc(), mvi->getDest(),
                           IsNotTake, IsInitialization);
    mvi->eraseFromParent();
    return true;
  }
  case DownwardScanResult::UseForDiagnostic: {
    assert(!interestingUse);
    assert(interestingUser);

    // Then check if we found a user that violated our dataflow rules. In such
    // a case, emit an error, cleanup our mark_unresolved_move_addr, and
    // finally continue.
    auto &astCtx = mvi->getFunction()->getASTContext();
    {
      auto diag =
          diag::sil_movechecking_value_used_after_consume;
      StringRef name = getDebugVarName(address);
      diagnose(astCtx, getSourceLocFromValue(address), diag, name);
    }

    {
      auto diag = diag::sil_movechecking_consuming_use_here;
      if (auto sourceLoc = mvi->getLoc().getSourceLoc()) {
        diagnose(astCtx, sourceLoc, diag);
      }
    }

    {
      auto diag = diag::sil_movechecking_nonconsuming_use_here;
      if (auto sourceLoc = interestingUser->getLoc().getSourceLoc()) {
        diagnose(astCtx, sourceLoc, diag);
      }
    }

    // We purposely continue to see if at least in simple cases, we can flag
    // mistakes from other moves. Since we are setting emittedDiagnostic to
    // true, we will not perform the actual dataflow due to a check after
    // the loop.
    //
    // We also clean up mvi by converting it to a copy_addr init so we do not
    // emit fail errors later.
    //
    // TODO: Can we handle multiple errors in the same block for a single
    // move?
    SILBuilderWithScope builder(mvi);
    builder.createCopyAddr(mvi->getLoc(), mvi->getSrc(), mvi->getDest(),
                           IsNotTake, IsInitialization);
    mvi->eraseFromParent();
    return true;
  }
  case DownwardScanResult::Reinit: {
    assert(!interestingUse);
    assert(interestingUser);

    // If we have a reinit, then we have a successful move.
    convertMemoryReinitToInitForm(interestingUser);
    useState.reinits.erase(interestingUser);
    SILBuilderWithScope builder(mvi);
    builder.createCopyAddr(mvi->getLoc(), mvi->getSrc(), mvi->getDest(), IsTake,
                           IsInitialization);
    if (addressDebugInst) {
      if (auto varInfo = addressDebugInst.getVarInfo()) {
        {
          SILBuilderWithScope undefBuilder(builder);
          undefBuilder.setCurrentDebugScope(addressDebugInst->getDebugScope());
          undefBuilder.createDebugValue(addressDebugInst->getLoc(),
                                        SILUndef::get(address), *varInfo, false,
                                        UsesMoveableValueDebugInfo);
        }
        {
          // Make sure at the reinit point to create a new debug value after the
          // reinit instruction so we reshow the variable.
          auto *next = interestingUser->getNextInstruction();
          SILBuilderWithScope reinitBuilder(next);
          reinitBuilder.setCurrentDebugScope(addressDebugInst->getDebugScope());
          reinitBuilder.createDebugValue(addressDebugInst->getLoc(), address,
                                         *varInfo, false,
                                         UsesMoveableValueDebugInfo);
        }
      }
      addressDebugInst.markAsMoved();
    }
    mvi->eraseFromParent();
    return false;
  }
  case DownwardScanResult::ClosureConsume: {
    assert(interestingUse);
    assert(interestingUser);

    // If we found a closure consume, then we found a single block case that we
    // can handle. Remove the destroys/reinit, register the specific.
    SILBuilderWithScope builder(mvi);
    builder.createCopyAddr(mvi->getLoc(), mvi->getSrc(), mvi->getDest(), IsTake,
                           IsInitialization);

    // This is correct today due to us only supporting defer. When we handle
    // partial apply, we will need to do more work ehre.
    FullApplySite fas(interestingUser);
    assert(fas);
    auto &bitVector = applySiteToPromotedArgIndices[fas];
    auto conventions = fas.getSubstCalleeConv();
    unsigned numNonResultArgs = conventions.getNumSILArguments();
    if (bitVector.size() < numNonResultArgs)
      bitVector.resize(numNonResultArgs);
    bitVector.set(fas.getAppliedArgIndex(*interestingUse));
    for (auto *user : interestingClosureUsers) {
      closureConsumes.insert(user);
    }
    LLVM_DEBUG(llvm::dbgs() << "Found apply site to clone: " << **fas);
    LLVM_DEBUG(llvm::dbgs() << "BitVector: ";
               dumpBitVector(llvm::dbgs(), bitVector); llvm::dbgs() << '\n');
    if (addressDebugInst) {
      if (auto varInfo = addressDebugInst.getVarInfo()) {
        SILBuilderWithScope undefBuilder(builder);
        undefBuilder.setCurrentDebugScope(addressDebugInst->getDebugScope());
        undefBuilder.createDebugValue(addressDebugInst->getLoc(),
                                      SILUndef::get(address), *varInfo, false,
                                      UsesMoveableValueDebugInfo);
      }
      addressDebugInst.markAsMoved();
    }
    mvi->eraseFromParent();
    return false;
  }
  case DownwardScanResult::MoveOut:
    assert(!interestingUse);
    assert(!interestingUser);
    break;
  }

  // If we did not found any uses later in the block that was an interesting
  // use, we need to perform dataflow.
  LLVM_DEBUG(llvm::dbgs() << "Our move is live out, so we need to process "
                             "it with the dataflow.\n");
  dataflowState.markMovesThatPropagateDownwards.emplace_back(mvi);

  // Now scan up to see if mvi is also a use to seed the dataflow. This could
  // happen if we have an earlier move.
  if (upwardScanForUseOut(mvi, dataflowState.useState)) {
    LLVM_DEBUG(llvm::dbgs() << "MVI projects a use up");
    dataflowState.useBlocks[mvi->getParent()] = mvi;
  }
  return false;
}

bool ConsumeOperatorCopyableAddressesChecker::check(SILValue address) {
  auto accessPathWithBase = AccessPathWithBase::compute(address);
  auto accessPath = accessPathWithBase.accessPath;

  // Bail on an invalid AccessPath.
  //
  // AccessPath completeness is verified independently--it may be invalid in
  // extraordinary situations. When AccessPath is valid, we know all its uses
  // are recognizable.
  //
  // NOTE: If due to an invalid access path we fail here, we will just error
  // on the _move since the _move would not have been handled.
  if (!accessPath.isValid())
    return false;

  GatherLexicalLifetimeUseVisitor visitor(useState);
  SWIFT_DEFER { visitor.clear(); };
  visitor.reset(address);
  if (!visitAccessPathUses(visitor, accessPath, fn))
    return false;

  // See if our base address is an inout. If we found any moves, add as a
  // liveness use all function terminators.
  if (auto *fArg = dyn_cast<SILFunctionArgument>(address)) {
    if (fArg->hasConvention(SILArgumentConvention::Indirect_Inout)) {
      if (visitor.useState.markMoves.size()) {
        SmallVector<SILBasicBlock *, 2> exitingBlocks;
        fn->findExitingBlocks(exitingBlocks);
        for (auto *block : exitingBlocks) {
          visitor.useState.livenessUses.insert(block->getTerminator());
        }
      }
    }
  }

  // Now initialize our data structures.
  SWIFT_DEFER { dataflowState.clear(); };

  // First go through and perform dataflow on each of the closures our address
  // depends on. We do not have to worry about other unrelated addresses from
  // being passed to the defer in our argument slot since address phis are
  // banned in canonical SIL.
  //
  // This summary will let us treat the whole closure's effect on the closure
  // operand as if it was a single instruction.
  for (auto &pair : useState.closureUses) {
    auto *operand = pair.first;
    auto &closureState = pair.second;

    if (!performClosureDataflow(operand, closureState)) {
      LLVM_DEBUG(llvm::dbgs()
                 << "!! Early exit due to failing to analyze closure operand: "
                 << *operand->getUser());
      return false;
    }
  }

  // Perform the single basic block analysis emitting a diagnostic/pairing
  // mark_unresolved_move_addr and destroys if needed. If we discover a
  // mark_move that propagates its state out of the current block, this
  // routine also prepares the pass for running the multi-basic block
  // diagnostic.
  bool emittedSingleBBDiagnostic = false;

  // Before we process any moves, gather the debug inst associated with our
  // address.
  //
  // NOTE: The reason why we do this early is that we rely on our address
  // initially having a single DebugValueCarryingInst (either an alloc_stack
  // itself or a debug_value associated with an argument). If we do this while
  // processing, as we insert additional debug info we will cause this condition
  // to begin failing.
  auto addressDebugInst = DebugVarCarryingInst::getFromValue(address);

  for (auto *mvi : useState.markMoves) {
    LLVM_DEBUG(llvm::dbgs() << "Performing single block analysis on: " << *mvi);
    emittedSingleBBDiagnostic |=
        performSingleBasicBlockAnalysis(address, addressDebugInst, mvi);
  }

  if (emittedSingleBBDiagnostic) {
    LLVM_DEBUG(llvm::dbgs()
               << "Performed single block analysis and found error!\n");
    return true;
  }

  // Then check if we do not need to propagate down any mark moves. In that
  // case, since we did not emit an error but we did not have any
  if (dataflowState.markMovesThatPropagateDownwards.empty()) {
    LLVM_DEBUG(llvm::dbgs() << "Single block analysis handled all cases "
                               "without finding an error!\n");
    return true;
  }

  // Ok, we need to perform global dataflow for one of our moves. Initialize our
  // dataflow state engine and then run the dataflow itself.
  dataflowState.init();
  bool result =
      dataflowState.process(address, addressDebugInst, closureConsumes);
  return result;
}

//===----------------------------------------------------------------------===//
//                     MARK: Unsupported Use Case Errors
//===----------------------------------------------------------------------===//

namespace {

struct UnsupportedUseCaseDiagnosticEmitter {
  MarkUnresolvedMoveAddrInst *mai;

  ~UnsupportedUseCaseDiagnosticEmitter() {
    assert(!mai && "Didn't call cleanup!\n");
  }

  bool cleanup() && {
    // Now that we have emitted the error, replace the move_addr with a
    // copy_addr so that future passes never see it. We mark it as a
    // copy_addr [init].
    SILBuilderWithScope builder(mai);
    builder.createCopyAddr(mai->getLoc(), mai->getSrc(), mai->getDest(),
                           IsNotTake, IsInitialization);
    mai->eraseFromParent();
    mai = nullptr;
    return true;
  }

  ASTContext &getASTContext() const { return mai->getModule().getASTContext(); }

  void emitUnsupportedUseCaseError() const {
    auto diag =
        diag::sil_movekillscopyablevalue_move_applied_to_unsupported_move;
    diagnose(getASTContext(), mai->getLoc().getSourceLoc(), diag);
  }

  /// Try to pattern match if we were trying to move a global. In such a case,
  /// emit a better error.
  bool tryEmitCannotConsumeNonLocalMemoryError() const {
    auto src = stripAccessMarkers(mai->getSrc());

    if (auto *gai = dyn_cast<GlobalAddrInst>(src)) {
      auto diag = diag::sil_movekillscopyable_move_applied_to_nonlocal_memory;
      diagnose(getASTContext(), mai->getLoc().getSourceLoc(), diag, 0);
      return true;
    }

    // If we have a project_box, then we must have an escaping capture. It is
    // the only case that allocbox to stack doesn't handle today.
    if (isa<ProjectBoxInst>(src)) {
      auto diag = diag::sil_movekillscopyable_move_applied_to_nonlocal_memory;
      diagnose(getASTContext(), mai->getLoc().getSourceLoc(), diag, 1);
      return true;
    }

    return false;
  }

  void emit() const {
    if (tryEmitCannotConsumeNonLocalMemoryError())
      return;
    emitUnsupportedUseCaseError();
  }
};

} // namespace

//===----------------------------------------------------------------------===//
//                            Top Level Entrypoint
//===----------------------------------------------------------------------===//

namespace {

class ConsumeOperatorCopyableAddressesCheckerPass
    : public SILFunctionTransform {
  void run() override {
    auto *fn = getFunction();

    // Don't rerun diagnostics on deserialized functions.
    if (getFunction()->wasDeserializedCanonical())
      return;

    assert(fn->getModule().getStage() == SILStage::Raw &&
           "Should only run on Raw SIL");

    llvm::SmallSetVector<SILValue, 32> addressesToCheck;

    for (auto *arg : fn->front().getSILFunctionArguments()) {
      if (arg->getType().isAddress() &&
          (arg->hasConvention(SILArgumentConvention::Indirect_In) ||
           arg->hasConvention(SILArgumentConvention::Indirect_In_Guaranteed) ||
           arg->hasConvention(SILArgumentConvention::Indirect_Inout) ||
           arg->hasConvention(SILArgumentConvention::Indirect_InoutAliasable)))
        addressesToCheck.insert(arg);
    }

    for (auto &block : *fn) {
      for (auto ii = block.begin(), ie = block.end(); ii != ie;) {
        auto *inst = &*ii;
        ++ii;

        if (auto *asi = dyn_cast<AllocStackInst>(inst)) {
          // Only check var_decl alloc_stack insts.
          if (asi->isFromVarDecl()) {
            LLVM_DEBUG(llvm::dbgs() << "Found lexical alloc_stack: " << *asi);
            addressesToCheck.insert(asi);
            continue;
          }
        }
      }
    }

    LLVM_DEBUG(llvm::dbgs() << "Visiting Function: " << fn->getName() << "\n");
    auto addressToProcess =
        llvm::ArrayRef(addressesToCheck.begin(), addressesToCheck.end());

    SILOptFunctionBuilder funcBuilder(*this);

    ConsumeOperatorCopyableAddressesChecker checker(getFunction(), funcBuilder);

    bool madeChange = false;
    while (!addressToProcess.empty()) {
      auto address = addressToProcess.front();
      addressToProcess = addressToProcess.drop_front(1);
      LLVM_DEBUG(llvm::dbgs() << "Visiting: " << *address);
      madeChange |= checker.check(address);
    }

    if (madeChange) {
      invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
    }

    // Now go through and clone any apply sites that we need to clone.
    SmallVector<SILValue, 8> newArgs;
    bool rewroteCallee = false;
    for (auto &pair : checker.applySiteToPromotedArgIndices) {
      SWIFT_DEFER { newArgs.clear(); };
      auto fas = pair.first;
      auto &bitVector = pair.second;
      LLVM_DEBUG(llvm::dbgs() << "CLONING APPLYSITE: " << **fas);
      LLVM_DEBUG(llvm::dbgs() << "BitVector: ";
                 dumpBitVector(llvm::dbgs(), bitVector); llvm::dbgs() << '\n');
      checker.cloneDeferCalleeAndRewriteUses(newArgs, bitVector, fas,
                                             checker.closureConsumes);
      rewroteCallee = true;
    }
    if (rewroteCallee)
      invalidateAnalysis(SILAnalysis::InvalidationKind::CallsAndInstructions);

    // Now search through our function one last time and any move_value
    // [allows_diagnostics] that remain are ones that we did not know how to
    // check so emit a diagnostic so the user doesn't assume that they have
    // guarantees. This gives us the guarantee that any moves written by the
    // user must have been properly resolved and thus maintain that all move
    // uses have been resolved appropriately.
    //
    // TODO: Emit specific diagnostics here (e.x.: _move of global).
    if (DisableUnhandledConsumeOperator)
      return;

    bool lateMadeChange = false;
    for (auto &block : *fn) {
      for (auto ii = block.begin(), ie = block.end(); ii != ie;) {
        auto *inst = &*ii;
        ++ii;

        if (auto *mai = dyn_cast<MarkUnresolvedMoveAddrInst>(inst)) {
          UnsupportedUseCaseDiagnosticEmitter emitter{mai};
          emitter.emit();
          std::move(emitter).cleanup();
          lateMadeChange = true;
        }
      }
    }
    if (lateMadeChange)
      invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
  }
};

} // anonymous namespace

SILTransform *swift::createConsumeOperatorCopyableAddressesChecker() {
  return new ConsumeOperatorCopyableAddressesCheckerPass();
}