rucc-opt 0.10.74

The pass manager, the acyclic e-graph, the rewrite rules and the analyses.
Documentation
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
//! Alias analysis: whether two memory references can touch the same byte.
//!
//! Design: `spec/optimizer/08-alias-analysis.md`, with the switch section 41.9 of
//! `spec/optimizer/41-correctness.md` asks for.
//!
//! # The one question
//!
//! There is one primitive and everything else is built on it. Given two memory references, can
//! they touch the same byte. Every memory optimization documents 16, 17 and 27 will bring is
//! gated on it, an answer that is too conservative costs performance quietly and forever, and an
//! answer that is too aggressive miscompiles in the way that produces a bug report three years
//! later from somebody whose program worked on every other compiler.
//!
//! So the answer is an [`Answer`], which is either [`Answer::May`] or a no carrying the layer
//! that concluded it. Section 8.5 asks for that and it is the best decision in spec 9.4: a
//! miscompilation from an alias bug is localised to one layer rather than bisected across the
//! whole analysis, the layer statistics come for free, and a user asking why something was not
//! optimized gets a real answer. It costs one byte in a return value that was going in a
//! register anyway.
//!
//! # The layers, in the order they run
//!
//! Section 8.2 lists six. This is the first five, and the order they run in is load bearing.
//!
//! **Two volatile accesses conflict**, and that is checked before anything else. Not may
//! conflict: they are treated as conflicting so that neither can be moved across the other,
//! which is what `volatile` is for.
//!
//! **Distinct storage and provenance**, layers 1 and 2, are one walk here because the IR names
//! the object a pointer came from. [`origin`] chases a pointer back through `ptr_add` and
//! `bitcast` to the `alloca` or the `global_addr` it started at, and two different objects never
//! alias. GCC gets the same answer less directly, out of tracking base declarations through a
//! tree walk. This layer answers a startling fraction of the queries real code asks and it is
//! the only one `-O1` needs.
//!
//! **Offsets**, layer 4, run next and only for two references to the same object, and running
//! them before the type-based layer rather than after is the whole of what makes union type
//! punning work. Writing through one member of a union and reading another is two accesses to
//! one object at overlapping offsets with unrelated types. It is undefined in ISO C, it is
//! defined by GCC, an enormous amount of real C rests on it, and a layer that asked about the
//! types first would answer no and miscompile all of it. GCC's comment at
//! `gcc/tree-ssa-alias.cc:2461` says exactly this and rucc reproduces the ordering rather than
//! the accident.
//!
//! **Escape**, which section 8.4 counts as the cheapest interprocedural-flavoured fact there is:
//! a local whose address never leaves the function is not the object some pointer this function
//! cannot follow is pointing at, and it is not one a call can touch either.
//!
//! **`restrict`**, layer 5, is two small numbers on the access and one comparison, which is all
//! GCC's is. See [`rucc_ir::Restrict`], including the trap.
//!
//! **Type-based aliasing**, layer 3, runs last of the five. Two accesses conflict when one of
//! their type nodes is at or above the other in the metadata tree, so an access through `char`,
//! whose node is the root, conflicts with everything. `-fno-strict-aliasing` is one condition in
//! one place, [`Options::strict_aliasing`], which is what section 41.9 means by the flag having
//! to actually work.
//!
//! Layer 6 is points-to, and it is not here. It is a module-wide fixed point rather than a fact
//! the IR already carries, section 8.3 has an open question about which solver it should be, and
//! section 8.6 is emphatic that provenance and points-to are different things that must not be
//! confused. So [`Origin`] is provenance, there is no points-to type for it to be converted
//! into, and the solver lands separately with the constraint generator split out from it the way
//! GCC 16 split its own.
//!
//! # What the front end still owes this
//!
//! Layer 3 is fed. `rucc_lower::aliasing` builds the tree and every load and every store an access
//! through a C type becomes carries the node for that type, keyed on a canonical spelling rather
//! than on the order the walk met it, which is what section 8.2 asks for so that document 35's LTO
//! does not silently gain disambiguations when two modules are merged. The tree is one level deep:
//! `char` is the root and every other scalar hangs under it, so a struct member is not yet
//! separated from the struct it is in. A member of a union carries the root rather than the node
//! for its own type, which this layer would not have needed, since layer 4 runs first and settles
//! it. It is there for the type plane, which has no layer 4, and it costs this layer nothing but a
//! disambiguation between a union member and an unrelated object of a different scalar type.
//!
//! Layer 5 is fed for the accesses that go through a `restrict` parameter, which is where the
//! qualifier is nearly always written and which the front end works out. A `restrict`
//! pointer declared inside a block does not carry one yet, which is tamnd/rucc#970, and neither
//! does an access through a pointer that came out of memory, which is not a question about names
//! and never will be.

use std::collections::HashSet;

use rucc_base::Symbol;
use rucc_ir::{
    AttrSet, Attrs, Def, Extra, Flags, Func, Imm, Inst, MemInfo, Meta, Opcode, Restrict, Type,
    Value,
};

use crate::modref::Summaries;
use crate::outside::Outside;

/// How far back through address arithmetic a pointer is chased before the answer is given up on.
///
/// The chain from an `alloca` to the address a load uses is two or three instructions in
/// anything a person writes. The limit is here so that a generated function with a thousand
/// `ptr_add`s in a row costs a bounded amount, and giving up produces an unknown origin, which
/// is the conservative answer rather than a wrong one.
const CHASE_LIMIT: u32 = 64;

/// How far up the metadata tree a type node is followed.
///
/// The tree is shallow, and the verifier is what would catch one that is not a tree at all. The
/// limit means a query cannot fail to terminate even on a module that came from somewhere the
/// verifier has not run.
const TREE_LIMIT: u32 = 32;

/// Which rule concluded that two references cannot touch the same byte.
///
/// Section 8.5. This is the whole point of the return type being an enum rather than a boolean.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Reason {
    /// They are references to two different objects, which is layers 1 and 2 together.
    Distinct,
    /// One is a local whose address never leaves the function and the other is not that local.
    Escape,
    /// They are references to one object at offsets whose byte ranges do not overlap.
    Offset,
    /// Their type nodes are in different parts of the tree, so no object has both types.
    Tbaa,
    /// They are in one `restrict` scope through different `restrict` pointers.
    Restrict,
    /// The callee's attributes say it does not touch memory this way.
    Attribute,
    /// What the callee does to memory was worked out from its body, and it does not do this.
    Summary,
    /// One of them touches only the safety planes, which nothing the program can name reaches.
    Plane,
}

impl Reason {
    /// Every reason, which is what a report walks.
    pub const ALL: [Self; 8] = [
        Self::Distinct,
        Self::Escape,
        Self::Offset,
        Self::Tbaa,
        Self::Restrict,
        Self::Attribute,
        Self::Summary,
        Self::Plane,
    ];

    /// How many there are, which is the width of a [`Counts`].
    pub const COUNT: usize = Self::ALL.len();

    /// Where this sits in [`Reason::ALL`].
    #[must_use]
    pub const fn index(self) -> usize {
        match self {
            Self::Distinct => 0,
            Self::Escape => 1,
            Self::Offset => 2,
            Self::Tbaa => 3,
            Self::Restrict => 4,
            Self::Attribute => 5,
            Self::Summary => 6,
            Self::Plane => 7,
        }
    }

    /// The one word `-fdump-alias` prints for it.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Distinct => "distinct",
            Self::Escape => "escape",
            Self::Offset => "offset",
            Self::Tbaa => "tbaa",
            Self::Restrict => "restrict",
            Self::Attribute => "attribute",
            Self::Summary => "summary",
            Self::Plane => "plane",
        }
    }

    /// The sentence a user gets when they ask why something was not optimized.
    #[must_use]
    pub const fn describe(self) -> &'static str {
        match self {
            Self::Distinct => "they are two different objects",
            Self::Escape => "the address of that local never leaves this function",
            Self::Offset => "they are parts of one object that do not overlap",
            Self::Tbaa => "no object has both of those types",
            Self::Restrict => "restrict says those two pointers do not reach the same object",
            Self::Attribute => "the callee is declared not to touch memory that way",
            Self::Summary => "what that callee does to memory was worked out, and it does not",
            Self::Plane => "that one touches only the planes, which the program cannot name",
        }
    }
}

/// What the analysis answers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Answer {
    /// They may touch the same byte, which is the answer whenever nothing proved otherwise.
    May,
    /// They cannot, and this is the rule that says so.
    No(Reason),
}

impl Answer {
    /// Whether this is a no.
    #[must_use]
    pub const fn is_no(self) -> bool {
        matches!(self, Self::No(_))
    }

    /// The rule behind a no.
    #[must_use]
    pub const fn reason(self) -> Option<Reason> {
        match self {
            Self::No(reason) => Some(reason),
            Self::May => None,
        }
    }
}

/// What the command line turns off.
///
/// One field, because there is one flag. Section 41.9 asks that `-fno-strict-aliasing` disable
/// the type-based component and nothing else, exactly as `gcc/alias.cc:420` and :556 do, and the
/// way to make that true rather than hoped for is to have one condition in one place.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Options {
    /// Whether the type-based layer is consulted. GCC's default at `-O2` is on and rucc matches
    /// it, so `-fno-strict-aliasing` is what clears this.
    pub strict_aliasing: bool,
}

impl Default for Options {
    fn default() -> Self {
        Self { strict_aliasing: true }
    }
}

/// Where a pointer came from, as far as this function can tell.
///
/// This is provenance and it is not points-to. Provenance says which object a pointer was
/// derived from, which the IR knows locally and cheaply. Points-to says which objects a pointer
/// might hold at run time, which needs a module-wide fixed point. Section 8.6 lists confusing
/// the two as one of the ways this analysis goes wrong, so there is no conversion between them
/// and there is no points-to type here at all.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Origin {
    /// An `alloca` in this function, which is storage nothing outside it knew about until the
    /// address was handed out.
    Local(Inst),
    /// A named object, by the symbol its address was taken by.
    Global(Symbol),
    /// An address this function cannot follow any further back: a parameter, something loaded
    /// out of memory, what a call returned, or an integer turned into a pointer.
    Unknown(Value),
}

impl Origin {
    /// Whether this names an object rather than an address of unknown origin.
    #[must_use]
    pub const fn is_object(self) -> bool {
        matches!(self, Self::Local(_) | Self::Global(_))
    }
}

/// Where a pointer came from, and how many bytes past the start of it the pointer is.
///
/// The offset is `None` when the walk passed arithmetic whose amount is not a constant, which
/// costs the offset layer and nothing else: the origin is still the origin, because adding an
/// unknown number of bytes to a pointer does not move it to a different object.
#[must_use]
pub fn origin(func: &Func, mut value: Value) -> (Origin, Option<i64>) {
    let mut offset = Some(0i64);
    for _ in 0..CHASE_LIMIT {
        let Def::Result { inst, .. } = func[value].def else {
            // A block parameter, which is where the address arrived from somewhere else.
            return (Origin::Unknown(value), offset);
        };
        let data = func[inst];
        match data.opcode {
            Opcode::Alloca => return (Origin::Local(inst), offset),
            Opcode::GlobalAddr => {
                let Extra::Symbol(name) = data.extra else {
                    return (Origin::Unknown(value), offset);
                };
                return (Origin::Global(name), offset);
            }
            Opcode::PtrAdd => {
                let args = &func[data.args];
                let (base, by) = (args[0], args[1]);
                offset = offset
                    .and_then(|so_far| Some((so_far, constant(func, by)?)))
                    .and_then(|(so_far, by)| so_far.checked_add(by));
                value = base;
            }
            // A cast between two pointers moves nothing, so it is the same address as its
            // operand and the walk goes through it.
            Opcode::Bitcast => value = func[data.args][0],
            // A capability is about the object its pointer is in, so the object at the end of
            // this walk is the same object either way. It is not an address and nothing loads
            // through one, so this is never the origin of an access. What it is for is the
            // escape analysis: once the walk gets here, a use of a capability that could let the
            // object out is a use this function can see, and [`keeps_address`] is what decides
            // which uses those are.
            Opcode::CapOf => value = func[data.args][0],
            _ => return (Origin::Unknown(value), offset),
        }
    }
    (Origin::Unknown(value), None)
}

/// One memory reference: which bytes an instruction touches and what it says about them.
///
/// Built by [`Alias::reads`] and [`Alias::writes`] rather than by hand, so that the size of a
/// load comes from the type it produces and the size of a `memcpy` comes from its access, and no
/// caller has to remember which.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Access {
    /// The object, or the address the walk stopped at.
    pub origin: Origin,
    /// How many bytes past the start of that the reference begins, when the walk could tell.
    pub offset: Option<i64>,
    /// How many bytes it covers, when that is known.
    pub size: Option<u64>,
    /// The type node the front end attached, if it attached one.
    pub tbaa: Option<Meta>,
    /// The `restrict` scope the access is in.
    pub restrict: Restrict,
    /// Whether the access is `volatile`.
    pub volatile: bool,
}

impl Access {
    /// A reference to somewhere behind this address, of unknown size and with nothing known
    /// about its type.
    ///
    /// This is what a pointer handed to a call is: the call touches something through it and
    /// there is nothing on the call saying how much.
    #[must_use]
    pub fn through(func: &Func, pointer: Value) -> Self {
        let (origin, offset) = origin(func, pointer);
        Self { origin, offset, size: None, tbaa: None, restrict: Restrict::NONE, volatile: false }
    }

    /// The half-open range of bytes this covers within its origin, when both ends are known.
    #[must_use]
    pub fn range(&self) -> Option<(i128, i128)> {
        let (offset, size) = (self.offset?, self.size?);
        let start = i128::from(offset);
        Some((start, start + i128::from(size)))
    }
}

/// Which of a function's locals had their address leave it.
///
/// Section 8.4 calls this the most valuable interprocedural-flavoured fact available without
/// interprocedural analysis, because it covers every local a C programmer takes the address of
/// only to pass one field of, and because a local whose address never escaped cannot be touched
/// by any call at all.
///
/// Section 8.6 says how it goes wrong, which is by missing an escape, and what to do about it.
/// [`keeps_address`] is a whitelist: an opcode it does not name lets the address out, and so
/// does an opcode added to the IR after this was written. A blacklist would mean the next person
/// to add an opcode introduces a miscompilation without touching this file.
#[derive(Clone, Debug, Default)]
pub struct Escapes {
    escaped: HashSet<Inst>,
}

impl Escapes {
    /// Works out which locals of this function escaped it.
    #[must_use]
    pub fn of(func: &Func) -> Self {
        Self::with(func, |_, _| false)
    }

    /// The same, given what the functions this one calls do to what they are handed.
    ///
    /// Section 34.6 calls this the upgrade the mod and ref summary makes possible: the question
    /// goes from does the address leave this function to does the address leave this function
    /// given what the callees do. An address handed to a call is an address gone as far as
    /// [`Escapes::of`] is concerned, and that is most of what a C program does with the address
    /// of a local, so a callee whose summary says it keeps nothing takes a whole class of locals
    /// out of the escaped set and every question about them afterwards is answered.
    ///
    /// Note what this does to the reader of the answer. The invariant that a call reaching the
    /// escape layer of the oracle cannot have been handed the address does not hold any more, so
    /// that layer asks whether this call was handed it rather than assuming not.
    #[must_use]
    pub fn knowing(func: &Func, summaries: &Summaries) -> Self {
        Self::with(func, |inst, index| {
            summaries.at(func, inst).is_some_and(|summary| !summary.param(index).escapes)
        })
    }

    /// The same, where `kept` says which operands of which calls hand the address to something
    /// that does not let it out. For [`crate::modref`], whose own answers are still moving while
    /// it asks and which therefore cannot hand over a finished [`Summaries`].
    #[must_use]
    pub fn with(func: &Func, kept: impl Fn(Inst, usize) -> bool) -> Self {
        let mut escaped = HashSet::new();
        for block in func.blocks() {
            for inst in func.insts(block) {
                let data = func[inst];
                for (index, &arg) in func[data.args].iter().enumerate() {
                    if keeps_address(data.opcode, index) || kept(inst, index) {
                        continue;
                    }
                    if let (Origin::Local(local), _) = origin(func, arg) {
                        escaped.insert(local);
                    }
                }
                // What a branch passes to a block parameter, which is where an address stops
                // being one this function can follow back to anything.
                for call in func.successors(inst) {
                    for &arg in &func[call.args] {
                        if let (Origin::Local(local), _) = origin(func, arg) {
                            escaped.insert(local);
                        }
                    }
                }
            }
        }
        Self { escaped }
    }

    /// Whether the address of this `alloca` left the function.
    #[must_use]
    pub fn escaped(&self, local: Inst) -> bool {
        self.escaped.contains(&local)
    }

    /// How many locals escaped.
    #[must_use]
    pub fn count(&self) -> usize {
        self.escaped.len()
    }
}

/// Whether a use of a pointer at this operand leaves the address inside the function.
///
/// A whitelist, per section 8.6, and the reason it is written this way is in [`Escapes`].
#[must_use]
pub const fn keeps_address(opcode: Opcode, index: usize) -> bool {
    match (opcode, index) {
        // Dereferenced, and the address itself goes nowhere.
        (Opcode::Load | Opcode::AtomicLoad, 0)
        | (Opcode::Store | Opcode::AtomicStore, 1)
        | (Opcode::AtomicRmw | Opcode::Cmpxchg, 0)
        | (Opcode::Memcpy | Opcode::Memmove, 0 | 1)
        | (Opcode::Memset | Opcode::Prefetch, 0) => true,
        // Copied, and the copy's own uses are walked in their turn, because the walk in
        // [`origin`] goes back through both of these.
        (Opcode::PtrAdd | Opcode::Bitcast, 0) => true,
        // Comparing two addresses neither reads them nor keeps them. Note that the answer may
        // not travel the other way: see [`rucc_ir::Restrict::disjoint`].
        (Opcode::ICmp, 0 | 1) => true,
        // A plane access takes the address as the row to look up and not as somewhere to put it.
        // [`Opcode::touches_only_planes`] is the argument, and what matters here is the last part
        // of it: the storage these reach is the runtime's, and no name in the program reaches one,
        // so nothing the program can run afterwards can get at the object through what one of them
        // did. Every operand, because every pointer one of them takes is a locator.
        (op, _) if op.touches_only_planes() => true,
        // The aux pair reaches the runtime's storage the same way, and the operands named here are
        // the ones that say which slot rather than the ones that say what goes in it. `cap_load`
        // takes the capability of the object the word is in and the address of the word.
        // `cap_store` takes those two as well, and its other two are the pointer being written and
        // that pointer's own capability, which are the thing being put somewhere a later `cap_load`
        // can read, so they are not here. `cap_copy` is not here either, and for the opposite
        // reason: every one of its operands is a locator, so it is above under the arm that takes
        // all of them.
        (Opcode::CapLoad | Opcode::CapStore, 0 | 1) => true,
        // Asking what object a pointer is in is not letting the pointer out. The capability that
        // comes back is about the object and the walk in [`origin`] goes through it, which is
        // what makes this safe: a use of the capability that could let the object out is a use
        // that arrives back here under its own opcode, and the ones that can are not in this
        // list. `cap_store` is above for the operand that takes a capability as a locator, so what
        // is left out is its other one, which hands a capability over to be written down, and then
        // `cap_narrow`, which makes a second capability from it, and `cap_recover`, which is the
        // road back to a usable pointer.
        (Opcode::CapOf, 0) => true,
        _ => false,
    }
}

/// How many queries each layer answered.
///
/// Section 8.5 says these come for free once the answer carries its reason, and section 8.3
/// wants them, because a layer that answers no on almost nothing is a layer to delete rather
/// than a layer to improve.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Counts {
    queries: u64,
    answered: [u64; Reason::COUNT],
}

impl Counts {
    /// How many queries were asked.
    #[must_use]
    pub const fn queries(&self) -> u64 {
        self.queries
    }

    /// How many of them this layer answered no.
    #[must_use]
    pub const fn answered(&self, reason: Reason) -> u64 {
        self.answered[reason.index()]
    }

    /// How many were answered no by any layer.
    #[must_use]
    pub fn total(&self) -> u64 {
        self.answered.iter().sum()
    }
}

/// The analysis over one function.
///
/// It borrows the function because nearly everything it asks is a question about one, and it
/// borrows an [`Outside`] because the rest is a question about the module: whether two symbols are
/// two objects, what a callee is declared to do, where a type node sits in the tree, and how wide
/// an address is. That is a copy of four module facts rather than the module itself, so that a
/// pass handed `&mut module[id]` can still build this. See [`crate::outside`] for why.
///
/// The escape analysis is run once when this is built, since every query may ask it and it is one
/// walk over the function.
#[derive(Debug)]
pub struct Alias<'a> {
    func: &'a Func,
    outside: &'a Outside,
    summaries: Option<&'a Summaries>,
    options: Options,
    escapes: Escapes,
    counts: Counts,
}

impl<'a> Alias<'a> {
    /// The analysis of this function, with the type-based layer on, which is GCC's `-O2`.
    #[must_use]
    pub fn new(func: &'a Func, outside: &'a Outside) -> Self {
        Self::with(func, outside, Options::default())
    }

    /// The same, with the type-based layer where the command line left it.
    #[must_use]
    pub fn with(func: &'a Func, outside: &'a Outside, options: Options) -> Self {
        Self {
            func,
            outside,
            summaries: None,
            options,
            escapes: Escapes::of(func),
            counts: Counts::default(),
        }
    }

    /// The same, with what the whole module's functions were worked out to do to memory.
    ///
    /// Without this the only thing known about a call is what somebody declared about it, which
    /// for most of a real translation unit is nothing. With it, a call to a function in the same
    /// unit is answered from what that function's body actually does. See [`crate::modref`].
    #[must_use]
    pub fn knowing(mut self, summaries: &'a Summaries) -> Self {
        self.escapes = Escapes::knowing(self.func, summaries);
        self.summaries = Some(summaries);
        self
    }

    /// Which locals escaped, for a caller that wants the fact on its own.
    #[must_use]
    pub const fn escapes(&self) -> &Escapes {
        &self.escapes
    }

    /// What each layer has answered so far.
    #[must_use]
    pub const fn counts(&self) -> &Counts {
        &self.counts
    }

    /// The bytes this instruction reads, if it reads any.
    #[must_use]
    pub fn reads(&self, inst: Inst) -> Option<Access> {
        let data = self.func[inst];
        let args = &self.func[data.args];
        let info = self.mem(inst);
        let (pointer, size) = match data.opcode {
            Opcode::Load | Opcode::AtomicLoad => (args[0], self.width(self.result_type(inst)?)),
            // A copy reads its source, which is its second operand, for the size on the access.
            // The size is not known where the program works the length out, and an access of no
            // known size is one every other access here may touch, which is the honest answer.
            Opcode::Memcpy | Opcode::Memmove => (args[1], self.bytes(inst, info?)),
            // A read-modify-write reads and writes the same bytes, and the width is the width
            // of what it operates with.
            Opcode::AtomicRmw => (args[0], self.width(self.func[args[1]].ty)),
            Opcode::Cmpxchg => (args[0], self.width(self.func[args[1]].ty)),
            Opcode::VaObject => (args[0], Some(info?.size)),
            _ => return None,
        };
        Some(self.access(pointer, size, info, data.flags))
    }

    /// How many bytes a bulk operation covers, where that is a number at all.
    ///
    /// One whose length the program works out has no number here, and `None` is what an access of
    /// unknown size is written as everywhere else in this file. It matters that this is not the
    /// payload's zero: a zero byte access is one nothing overlaps, so reading the payload on this
    /// shape would say a copy touches nothing rather than that it may touch anything.
    fn bytes(&self, inst: Inst, info: MemInfo) -> Option<u64> {
        match self.func.bulk(inst) {
            Some(bulk) if bulk.length.is_some() => None,
            _ => Some(info.size),
        }
    }

    /// The bytes this instruction writes, if it writes any.
    #[must_use]
    pub fn writes(&self, inst: Inst) -> Option<Access> {
        let data = self.func[inst];
        let args = &self.func[data.args];
        let info = self.mem(inst);
        let (pointer, size) = match data.opcode {
            Opcode::Store | Opcode::AtomicStore => (args[1], self.width(self.func[args[0]].ty)),
            Opcode::Memcpy | Opcode::Memmove | Opcode::Memset => (args[0], self.bytes(inst, info?)),
            Opcode::AtomicRmw | Opcode::Cmpxchg => (args[0], self.width(self.func[args[1]].ty)),
            _ => return None,
        };
        Some(self.access(pointer, size, info, data.flags))
    }

    /// Whether these two references can touch the same byte.
    pub fn query(&mut self, a: &Access, b: &Access) -> Answer {
        self.counts.queries += 1;
        let answer = self.decide(a, b);
        if let Answer::No(reason) = answer {
            self.counts.answered[reason.index()] += 1;
        }
        answer
    }

    /// Whether this call can write the bytes the reference covers.
    ///
    /// GCC's `call_may_clobber_ref_p_1`. Three things answer it and they are asked in that
    /// order: the escape analysis, which is the cheap one and needs nothing outside this
    /// function; the attributes a C programmer already wrote, which are section 8.4's; and the
    /// mod and ref summaries of document 34, which are what the same three questions look like
    /// when the callee's body is read rather than taken on trust. Without the last of those the
    /// honest answer for anything whose address escaped was yes, and `crate::modref` is where it
    /// stopped being. All three are in `Alias::decide_call`, which is also what
    /// [`Alias::read_by`] asks.
    pub fn clobbered_by(&mut self, reference: &Access, call: Inst) -> Answer {
        self.touched_by(reference, call, true)
    }

    /// Whether this call can read them.
    ///
    /// GCC's `ref_maybe_used_by_call_p_1`, and the same argument as [`Alias::clobbered_by`].
    pub fn read_by(&mut self, reference: &Access, call: Inst) -> Answer {
        self.touched_by(reference, call, false)
    }

    // The layers.

    fn decide(&self, a: &Access, b: &Access) -> Answer {
        // Section 8.1, and it is first because every layer below would be glad to say no.
        // Treating two volatile accesses as conflicting is what stops either being moved across
        // the other, which is the whole of what `volatile` promises.
        if a.volatile && b.volatile {
            return Answer::May;
        }

        // Two objects this function can name. Different objects never alias, and for one object
        // the offsets settle it on their own.
        //
        // The type-based layer is deliberately not reached from here, and that ordering is what
        // makes union type punning work: writing one member and reading another is two accesses
        // to one object at overlapping offsets whose types are unrelated, and asking about the
        // types first would answer no.
        if a.origin.is_object() && b.origin.is_object() {
            if self.distinct(a.origin, b.origin) {
                return Answer::No(Reason::Distinct);
            }
            if a.origin == b.origin {
                return by_offset(a, b);
            }
            return Answer::May;
        }

        // A local whose address never left the function is not what an address this function
        // cannot follow is pointing at, whatever it is pointing at.
        if let Some(local) = self.private(a).or_else(|| self.private(b)) {
            let _ = local;
            return Answer::No(Reason::Escape);
        }

        if a.restrict.disjoint(b.restrict) {
            return Answer::No(Reason::Restrict);
        }

        if self.options.strict_aliasing {
            if let (Some(one), Some(other)) = (a.tbaa, b.tbaa) {
                if !self.types_conflict(one, other) {
                    return Answer::No(Reason::Tbaa);
                }
            }
        }

        // Two references through one address this function cannot follow, at offsets it can.
        if a.origin == b.origin {
            return by_offset(a, b);
        }

        Answer::May
    }

    /// The local one of these is a reference to, when it is one nothing outside can reach and
    /// the other reference is not to it.
    fn private(&self, reference: &Access) -> Option<Inst> {
        match reference.origin {
            Origin::Local(local) if !self.escapes.escaped(local) => Some(local),
            _ => None,
        }
    }

    /// Whether one of this call's operands is the address of that local.
    ///
    /// Only for a local that did not escape, where it is the difference between the one call that
    /// was handed the address and every other call in the function.
    fn handed(&self, local: Inst, call: Inst) -> bool {
        self.func[self.func[call].args]
            .iter()
            .any(|&arg| matches!(origin(self.func, arg).0, Origin::Local(it) if it == local))
    }

    /// Whether these two origins are two objects.
    fn distinct(&self, a: Origin, b: Origin) -> bool {
        match (a, b) {
            (Origin::Local(one), Origin::Local(other)) => one != other,
            // Fresh storage this function made is not any named object.
            (Origin::Local(_), Origin::Global(_)) | (Origin::Global(_), Origin::Local(_)) => true,
            (Origin::Global(one), Origin::Global(other)) => {
                one != other && self.one_object(one) && self.one_object(other)
            }
            _ => false,
        }
    }

    /// Whether this symbol is a name for an object no other name in the module also names.
    ///
    /// An `alias` or an `ifunc` is exactly a second name for something, so two different symbols
    /// can be one object and the rule that two objects do not alias does not reach them. A name
    /// the module does not have at all is treated the same way, because something is wrong and
    /// the conservative answer is the one to be wrong in the direction of.
    fn one_object(&self, name: Symbol) -> bool {
        self.outside.one_object(name)
    }

    /// Whether two type nodes can describe the same byte.
    ///
    /// They can when one is at or above the other in the tree, which is what makes an access
    /// through `char` conflict with everything: `char`'s node is the root and every other node
    /// hangs below it. Two nodes in different parts of the tree describe no object in common.
    fn types_conflict(&self, one: Meta, other: Meta) -> bool {
        self.at_or_below(one, other) || self.at_or_below(other, one)
    }

    /// Whether `node` is `ancestor` or hangs below it.
    fn at_or_below(&self, mut node: Meta, ancestor: Meta) -> bool {
        for _ in 0..TREE_LIMIT {
            if node == ancestor {
                return true;
            }
            match self.outside.parent(node) {
                Some(up) => node = up,
                None => return false,
            }
        }
        // A tree deeper than the limit, or a cycle the verifier would have turned down. Either
        // way the answer that cannot be wrong is that they conflict.
        true
    }

    fn touched_by(&mut self, reference: &Access, call: Inst, writing: bool) -> Answer {
        self.counts.queries += 1;
        let answer = self.decide_call(reference, call, writing);
        if let Answer::No(reason) = answer {
            self.counts.answered[reason.index()] += 1;
        }
        answer
    }

    fn decide_call(&self, reference: &Access, call: Inst, writing: bool) -> Answer {
        // Not always a call. The memory chain sends everything that touches memory without an
        // access saying what through here, and the safety instrumentation is most of that: a check
        // reads a plane and a `meta_` writes one. Neither is memory the program can name, so
        // neither is what this reference covers, and [`Opcode::touches_only_planes`] is the whole
        // argument. It is first because it is a match on an opcode and the layers under it are not.
        if self.func[call].opcode.touches_only_planes() {
            return Answer::No(Reason::Plane);
        }

        // A `setjmp` marker is not a call and the escape argument under this one does not reach it,
        // so it has to be turned away before that argument is made. See
        // [`Opcode::is_jump_marker`] for why, and what it costs to get this wrong is a store
        // forwarded over the marker to a load the jump was the whole reason for.
        if self.func[call].opcode.is_jump_marker() {
            return Answer::May;
        }

        // Everything a call reaches, it reaches through an address, and an object whose address
        // never left this function is not one it has. The second half used to be free: reaching
        // here meant the address was not handed to this call either, because that would have been
        // an escape. [`Escapes::knowing`] is what took it away, since a local handed to a callee
        // that keeps nothing no longer counts as escaped, so the question gets asked outright.
        if let Some(local) = self.private(reference) {
            if !self.handed(local, call) {
                return Answer::No(Reason::Escape);
            }
        }

        let Some(attrs) = self.callee(call) else {
            return Answer::May;
        };
        // `const` reads no memory and writes none. `pure` may read and does not write.
        if attrs.set.contains(AttrSet::READNONE)
            || (writing && attrs.set.contains(AttrSet::READONLY))
        {
            return Answer::No(Reason::Attribute);
        }

        // Touching nothing except through the pointers it was passed. Every one of those is a
        // reference of its own, and if none of them can reach these bytes then neither can the
        // call. The reading is the non-transitive one the attribute's own documentation gives,
        // which is what makes this sound without a points-to solver behind it: what the callee
        // may reach by following a pointer it found in the memory it was passed is memory it
        // was passed.
        if attrs.set.contains(AttrSet::ARGMEM_ONLY) {
            let args = &self.func[self.func[call].args];
            let mut all = true;
            for &arg in args {
                if !self.func[arg].ty.is_ptr() {
                    continue;
                }
                let through = Access::through(self.func, arg);
                all &= self.decide(reference, &through).is_no();
            }
            if all {
                return Answer::No(Reason::Attribute);
            }
        }

        // The same three questions again, this time answered from the callee's body rather than
        // from what somebody wrote above it. Below the declarations because a declaration is a
        // promise the caller was told to rely on, and a body that does less than it promised is
        // still reached here.
        if let Some(summary) = self.summaries.and_then(|known| known.at(self.func, call)) {
            if summary.touches_nothing() || (writing && summary.writes_nothing()) {
                return Answer::No(Reason::Summary);
            }
            // Everything it touched, it reached through an argument. Unlike the attribute above
            // this is worked out rather than asserted, and the walk that worked it out gave up on
            // any address it could not follow back to a parameter, so a callee that follows a
            // pointer out of the memory it was handed is not one that reaches here.
            if summary.only_through_arguments() {
                let args = &self.func[self.func[call].args];
                let mut all = true;
                for (at, &arg) in args.iter().enumerate() {
                    if !self.func[arg].ty.is_ptr() {
                        continue;
                    }
                    // And not every argument, only the ones it does this to. A callee that reads
                    // one array and writes another is one whose write cannot be the read of the
                    // array it only reads, which is the thing an attribute cannot say.
                    let touch = summary.param(at);
                    let reached =
                        if writing { touch.effect.writes() } else { touch.effect.reads() };
                    if !reached {
                        continue;
                    }
                    let through = Access::through(self.func, arg);
                    all &= self.decide(reference, &through).is_no();
                }
                if all {
                    return Answer::No(Reason::Summary);
                }
            }
        }

        Answer::May
    }

    // Reading the instruction.

    /// What the callee of a direct call is declared to be, for a call whose callee the module
    /// has. An indirect call and a callee from nowhere both give nothing.
    fn callee(&self, call: Inst) -> Option<Attrs> {
        let Extra::Call(info) = self.func[call].extra else {
            return None;
        };
        let name = self.func[info].callee?;
        self.outside.attrs(name)
    }

    fn mem(&self, inst: Inst) -> Option<MemInfo> {
        match self.func[inst].extra {
            Extra::Mem(info) | Extra::Rmw(_, info) => Some(self.func[info]),
            Extra::VaObject(object) => Some(self.func[self.func[object].mem]),
            _ => None,
        }
    }

    fn result_type(&self, inst: Inst) -> Option<Type> {
        self.func[inst].results().next().map(|value| self.func[value].ty)
    }

    fn access(
        &self,
        pointer: Value,
        size: Option<u64>,
        info: Option<MemInfo>,
        flags: Flags,
    ) -> Access {
        let (origin, offset) = origin(self.func, pointer);
        Access {
            origin,
            offset,
            size,
            tbaa: info.and_then(|info| info.tbaa),
            restrict: info.map_or(Restrict::NONE, |info| info.restrict),
            volatile: flags.contains(Flags::VOLATILE),
        }
    }

    /// How many bytes a value of this type takes, which for an address is the target's answer
    /// and not the type's.
    fn width(&self, ty: Type) -> Option<u64> {
        if ty.is_ptr() {
            return self.outside.pointer_bytes();
        }
        let bits = u64::from(ty.bits()) * u64::from(ty.lanes());
        (bits > 0).then(|| bits.div_ceil(8))
    }
}

/// Layer 4: one object, two byte ranges.
fn by_offset(a: &Access, b: &Access) -> Answer {
    let (Some((a_start, a_end)), Some((b_start, b_end))) = (a.range(), b.range()) else {
        return Answer::May;
    };
    if a_end <= b_start || b_end <= a_start {
        return Answer::No(Reason::Offset);
    }
    Answer::May
}

/// The value of an integer constant, as a byte count.
fn constant(func: &Func, value: Value) -> Option<i64> {
    let Def::Result { inst, .. } = func[value].def else {
        return None;
    };
    let data = func[inst];
    if data.opcode != Opcode::IConst {
        return None;
    }
    let Extra::Imm(imm) = data.extra else {
        return None;
    };
    i64::try_from(Imm::signed(func[imm], func[value].ty)).ok()
}

#[cfg(test)]
mod tests {
    use rucc_base::{Interner, Symbol};
    use rucc_ir::{
        AttrSet, Attrs, Builder, CallInfo, Extra, Flags, Func, Global, InstData, IntPred, MemInfo,
        MemOrder, MetaNode, Module, Opcode, Pic, Restrict, Signature, TbaaNode, Type, Value,
    };

    use crate::callgraph::CallGraph;
    use crate::modref::{Summaries, summarize};
    use rucc_target::{TargetInfo, Triple};

    use super::*;

    /// A module for the host-shaped target, and the interner its names are in.
    fn module(names: &mut Interner) -> Module {
        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
        Module::new(names.intern("t.c"), &target)
    }

    /// A function taking those parameters, with an entry block and nothing in it.
    fn func(names: &mut Interner, params: &[Type]) -> Func {
        let mut func = Func::new(names.intern("f"), Signature::new().with_params(params));
        let entry = func.create_block();
        for &ty in params {
            func.append_param(entry, ty);
        }
        func
    }

    /// A builder appending to the entry block, which is where every test here puts everything.
    fn builder(func: &mut Func) -> Builder<'_> {
        let entry = func.entry().expect("the function has an entry block");
        Builder::new(func, entry)
    }

    fn param(func: &Func, index: usize) -> Value {
        let entry = func.entry().expect("the function has an entry block");
        func[entry].params[index]
    }

    fn plain(align: u32) -> MemInfo {
        MemInfo {
            size: 0,
            align,
            order: MemOrder::NotAtomic,
            tbaa: None,
            owns: 0,
            restrict: Restrict::NONE,
        }
    }

    fn sized(size: u64, align: u32) -> MemInfo {
        MemInfo { size, ..plain(align) }
    }

    /// An `alloca` of that many bytes in the entry block.
    fn local(build: &mut Builder<'_>, size: u64) -> Value {
        let mem = build.func().add_mem(sized(size, 8));
        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
    }

    /// That address, moved on by a constant number of bytes.
    fn at(build: &mut Builder<'_>, base: Value, offset: i64) -> Value {
        let by = build.iconst(Type::int(64), i128::from(offset));
        build.binary(Opcode::PtrAdd, base, by, Flags::NONE)
    }

    /// The address of a global of that name, declared in the module as it goes.
    fn global(build: &mut Builder<'_>, module: &mut Module, name: Symbol) -> Value {
        module.add_global(Global::new(name, 16, 8));
        build.value(
            InstData { extra: Extra::Symbol(name), ..InstData::new(Opcode::GlobalAddr) },
            Type::PTR,
        )
    }

    #[test]
    fn two_different_locals_are_two_objects() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let one = local(&mut build, 16);
        let other = local(&mut build, 16);
        let read = build.load(Type::int(32), one, plain(4), Flags::NONE);
        build.store(read, other, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Distinct));
        assert_eq!(alias.counts().answered(Reason::Distinct), 1);
        assert_eq!(alias.counts().queries(), 1);
    }

    /// The reference the first load in the function reads and the one the first store writes.
    fn two(alias: &Alias<'_>, func: &Func) -> (Access, Access) {
        let mut read = None;
        let mut written = None;
        for block in func.blocks() {
            for inst in func.insts(block) {
                if read.is_none() {
                    read = alias.reads(inst);
                }
                if written.is_none() {
                    written = alias.writes(inst);
                }
            }
        }
        (read.expect("a read"), written.expect("a write"))
    }

    #[test]
    fn a_local_and_a_global_are_two_objects() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let x = names.intern("x");
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let one = local(&mut build, 16);
        let other = global(&mut build, &mut module, x);
        let read = build.load(Type::int(32), one, plain(4), Flags::NONE);
        build.store(read, other, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Distinct));
    }

    #[test]
    fn two_different_globals_are_two_objects() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let (x, y) = (names.intern("x"), names.intern("y"));
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let one = global(&mut build, &mut module, x);
        let other = global(&mut build, &mut module, y);
        let read = build.load(Type::int(32), one, plain(4), Flags::NONE);
        build.store(read, other, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Distinct));
    }

    #[test]
    fn a_global_the_module_does_not_have_is_not_argued_about() {
        // Nothing should produce this, and if something does, the answer that cannot be wrong
        // is that the two may alias.
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let (x, y) = (names.intern("x"), names.intern("y"));
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let one = global(&mut build, &mut module, x);
        let other = build.value(
            InstData { extra: Extra::Symbol(y), ..InstData::new(Opcode::GlobalAddr) },
            Type::PTR,
        );
        let read = build.load(Type::int(32), one, plain(4), Flags::NONE);
        build.store(read, other, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::May);
    }

    #[test]
    fn two_parts_of_one_object_that_do_not_overlap_are_disjoint() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let first = at(&mut build, object, 0);
        let second = at(&mut build, object, 4);
        let read = build.load(Type::int(32), first, plain(4), Flags::NONE);
        build.store(read, second, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Offset));
    }

    #[test]
    fn two_parts_of_one_object_that_do_overlap_are_not() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let first = at(&mut build, object, 0);
        let second = at(&mut build, object, 2);
        let read = build.load(Type::int(32), first, plain(4), Flags::NONE);
        build.store(read, second, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::May);
    }

    #[test]
    fn an_offset_nobody_knows_gives_up_the_offset_and_keeps_the_object() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::int(64)]);
        let n = param(&f, 0);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let somewhere = build.binary(Opcode::PtrAdd, object, n, Flags::NONE);
        let read = build.load(Type::int(32), somewhere, plain(4), Flags::NONE);
        build.store(read, object, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(a.origin, b.origin, "both are still that one object");
        assert_eq!(a.offset, None);
        assert_eq!(alias.query(&a, &b), Answer::May);
    }

    #[test]
    fn a_local_whose_address_stays_here_is_not_what_a_parameter_points_at() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let read = build.load(Type::int(32), object, plain(4), Flags::NONE);
        build.store(read, outside, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        assert_eq!(alias.escapes().count(), 0);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Escape));
    }

    #[test]
    fn a_local_whose_address_was_stored_somewhere_is() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        // The address itself is written out through a pointer this function did not make, and
        // from here anything can reach the object.
        build.store(object, outside, plain(8), Flags::NONE);
        let read = build.load(Type::int(32), object, plain(4), Flags::NONE);
        build.store(read, outside, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        assert_eq!(alias.escapes().count(), 1);
        let read = first(&f, Opcode::Load);
        let write = last(&f, Opcode::Store);
        let a = alias.reads(read).unwrap();
        let b = alias.writes(write).unwrap();
        assert_eq!(alias.query(&a, &b), Answer::May);
    }

    fn first(func: &Func, opcode: Opcode) -> Inst {
        func.blocks()
            .flat_map(|block| func.insts(block))
            .find(|&inst| func[inst].opcode == opcode)
            .expect("an instruction with that opcode")
    }

    fn last(func: &Func, opcode: Opcode) -> Inst {
        func.blocks()
            .flat_map(|block| func.insts(block))
            .filter(|&inst| func[inst].opcode == opcode)
            .last()
            .expect("an instruction with that opcode")
    }

    #[test]
    fn an_address_carried_through_a_block_parameter_has_left_the_function() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let start = f.entry().expect("an entry block");
        let next = f.create_block();
        f.append_param(next, Type::PTR);

        let mut build = Builder::new(&mut f, start);
        let object = local(&mut build, 16);
        build.jump(next, &[object]);
        let mut build = Builder::new(&mut f, next);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        assert!(alias.escapes().escaped(first(&f, Opcode::Alloca)));
    }

    #[test]
    fn comparing_two_addresses_does_not_let_either_of_them_out() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        build.icmp(IntPred::Eq, object, outside);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        assert_eq!(alias.escapes().count(), 0);
    }

    #[test]
    fn a_plane_write_on_a_local_does_not_let_its_address_out() {
        // What a `-fsafety=detect` build puts beside the first store into a local. The runtime
        // writes down that those bytes are now initialised, in storage of its own, and nothing
        // the program can run afterwards reaches the local through it.
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let width = build.iconst(Type::int(64), 16);
        let args = build.func().push_values(&[object, width]);
        build.inst(InstData { args, ..InstData::new(Opcode::MetaInit) }, &[]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        assert_eq!(alias.escapes().count(), 0);
    }

    #[test]
    fn a_local_that_is_only_asked_about_and_checked_does_not_leave_the_function() {
        // What one bounds check on a local lowers to before `rucc_safety::lower` runs, which is
        // an `alloca`, the capability of the object it is, and a check that reads a plane. None
        // of the three hands the address to anything, and before this was written the `cap_of`
        // in the middle of it escaped every local in a program built with the checks on.
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let args = build.func().push_values(&[object]);
        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
        let args = build.func().push_values(&[capability, object]);
        build.inst(InstData { args, ..InstData::new(Opcode::CheckBounds) }, &[]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        assert_eq!(alias.escapes().count(), 0);
    }

    #[test]
    fn a_capability_of_a_local_used_for_anything_else_does_let_it_out() {
        // The other side of the same line, and the reason the walk goes through `cap_of` rather
        // than the whitelist naming it on its own. `cap_narrow` makes a second capability from
        // the first, and where that one ends up is not something this walk follows, so the local
        // it is about has to count as gone.
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let args = build.func().push_values(&[object]);
        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
        let base = build.iconst(Type::int(64), 0);
        let size = build.iconst(Type::int(64), 4);
        let args = build.func().push_values(&[capability, base, size]);
        build.value(InstData { args, ..InstData::new(Opcode::CapNarrow) }, Type::CAP);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        assert!(alias.escapes().escaped(first(&f, Opcode::Alloca)));
    }

    #[test]
    fn the_whitelist_says_yes_to_a_plane_access_at_every_operand() {
        // Asked of the list rather than of a program, because what makes this safe is that every
        // pointer one of these takes is a row to look up, and a test built out of one instruction
        // only ever says it about the operand that instruction has.
        for opcode in Opcode::all().filter(|opcode| opcode.touches_only_planes()) {
            for index in 0..4 {
                assert!(keeps_address(opcode, index), "{opcode} at {index}");
            }
        }
        for opcode in [Opcode::CapNarrow, Opcode::CapRecover] {
            assert!(!keeps_address(opcode, 0), "{opcode}");
        }
        // The two operands of the aux pair that say which slot, against the two of `cap_store`
        // that say what goes in it.
        for opcode in [Opcode::CapLoad, Opcode::CapStore, Opcode::CapCopy] {
            for index in 0..2 {
                assert!(keeps_address(opcode, index), "{opcode} at {index}");
            }
        }
        assert!(!keeps_address(Opcode::CapStore, 2));
        assert!(!keeps_address(Opcode::CapStore, 3));
        assert!(keeps_address(Opcode::CapOf, 0));
    }

    #[test]
    fn a_local_a_pointer_is_written_into_does_not_leave_the_function_for_the_writing_down() {
        // What `int *slot; slot = p;` lowers to with the checks on, which is the store and a
        // `cap_store` behind it putting the pointer's capability in the slot beside the word. The
        // local holding the pointer is the container and it is named twice, once as its capability
        // and once as the address of the word, and neither of those is a way to reach it later.
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let written = param(&f, 0);
        let mut build = builder(&mut f);
        let object = local(&mut build, 8);
        let args = build.func().push_values(&[object]);
        let container = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
        let args = build.func().push_values(&[written]);
        let held = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
        build.store(written, object, plain(8), Flags::NONE);
        let args = build.func().push_values(&[container, object, written, held]);
        build.inst(InstData { args, ..InstData::new(Opcode::CapStore) }, &[]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        assert_eq!(alias.escapes().count(), 0);
    }

    #[test]
    fn a_local_whose_capability_is_written_into_a_slot_does_leave_the_function() {
        // The other two operands, and the line between them and the two above. Here the local is
        // the pointer being stored rather than the object being stored into, so its address goes
        // into somebody else's memory and its capability goes into the slot beside it, and both of
        // those are places a later `cap_load` in another function can read.
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let into = param(&f, 0);
        let mut build = builder(&mut f);
        let object = local(&mut build, 8);
        let args = build.func().push_values(&[into]);
        let container = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
        let args = build.func().push_values(&[object]);
        let held = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
        let args = build.func().push_values(&[container, into, object, held]);
        build.inst(InstData { args, ..InstData::new(Opcode::CapStore) }, &[]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        assert!(alias.escapes().escaped(first(&f, Opcode::Alloca)));
    }

    #[test]
    fn an_address_turned_into_a_number_has_left_the_function() {
        // The number can be turned back into a pointer anywhere, including in a different
        // translation unit, so this is an escape and the whitelist is what makes it one.
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        build.unary(Opcode::PtrToInt, object, Type::int(64));
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        assert!(alias.escapes().escaped(first(&f, Opcode::Alloca)));
    }

    #[test]
    fn two_restrict_pointers_in_one_scope_do_not_reach_the_same_object() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR, Type::PTR]);
        let (one, other) = (param(&f, 0), param(&f, 1));
        let mut build = builder(&mut f);
        let mut info = plain(4);
        info.restrict = Restrict { clique: 1, base: 1 };
        let read = build.load(Type::int(32), one, info, Flags::NONE);
        info.restrict = Restrict { clique: 1, base: 2 };
        build.store(read, other, info, Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Restrict));
    }

    #[test]
    fn two_restrict_pointers_in_different_scopes_say_nothing_about_each_other() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR, Type::PTR]);
        let (one, other) = (param(&f, 0), param(&f, 1));
        let mut build = builder(&mut f);
        let mut info = plain(4);
        info.restrict = Restrict { clique: 1, base: 1 };
        let read = build.load(Type::int(32), one, info, Flags::NONE);
        info.restrict = Restrict { clique: 2, base: 1 };
        build.store(read, other, info, Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::May);
    }

    /// A module with a `char` root and an `int` and a `float` hanging off it.
    fn types(module: &mut Module, names: &mut Interner) -> (Meta, Meta, Meta) {
        let root = module.add_meta(MetaNode::Tbaa(TbaaNode {
            name: names.intern("char"),
            parent: None,
            offset: 0,
        }));
        let int = module.add_meta(MetaNode::Tbaa(TbaaNode {
            name: names.intern("int"),
            parent: Some(root),
            offset: 0,
        }));
        let float = module.add_meta(MetaNode::Tbaa(TbaaNode {
            name: names.intern("float"),
            parent: Some(root),
            offset: 0,
        }));
        (root, int, float)
    }

    #[test]
    fn two_unrelated_types_describe_no_object_in_common() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let (_, int, float) = types(&mut module, &mut names);
        let mut f = func(&mut names, &[Type::PTR, Type::PTR]);
        let (one, other) = (param(&f, 0), param(&f, 1));
        let mut build = builder(&mut f);
        let mut info = plain(4);
        info.tbaa = Some(int);
        let read = build.load(Type::int(32), one, info, Flags::NONE);
        info.tbaa = Some(float);
        build.store(read, other, info, Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Tbaa));
    }

    #[test]
    fn an_access_through_char_conflicts_with_everything() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let (root, int, _) = types(&mut module, &mut names);
        let mut f = func(&mut names, &[Type::PTR, Type::PTR]);
        let (one, other) = (param(&f, 0), param(&f, 1));
        let mut build = builder(&mut f);
        let mut info = plain(4);
        info.tbaa = Some(int);
        let read = build.load(Type::int(32), one, info, Flags::NONE);
        info.tbaa = Some(root);
        build.store(read, other, info, Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::May);
    }

    #[test]
    fn turning_strict_aliasing_off_turns_off_that_layer_and_no_other() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let (_, int, float) = types(&mut module, &mut names);
        let mut f = func(&mut names, &[Type::PTR, Type::PTR]);
        let (one, other) = (param(&f, 0), param(&f, 1));
        let mut build = builder(&mut f);
        let mut info = plain(4);
        info.tbaa = Some(int);
        info.restrict = Restrict { clique: 1, base: 1 };
        let read = build.load(Type::int(32), one, info, Flags::NONE);
        info.tbaa = Some(float);
        info.restrict = Restrict { clique: 1, base: 2 };
        build.store(read, other, info, Flags::NONE);
        build.ret(&[]);

        let options = Options { strict_aliasing: false };
        let outside = Outside::of(&module);
        let mut alias = Alias::with(&f, &outside, options);
        let (a, b) = two(&alias, &f);
        // The `restrict` layer still answers, which is the point: the flag is one condition in
        // one place and it does not reach anything else.
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Restrict));

        let mut without = Alias::with(&f, &outside, options);
        let plainer = Access { restrict: Restrict::NONE, ..a };
        let other = Access { restrict: Restrict::NONE, ..b };
        assert_eq!(without.query(&plainer, &other), Answer::May);

        let mut with = Alias::new(&f, &outside);
        assert_eq!(with.query(&plainer, &other), Answer::No(Reason::Tbaa));
    }

    #[test]
    fn writing_one_member_of_a_union_and_reading_another_is_one_object() {
        // The compatibility fact of section 8.6. Two accesses to one object at the same offset
        // with unrelated types, which is `union { int i; float f; }` written as one and read as
        // the other. The offset layer runs first, it says they overlap, and the type layer
        // never gets to say no. Twenty years of real C rests on this answer.
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let (_, int, float) = types(&mut module, &mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 4);
        let mut info = plain(4);
        info.tbaa = Some(float);
        let read = build.load(Type::int(32), object, info, Flags::NONE);
        info.tbaa = Some(int);
        build.store(read, object, info, Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::May);
    }

    #[test]
    fn two_volatile_accesses_conflict_whatever_else_is_true_of_them() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let one = local(&mut build, 16);
        let other = local(&mut build, 16);
        let read = build.load(Type::int(32), one, plain(4), Flags::VOLATILE);
        build.store(read, other, plain(4), Flags::VOLATILE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        // Two different objects, and the answer is still that they conflict, because moving
        // one volatile access across another is the thing `volatile` exists to forbid.
        assert_eq!(alias.query(&a, &b), Answer::May);
    }

    #[test]
    fn one_volatile_access_and_one_ordinary_one_are_argued_about_as_usual() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let one = local(&mut build, 16);
        let other = local(&mut build, 16);
        let read = build.load(Type::int(32), one, plain(4), Flags::VOLATILE);
        build.store(read, other, plain(4), Flags::NONE);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let (a, b) = two(&alias, &f);
        assert_eq!(alias.query(&a, &b), Answer::No(Reason::Distinct));
    }

    #[test]
    fn a_copy_reads_its_source_and_writes_its_destination() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let to = local(&mut build, 16);
        let from = local(&mut build, 16);
        let mem = build.func().add_mem(sized(16, 8));
        let args = build.func().push_values(&[to, from]);
        build.inst(InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Memcpy) }, &[]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        let copy = first(&f, Opcode::Memcpy);
        let read = alias.reads(copy).expect("a copy reads");
        let written = alias.writes(copy).expect("a copy writes");
        assert_eq!(read.size, Some(16));
        assert_eq!(written.size, Some(16));
        assert_ne!(read.origin, written.origin);
    }

    #[test]
    fn a_copy_of_a_length_the_program_works_out_is_an_access_of_no_known_size() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::int(64)]);
        let length = param(&f, 0);
        let mut build = builder(&mut f);
        let to = local(&mut build, 16);
        let from = local(&mut build, 16);
        let mem = build.func().add_mem(sized(0, 8));
        let args = build.func().push_values(&[to, from, length]);
        build.inst(InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Memcpy) }, &[]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let alias = Alias::new(&f, &outside);
        let copy = first(&f, Opcode::Memcpy);
        // Not `Some(0)`, which is what the payload says and which would make this a copy that
        // touches nothing rather than one that may touch anything.
        assert_eq!(alias.reads(copy).expect("a copy reads").size, None);
        assert_eq!(alias.writes(copy).expect("a copy writes").size, None);
    }

    /// A call to a function declared with those attributes.
    fn call_to(
        names: &mut Interner,
        module: &mut Module,
        f: &mut Func,
        attrs: Attrs,
        args: &[Value],
    ) -> Inst {
        let name = names.intern("g");
        let params: Vec<Type> = args.iter().map(|_| Type::PTR).collect();
        let mut callee = Func::new(name, Signature::new().with_params(&params));
        callee.attrs = attrs;
        module.add_func(callee);
        let signature = f.add_signature(Signature::new().with_params(&params));
        let mut build = builder(f);
        build.call(name, signature, args)
    }

    fn attrs(set: AttrSet) -> Attrs {
        Attrs { set, ..Attrs::NONE }
    }

    #[test]
    fn a_call_cannot_touch_a_local_whose_address_stayed_here() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let read = build.load(Type::int(32), object, plain(4), Flags::NONE);
        let _ = read;
        let call = call_to(&mut names, &mut module, &mut f, Attrs::NONE, &[outside]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        assert_eq!(alias.clobbered_by(&reference, call), Answer::No(Reason::Escape));
        assert_eq!(alias.read_by(&reference, call), Answer::No(Reason::Escape));
    }

    #[test]
    fn a_call_can_touch_a_local_it_was_handed() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        build.load(Type::int(32), object, plain(4), Flags::NONE);
        let call = call_to(&mut names, &mut module, &mut f, Attrs::NONE, &[object]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        assert_eq!(alias.clobbered_by(&reference, call), Answer::May);
    }

    #[test]
    fn a_setjmp_marker_can_touch_a_local_whose_address_stayed_here() {
        // The marker is on the memory chain and it is not a call, so the argument the two tests
        // above rest on says nothing about it. Control arrives at what follows it from wherever
        // the matching `longjmp` sits, and the jump comes back into this frame, so a local this
        // function never let out is exactly what the landing goes on to read.
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let name = names.intern("jmp_buf");
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        build.load(Type::int(32), object, plain(4), Flags::NONE);
        let buffer = global(&mut build, &mut module, name);
        let args = build.func().push_values(&[buffer]);
        let marker =
            build.inst(InstData { args, ..InstData::new(Opcode::SetjmpMarker) }, &[Type::int(32)]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        assert_eq!(alias.clobbered_by(&reference, marker), Answer::May);
        assert_eq!(alias.read_by(&reference, marker), Answer::May);
    }

    #[test]
    fn a_pure_callee_reads_memory_and_writes_none() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        build.load(Type::int(32), outside, plain(4), Flags::NONE);
        let call = call_to(&mut names, &mut module, &mut f, attrs(AttrSet::READONLY), &[outside]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        assert_eq!(alias.clobbered_by(&reference, call), Answer::No(Reason::Attribute));
        assert_eq!(alias.read_by(&reference, call), Answer::May);
    }

    #[test]
    fn a_plane_write_is_not_a_write_to_the_address_it_names() {
        // The one that was costing the memory passes everything on a safety build. `meta_init %p`
        // writes the entry the lifetime plane keeps for `%p`, and the oracle reading its operand
        // the ordinary way sees a write to exactly the bytes a load of `%p` wants, which is the
        // worst possible wrong answer: the instrumentation blocking the optimization of the code
        // it was put in to check.
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        build.load(Type::int(32), outside, plain(4), Flags::NONE);
        let width = build.iconst(Type::int(64), 4);
        let args = build.func().push_values(&[outside, width]);
        build.inst(InstData { args, ..InstData::new(Opcode::MetaInit) }, &[]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        let plane = first(&f, Opcode::MetaInit);
        assert_eq!(alias.clobbered_by(&reference, plane), Answer::No(Reason::Plane));
        // And it does not read it either, so a store the program made is not kept alive by one.
        assert_eq!(alias.read_by(&reference, plane), Answer::No(Reason::Plane));
    }

    #[test]
    fn a_check_reads_a_plane_and_not_what_it_is_about() {
        // The reading half of the same fact, which is what a walk back over memory runs into
        // first: a check between a store and a load of the same address is on the chain, and
        // answering `May` for it is a load kept for no reason.
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        build.load(Type::int(32), outside, plain(4), Flags::NONE);
        let width = build.iconst(Type::int(64), 4);
        let args = build.func().push_values(&[outside, width]);
        build.inst(InstData { args, ..InstData::new(Opcode::CheckBounds) }, &[]);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        let check = first(&f, Opcode::CheckBounds);
        assert_eq!(alias.clobbered_by(&reference, check), Answer::No(Reason::Plane));
        assert_eq!(alias.read_by(&reference, check), Answer::No(Reason::Plane));
    }

    #[test]
    fn a_const_callee_touches_no_memory_at_all() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        build.load(Type::int(32), outside, plain(4), Flags::NONE);
        let call = call_to(&mut names, &mut module, &mut f, attrs(AttrSet::READNONE), &[outside]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        assert_eq!(alias.clobbered_by(&reference, call), Answer::No(Reason::Attribute));
        assert_eq!(alias.read_by(&reference, call), Answer::No(Reason::Attribute));
    }

    #[test]
    fn a_callee_that_touches_only_its_arguments_leaves_a_global_it_was_not_passed_alone() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let x = names.intern("x");
        let mut f = func(&mut names, &[Type::PTR]);
        let outside = param(&f, 0);
        let mut build = builder(&mut f);
        let object = global(&mut build, &mut module, x);
        build.load(Type::int(32), object, plain(4), Flags::NONE);
        let call =
            call_to(&mut names, &mut module, &mut f, attrs(AttrSet::ARGMEM_ONLY), &[outside]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        // The one pointer it was handed is a parameter of unknown origin, which may be that
        // global, so this is the answer that cannot be wrong.
        assert_eq!(alias.clobbered_by(&reference, call), Answer::May);
    }

    #[test]
    fn a_callee_that_touches_only_its_arguments_and_was_handed_one_object_leaves_the_other() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let (x, y) = (names.intern("x"), names.intern("y"));
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let watched = global(&mut build, &mut module, x);
        let handed = global(&mut build, &mut module, y);
        build.load(Type::int(32), watched, plain(4), Flags::NONE);
        let call = call_to(&mut names, &mut module, &mut f, attrs(AttrSet::ARGMEM_ONLY), &[handed]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        assert_eq!(alias.clobbered_by(&reference, call), Answer::No(Reason::Attribute));
    }

    /// A call to a function of that many pointer parameters whose body is that.
    ///
    /// Unlike [`call_to`] the callee is defined, which is what gives [`crate::modref`] something
    /// to read. Nothing is declared about it, so every answer below comes from the body.
    fn call_to_body(
        names: &mut Interner,
        module: &mut Module,
        f: &mut Func,
        arity: usize,
        body: fn(&mut Builder<'_>, &[Value]),
        args: &[Value],
    ) -> Inst {
        defines(names, module, "g", arity, body);
        calls_it(names, f, "g", arity, args)
    }

    /// Adds a function of that name to the module, with that many pointer parameters and that
    /// body.
    fn defines(
        names: &mut Interner,
        module: &mut Module,
        called: &str,
        arity: usize,
        body: fn(&mut Builder<'_>, &[Value]),
    ) {
        let name = names.intern(called);
        let params = vec![Type::PTR; arity];
        let mut callee = Func::new(name, Signature::new().with_params(&params));
        let entry = callee.create_block();
        let got: Vec<Value> = params.iter().map(|&ty| callee.append_param(entry, ty)).collect();
        let mut build = Builder::new(&mut callee, entry);
        body(&mut build, &got);
        module.add_func(callee);
    }

    /// A call to a function of that name, for a test that wants more than one of them.
    fn calls_it(
        names: &mut Interner,
        f: &mut Func,
        called: &str,
        arity: usize,
        args: &[Value],
    ) -> Inst {
        let name = names.intern(called);
        let signature = f.add_signature(Signature::new().with_params(&vec![Type::PTR; arity]));
        let mut build = builder(f);
        build.call(name, signature, args)
    }

    /// What the module's functions were worked out to do to memory.
    fn worked_out(module: &Module) -> Summaries {
        let mut summaries = Summaries::of_module(module);
        summarize(module, &CallGraph::of(module, Pic::Executable), &mut summaries);
        summaries
    }

    /// Comes back and does nothing on the way.
    fn body_does_nothing(build: &mut Builder<'_>, _: &[Value]) {
        build.ret(&[]);
    }

    /// Reads four bytes through the first pointer it was handed.
    fn body_reads_the_first(build: &mut Builder<'_>, args: &[Value]) {
        let value = build.load(Type::int(32), args[0], plain(4), Flags::NONE);
        build.ret(&[value]);
    }

    /// Writes four bytes through the first pointer it was handed and leaves the rest alone.
    fn body_writes_the_first(build: &mut Builder<'_>, args: &[Value]) {
        let zero = build.iconst(Type::int(32), 0);
        build.store(zero, args[0], plain(4), Flags::NONE);
        build.ret(&[]);
    }

    /// Writes the first pointer it was handed down at the second, so the address gets out.
    fn body_keeps_the_first(build: &mut Builder<'_>, args: &[Value]) {
        build.store(args[0], args[1], plain(8), Flags::NONE);
        build.ret(&[]);
    }

    #[test]
    fn a_callee_nobody_declared_anything_about_is_read_out_of_its_body() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let x = names.intern("x");
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = global(&mut build, &mut module, x);
        build.load(Type::int(32), object, plain(4), Flags::NONE);
        let call = call_to_body(&mut names, &mut module, &mut f, 0, body_does_nothing, &[]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let reference = Alias::new(&f, &outside).reads(first(&f, Opcode::Load)).unwrap();
        // Without the summaries there is nothing to go on, because nobody wrote an attribute.
        let mut blind = Alias::new(&f, &outside);
        assert_eq!(blind.clobbered_by(&reference, call), Answer::May);

        let summaries = worked_out(&module);
        let mut alias = Alias::new(&f, &outside).knowing(&summaries);
        assert_eq!(alias.clobbered_by(&reference, call), Answer::No(Reason::Summary));
        assert_eq!(alias.read_by(&reference, call), Answer::No(Reason::Summary));
    }

    #[test]
    fn a_callee_worked_out_to_write_nothing_clobbers_nothing() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR]);
        let handed = param(&f, 0);
        let mut build = builder(&mut f);
        build.load(Type::int(32), handed, plain(4), Flags::NONE);
        let call =
            call_to_body(&mut names, &mut module, &mut f, 1, body_reads_the_first, &[handed]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let summaries = worked_out(&module);
        let reference = Alias::new(&f, &outside).reads(first(&f, Opcode::Load)).unwrap();
        let mut alias = Alias::new(&f, &outside).knowing(&summaries);
        assert_eq!(alias.clobbered_by(&reference, call), Answer::No(Reason::Summary));
        // It was handed that very object and it does read, so the other question is still open.
        assert_eq!(alias.read_by(&reference, call), Answer::May);
    }

    #[test]
    fn a_callee_that_writes_one_of_the_two_it_was_handed_leaves_the_other() {
        // The answer no attribute can give. `argmemonly` says the call touched nothing it was not
        // handed, and it was handed both of these, so the declaration alone has to say `May`.
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let (x, y) = (names.intern("x"), names.intern("y"));
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let watched = global(&mut build, &mut module, x);
        let written = global(&mut build, &mut module, y);
        build.load(Type::int(32), watched, plain(4), Flags::NONE);
        let call = call_to_body(
            &mut names,
            &mut module,
            &mut f,
            2,
            body_writes_the_first,
            &[written, watched],
        );
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let summaries = worked_out(&module);
        let reference = Alias::new(&f, &outside).reads(first(&f, Opcode::Load)).unwrap();
        let mut alias = Alias::new(&f, &outside).knowing(&summaries);
        assert_eq!(alias.clobbered_by(&reference, call), Answer::No(Reason::Summary));
    }

    #[test]
    fn a_local_lent_to_a_callee_that_keeps_it_not_is_still_private_everywhere_else() {
        // Section 34.6's upgrade. Handing the address of a local to a call is what a C program
        // does with most of the locals it takes the address of at all, and without a summary of
        // the callee that is the end of every question about that local.
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let x = names.intern("x");
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let elsewhere = global(&mut build, &mut module, x);
        build.load(Type::int(32), object, plain(4), Flags::NONE);
        defines(&mut names, &mut module, "g", 1, body_writes_the_first);
        let lent = calls_it(&mut names, &mut f, "g", 1, &[object]);
        let other = calls_it(&mut names, &mut f, "g", 1, &[elsewhere]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let reference = Alias::new(&f, &outside).reads(first(&f, Opcode::Load)).unwrap();
        // Without the summaries the address went out at the first call and stayed out.
        let mut blind = Alias::new(&f, &outside);
        assert_eq!(blind.clobbered_by(&reference, lent), Answer::May);
        assert_eq!(blind.clobbered_by(&reference, other), Answer::May);

        let summaries = worked_out(&module);
        let mut alias = Alias::new(&f, &outside).knowing(&summaries);
        // The call that was handed it can still have written it, and is asked about rather than
        // assumed away, which is the invariant the upgrade took off the escape layer.
        assert_eq!(alias.clobbered_by(&reference, lent), Answer::May);
        // The one that was not never had the address and never could get it.
        assert_eq!(alias.clobbered_by(&reference, other), Answer::No(Reason::Escape));
        assert_eq!(alias.escapes().count(), 0);
    }

    #[test]
    fn a_local_written_down_by_a_callee_is_gone_exactly_as_before() {
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let x = names.intern("x");
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        let elsewhere = global(&mut build, &mut module, x);
        build.load(Type::int(32), object, plain(4), Flags::NONE);
        defines(&mut names, &mut module, "g", 2, body_keeps_the_first);
        defines(&mut names, &mut module, "h", 1, body_does_nothing);
        calls_it(&mut names, &mut f, "g", 2, &[object, elsewhere]);
        let other = calls_it(&mut names, &mut f, "h", 1, &[elsewhere]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let summaries = worked_out(&module);
        let reference = Alias::new(&f, &outside).reads(first(&f, Opcode::Load)).unwrap();
        let mut alias = Alias::new(&f, &outside).knowing(&summaries);
        // That callee put the address somewhere, so the upgrade does not save it and every
        // question about the local is back to the answer that cannot be wrong.
        assert_eq!(alias.escapes().count(), 1);
        assert_eq!(alias.private(&reference), None);
        // `h` touches nothing at all, so it is still answered, just not by the escape layer.
        assert_eq!(alias.clobbered_by(&reference, other), Answer::No(Reason::Summary));
    }

    #[test]
    fn a_local_handed_to_a_const_declaration_is_still_gone() {
        // `const` says the result comes out of the arguments. It does not say the function did
        // not hand one of them back, so the address may be in the caller's hands after the call
        // under a name the escape walk cannot follow to this local, and the upgrade has to leave
        // this one alone.
        let mut names = Interner::new();
        let mut module = module(&mut names);
        let mut f = func(&mut names, &[]);
        let mut build = builder(&mut f);
        let object = local(&mut build, 16);
        build.load(Type::int(32), object, plain(4), Flags::NONE);
        call_to(&mut names, &mut module, &mut f, attrs(AttrSet::READNONE), &[object]);
        let mut build = builder(&mut f);
        build.ret(&[]);

        let outside = Outside::of(&module);
        let summaries = worked_out(&module);
        let reference = Alias::new(&f, &outside).reads(first(&f, Opcode::Load)).unwrap();
        let alias = Alias::new(&f, &outside).knowing(&summaries);
        assert_eq!(alias.escapes().count(), 1);
        assert_eq!(alias.private(&reference), None);
    }

    #[test]
    fn an_indirect_call_is_not_argued_about() {
        let mut names = Interner::new();
        let module = module(&mut names);
        let mut f = func(&mut names, &[Type::PTR, Type::PTR]);
        let (target, outside) = (param(&f, 0), param(&f, 1));
        let mut build = builder(&mut f);
        build.load(Type::int(32), outside, plain(4), Flags::NONE);
        let signature = build.func().add_signature(Signature::new().with_params(&[Type::PTR]));
        let varargs = build.func().push_abis(&[]);
        let info = build.func().add_call(CallInfo { callee: None, signature, varargs });
        let args = build.func().push_values(&[target, outside]);
        let call = build.inst(
            InstData { args, extra: Extra::Call(info), ..InstData::new(Opcode::CallIndirect) },
            &[],
        );
        build.ret(&[]);

        let outside = Outside::of(&module);
        let mut alias = Alias::new(&f, &outside);
        let reference = alias.reads(first(&f, Opcode::Load)).unwrap();
        assert_eq!(alias.clobbered_by(&reference, call), Answer::May);
    }

    #[test]
    fn every_reason_has_a_name_and_a_sentence() {
        for reason in Reason::ALL {
            assert!(!reason.name().is_empty());
            assert!(!reason.describe().is_empty());
            assert_eq!(Reason::ALL[reason.index()], reason);
        }
        assert_eq!(Reason::ALL.len(), Reason::COUNT);
        assert_eq!(Answer::No(Reason::Offset).reason(), Some(Reason::Offset));
        assert!(Answer::No(Reason::Offset).is_no());
        assert_eq!(Answer::May.reason(), None);
        assert!(!Answer::May.is_no());
    }
}