summaryrefslogtreecommitdiff
path: root/compiler/GHC/Types/Demand.hs
blob: ba5e5266c9da1b1fb90b2aa6781bea4e4b28eef9 (plain)
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
{-# LANGUAGE CPP          #-}
{-# LANGUAGE ViewPatterns #-}

{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}

{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}

-- | A language to express the evaluation context of an expression as a
-- 'Demand' and track how an expression evaluates free variables and arguments
-- in turn as a 'DmdType'.
--
-- Lays out the abstract domain for "GHC.Core.Opt.DmdAnal".
module GHC.Types.Demand (
    -- * Demands
    Card(..), Demand(..), SubDemand(Prod), mkProd, viewProd,
    -- ** Algebra
    absDmd, topDmd, botDmd, seqDmd, topSubDmd,
    -- *** Least upper bound
    lubCard, lubDmd, lubSubDmd,
    -- *** Plus
    plusCard, plusDmd, plusSubDmd,
    -- *** Multiply
    multCard, multDmd, multSubDmd,
    -- ** Predicates on @Card@inalities and @Demand@s
    isAbs, isUsedOnce, isStrict,
    isAbsDmd, isUsedOnceDmd, isStrUsedDmd,
    isTopDmd, isSeqDmd, isWeakDmd,
    -- ** Special demands
    evalDmd,
    -- *** Demands used in PrimOp signatures
    lazyApply1Dmd, lazyApply2Dmd, strictOnceApply1Dmd, strictManyApply1Dmd,
    -- ** Other @Demand@ operations
    oneifyCard, oneifyDmd, strictifyDmd, strictifyDictDmd, mkWorkerDemand,
    peelCallDmd, peelManyCalls, mkCalledOnceDmd, mkCalledOnceDmds,
    addCaseBndrDmd,
    -- ** Extracting one-shot information
    argOneShots, argsOneShots, saturatedByOneShots,

    -- * Demand environments
    DmdEnv, emptyDmdEnv,
    keepAliveDmdEnv, reuseEnv,

    -- * Divergence
    Divergence(..), topDiv, botDiv, exnDiv, lubDivergence, isDeadEndDiv,

    -- * Demand types
    DmdType(..), dmdTypeDepth,
    -- ** Algebra
    nopDmdType, botDmdType,
    lubDmdType, plusDmdType, multDmdType,
    -- *** PlusDmdArg
    PlusDmdArg, mkPlusDmdArg, toPlusDmdArg,
    -- ** Other operations
    peelFV, findIdDemand, addDemand, splitDmdTy, deferAfterPreciseException,
    keepAliveDmdType,

    -- * Demand signatures
    StrictSig(..), mkStrictSigForArity, mkClosedStrictSig,
    splitStrictSig, strictSigDmdEnv, hasDemandEnvSig,
    nopSig, botSig, isTopSig, isDeadEndSig, appIsDeadEnd,
    -- ** Handling arity adjustments
    prependArgsStrictSig, etaConvertStrictSig,

    -- * Demand transformers from demand signatures
    DmdTransformer, dmdTransformSig, dmdTransformDataConSig, dmdTransformDictSelSig,

    -- * Trim to a type shape
    TypeShape(..), trimToType,

    -- * @seq@ing stuff
    seqDemand, seqDemandList, seqDmdType, seqStrictSig,

    -- * Zapping usage information
    zapUsageDemand, zapDmdEnvSig, zapUsedOnceDemand, zapUsedOnceSig
  ) where

#include "HsVersions.h"

import GHC.Prelude

import GHC.Types.Var ( Var, Id )
import GHC.Types.Var.Env
import GHC.Types.Var.Set
import GHC.Types.Unique.FM
import GHC.Types.Basic
import GHC.Data.Maybe   ( orElse )

import GHC.Core.Type    ( Type )
import GHC.Core.TyCon   ( isNewTyCon, isClassTyCon )
import GHC.Core.DataCon ( splitDataProductType_maybe )
import GHC.Core.Multiplicity    ( scaledThing )

import GHC.Utils.Binary
import GHC.Utils.Misc
import GHC.Utils.Outputable
import GHC.Utils.Panic

{-
************************************************************************
*                                                                      *
           Card: Combining Strictness and Usage
*                                                                      *
************************************************************************
-}

-- | Describes an interval of /evaluation cardinalities/.
-- @C_lu@ means "evaluated /at least/ @l@ and /at most/ @u@ times".
-- The lower bound corresponds to /strictness/ (hence @l@ is either @0@ or @1@),
-- the upper bound corresponds to /usage/      (@u@ is one of @0@, @1@, @n@).
--
-- Intervals describe sets, so the underlying lattice is the powerset lattice.
data Card
  = C_00 -- ^ {0}     Absent.
  | C_01 -- ^ {0,1}   Used at most once.
  | C_0N -- ^ {0,1,n} Every possible cardinality; the top element.
  | C_11 -- ^ {1}     Strict and used once.
  | C_1N -- ^ {1,n}   Strict and used (possibly) many times.
  | C_10 -- ^ {}      The empty interval; the bottom element of the lattice.
  deriving Eq

_botCard, topCard :: Card
_botCard = C_10
topCard = C_0N

-- | True <=> lower bound is 1.
isStrict :: Card -> Bool
isStrict C_10 = True
isStrict C_11 = True
isStrict C_1N = True
isStrict _    = False

-- | True <=> upper bound is 0.
isAbs :: Card -> Bool
isAbs C_00 = True
isAbs C_10 = True -- Bottom cardinality is also absent
isAbs _    = False

-- | True <=> upper bound is 1.
isUsedOnce :: Card -> Bool
isUsedOnce C_0N = False
isUsedOnce C_1N = False
isUsedOnce _    = True

-- | Intersect with [0,1].
oneifyCard :: Card -> Card
oneifyCard C_0N = C_01
oneifyCard C_1N = C_11
oneifyCard c    = c

-- | Denotes '∪' on 'Card'.
lubCard :: Card -> Card -> Card
-- Handle C_10 (bot)
lubCard C_10 n    = n    -- bot
lubCard n    C_10 = n    -- bot
-- Handle C_0N (top)
lubCard C_0N _    = C_0N -- top
lubCard _    C_0N = C_0N -- top
-- Handle C_11
lubCard C_00 C_11 = C_01 -- {0} ∪ {1} = {0,1}
lubCard C_11 C_00 = C_01 -- {0} ∪ {1} = {0,1}
lubCard C_11 n    = n    -- {1} is a subset of all other intervals
lubCard n    C_11 = n    -- {1} is a subset of all other intervals
-- Handle C_1N
lubCard C_1N C_1N = C_1N -- reflexivity
lubCard _    C_1N = C_0N -- {0} ∪ {1,n} = top
lubCard C_1N _    = C_0N -- {0} ∪ {1,n} = top
-- Handle C_01
lubCard C_01 _    = C_01 -- {0} ∪ {0,1} = {0,1}
lubCard _    C_01 = C_01 -- {0} ∪ {0,1} = {0,1}
-- Handle C_00
lubCard C_00 C_00 = C_00 -- reflexivity

-- | Denotes '+' on 'Card'.
plusCard :: Card -> Card -> Card
-- Handle C_00
plusCard C_00 n    = n    -- {0}+n = n
plusCard n    C_00 = n    -- {0}+n = n
-- Handle C_10
plusCard C_10 C_01 = C_11 -- These follow by applying + to lower and upper
plusCard C_10 C_0N = C_1N -- bounds individually
plusCard C_10 n    = n
plusCard C_01 C_10 = C_11
plusCard C_0N C_10 = C_1N
plusCard n    C_10 = n
-- Handle the rest (C_01, C_0N, C_11, C_1N)
plusCard C_01 C_01 = C_0N -- The upper bound is at least 1, so upper bound of
plusCard C_01 C_0N = C_0N -- the result must be 1+1 ~= N.
plusCard C_0N C_01 = C_0N -- But for the lower bound we have 4 cases where
plusCard C_0N C_0N = C_0N -- 0+0 ~= 0 (as opposed to 1), so we match on these.
plusCard _    _    = C_1N -- Otherwise we return {1,n}

-- | Denotes '*' on 'Card'.
multCard :: Card -> Card -> Card
-- Handle C_11 (neutral element)
multCard C_11 c    = c
multCard c    C_11 = c
-- Handle C_00 (annihilating element)
multCard C_00 _    = C_00
multCard _    C_00 = C_00
-- Handle C_10
multCard C_10 c    = if isStrict c then C_10 else C_00
multCard c    C_10 = if isStrict c then C_10 else C_00
-- Handle reflexive C_1N, C_01
multCard C_1N C_1N = C_1N
multCard C_01 C_01 = C_01
-- Handle C_0N and the rest (C_01, C_1N):
multCard _    _    = C_0N

{-
************************************************************************
*                                                                      *
           Demand: Evaluation contexts
*                                                                      *
************************************************************************
-}

-- | A demand describes a /scaled evaluation context/, e.g. how many times
-- and how deep the denoted thing is evaluated.
--
-- The "how many" component is represented by a 'Card'inality.
-- The "how deep" component is represented by a 'SubDemand'.
-- Examples (using Note [Demand notation]):
--
--   * 'seq' puts demand @SA@ on its argument: It evaluates the argument
--     strictly (@S@), but not any deeper (@A@).
--   * 'fst' puts demand @SP(SU,A)@ on its argument: It evaluates the argument
--     pair strictly and the first component strictly, but no nested info
--     beyond that (@U@). Its second argument is not used at all.
--   * '$' puts demand @SCS(U)@ on its first argument: It calls (@C@) the
--     argument function with one argument, exactly once (@S@). No info
--     on how the result of that call is evaluated (@U@).
--   * 'maybe' puts demand @1C1(U)@ on its second argument: It evaluates
--     the argument function lazily and calls it once when it is evaluated.
--   * @fst p + fst p@ puts demand @MP(MU,A)@ on @p@: It's @SP(SU,A)@
--     multiplied by two, so we get @M@ (used at least once, possibly multiple
--     times).
--
-- This data type is quite similar to @'Scaled' 'SubDemand'@, but it's scaled
-- by 'Card', which is an /interval/ on 'Multiplicity', the upper bound of
-- which could be used to infer uniqueness types.
data Demand
  = !Card :* !SubDemand
  deriving Eq

-- | A sub-demand describes an /evaluation context/, e.g. how deep the
-- denoted thing is evaluated. See 'Demand' for examples.
--
-- The nested 'SubDemand' @d@ of a 'Call' @Cn(d)@ is /relative/ to a single such call.
-- E.g. The expression @f 1 2 + f 3 4@ puts call demand @MCM(CS(U))@ on @f@:
-- @f@ is called exactly twice (@M@), each time exactly once (@S@) with an
-- additional argument.
--
-- The nested 'Demand's @dn@ of a 'Prod' @P(d1,d2,...)@ apply /absolutely/:
-- If @dn@ is a used once demand (cf. 'isUsedOnce'), then that means that
-- the denoted sub-expression is used once in the entire evaluation context
-- described by the surrounding 'Demand'. E.g., @UP(1U)@ means that the
-- field of the denoted expression is used at most once, although the
-- entire expression might be used many times.
--
-- See Note [Call demands are relative]
-- and Note [Demand notation].
data SubDemand
  = Poly !Card
  -- ^ Polymorphic demand, the denoted thing is evaluated arbitrarily deep,
  -- with the specified cardinality at every level.
  -- Expands to 'Call' via 'viewCall' and to 'Prod' via 'viewProd'.
  --
  -- @Poly n@ is semantically equivalent to @Prod [n :* Poly n, ...]@ or
  -- @Call n (Poly n)@. 'mkCall' and 'mkProd' do these rewrites.
  --
  -- In Note [Demand notation]: @U === P(U,U,...)@ and @U === CU(U)@,
  --                            @S === P(S,S,...)@ and @S === CS(S)@, and so on.
  --
  -- We only really use 'Poly' with 'C_10' (bottom), 'C_00' (absent),
  -- 'C_0N' (top) and sometimes 'C_1N', but it's simpler to treat it uniformly
  -- than to have a special constructor for each of the three cases.
  | Call !Card !SubDemand
  -- ^ @Call n sd@ describes the evaluation context of @n@ function
  -- applications, where every individual result is evaluated according to @sd@.
  -- @sd@ is /relative/ to a single call, cf. Note [Call demands are relative].
  -- Used only for values of function type. Use the smart constructor 'mkCall'
  -- whenever possible!
  | Prod ![Demand]
  -- ^ @Prod ds@ describes the evaluation context of a case scrutinisation
  -- on an expression of product type, where the product components are
  -- evaluated according to @ds@.
  deriving Eq

poly00, poly01, poly0N, poly11, poly1N, poly10 :: SubDemand
topSubDmd, botSubDmd, seqSubDmd :: SubDemand
poly00 = Poly C_00
poly01 = Poly C_01
poly0N = Poly C_0N
poly11 = Poly C_11
poly1N = Poly C_1N
poly10 = Poly C_10
topSubDmd = poly0N
botSubDmd = poly10
seqSubDmd = poly00

polyDmd :: Card -> Demand
polyDmd C_00 = C_00 :* poly00
polyDmd C_01 = C_01 :* poly01
polyDmd C_0N = C_0N :* poly0N
polyDmd C_11 = C_11 :* poly11
polyDmd C_1N = C_1N :* poly1N
polyDmd C_10 = C_10 :* poly10

-- | A smart constructor for 'Prod', applying rewrite rules along the semantic
-- equality @Prod [polyDmd n, ...] === polyDmd n@, simplifying to 'Poly'
-- 'SubDemand's when possible. Note that this degrades boxity information! E.g. a
-- polymorphic demand will never unbox.
mkProd :: [Demand] -> SubDemand
mkProd [] = seqSubDmd
mkProd ds@(n:*sd : _)
  | want_to_simplify n, all (== polyDmd n) ds = sd
  | otherwise                                 = Prod ds
  where
    -- We only want to simplify absent and bottom demands and unbox the others.
    -- See also Note [U should win] and Note [Don't optimise UP(U,U,...) to U].
    want_to_simplify C_00 = True
    want_to_simplify C_10 = True
    want_to_simplify _    = False

-- | @viewProd n sd@ interprets @sd@ as a 'Prod' of arity @n@, expanding 'Poly'
-- demands as necessary.
viewProd :: Arity -> SubDemand -> Maybe [Demand]
-- It's quite important that this function is optimised well;
-- it is used by lubSubDmd and plusSubDmd. Note the strict
-- application to 'polyDmd':
viewProd n (Prod ds)   | ds `lengthIs` n = Just ds
-- Note the strict application to replicate: This makes sure we don't allocate
-- a thunk for it, inlines it and lets case-of-case fire at call sites.
viewProd n (Poly card)                   = Just (replicate n $! polyDmd card)
viewProd _ _                             = Nothing
{-# INLINE viewProd #-} -- we want to fuse away the replicate and the allocation
                        -- for Arity. Otherwise, #18304 bites us.

-- | A smart constructor for 'Call', applying rewrite rules along the semantic
-- equality @Call n (Poly n) === Poly n@, simplifying to 'Poly' 'SubDemand's
-- when possible.
mkCall :: Card -> SubDemand -> SubDemand
mkCall n cd@(Poly m) | n == m = cd
mkCall n cd                   = Call n cd

-- | @viewCall sd@ interprets @sd@ as a 'Call', expanding 'Poly' demands as
-- necessary.
viewCall :: SubDemand -> Maybe (Card, SubDemand)
viewCall (Call n sd)    = Just (n, sd)
viewCall sd@(Poly card) = Just (card, sd)
viewCall _              = Nothing

topDmd, absDmd, botDmd, seqDmd :: Demand
topDmd = polyDmd C_0N
absDmd = polyDmd C_00
botDmd = polyDmd C_10
seqDmd = C_11 :* seqSubDmd

-- | Denotes '∪' on 'SubDemand'.
lubSubDmd :: SubDemand -> SubDemand -> SubDemand
-- Handle Prod
lubSubDmd (Prod ds1) (viewProd (length ds1) -> Just ds2) =
  Prod $ zipWith lubDmd ds2 ds1 -- try to fuse with ds2
-- Handle Call
lubSubDmd (Call n1 d1) (viewCall -> Just (n2, d2))
  -- See Note [Call demands are relative]
  | isAbs n1  = mkCall (lubCard n1 n2) (lubSubDmd botSubDmd d2)
  | isAbs n2  = mkCall (lubCard n1 n2) (lubSubDmd d1 botSubDmd)
  | otherwise = mkCall (lubCard n1 n2) (lubSubDmd d1        d2)
-- Handle Poly
lubSubDmd (Poly n1)  (Poly n2) = Poly (lubCard n1 n2)
-- Make use of reflexivity (so we'll match the Prod or Call cases again).
lubSubDmd sd1@Poly{} sd2       = lubSubDmd sd2 sd1
-- Otherwise (Call `lub` Prod) return Top
lubSubDmd _          _         = topSubDmd

-- | Denotes '∪' on 'Demand'.
lubDmd :: Demand -> Demand -> Demand
lubDmd (n1 :* sd1) (n2 :* sd2) = lubCard n1 n2 :* lubSubDmd sd1 sd2

-- | Denotes '+' on 'SubDemand'.
plusSubDmd :: SubDemand -> SubDemand -> SubDemand
-- Handle Prod
plusSubDmd (Prod ds1) (viewProd (length ds1) -> Just ds2) =
  Prod $ zipWith plusDmd ds2 ds1 -- try to fuse with ds2
-- Handle Call
plusSubDmd (Call n1 d1) (viewCall -> Just (n2, d2))
  -- See Note [Call demands are relative]
  | isAbs n1  = mkCall (plusCard n1 n2) (lubSubDmd botSubDmd d2)
  | isAbs n2  = mkCall (plusCard n1 n2) (lubSubDmd d1 botSubDmd)
  | otherwise = mkCall (plusCard n1 n2) (lubSubDmd d1        d2)
-- Handle Poly
plusSubDmd (Poly n1)  (Poly n2) = Poly (plusCard n1 n2)
-- Make use of reflexivity (so we'll match the Prod or Call cases again).
plusSubDmd sd1@Poly{} sd2       = plusSubDmd sd2 sd1
-- Otherwise (Call `lub` Prod) return Top
plusSubDmd _          _         = topSubDmd

-- | Denotes '+' on 'Demand'.
plusDmd :: Demand -> Demand -> Demand
plusDmd (n1 :* sd1) (n2 :* sd2) = plusCard n1 n2 :* plusSubDmd sd1 sd2

-- | The trivial cases of the @mult*@ functions.
-- If @multTrivial n abs a = ma@, we have the following outcomes
-- depending on @n@:
--
--   * 'C_11' => multiply by one, @ma = Just a@
--   * 'C_00', 'C_10' (e.g. @'isAbs' n@) => return the absent thing,
--      @ma = Just abs@
--   * Otherwise ('C_01', 'C_*N') it's not a trivial case, @ma = Nothing@.
multTrivial :: Card -> a -> a -> Maybe a
multTrivial C_11 _   a           = Just a
multTrivial n    abs _ | isAbs n = Just abs
multTrivial _    _   _           = Nothing

multSubDmd :: Card -> SubDemand -> SubDemand
multSubDmd n sd
  | Just sd' <- multTrivial n seqSubDmd sd = sd'
multSubDmd n (Poly n')    = Poly (multCard n n')
multSubDmd n (Call n' sd) = mkCall (multCard n n') sd -- See Note [Call demands are relative]
multSubDmd n (Prod ds)    = Prod (map (multDmd n) ds)

multDmd :: Card -> Demand -> Demand
multDmd n    dmd
  | Just dmd' <- multTrivial n absDmd dmd = dmd'
multDmd n (m :* dmd) = multCard n m :* multSubDmd n dmd

-- | Used to suppress pretty-printing of an uninformative demand
isTopDmd :: Demand -> Bool
isTopDmd dmd = dmd == topDmd

isAbsDmd :: Demand -> Bool
isAbsDmd (n :* _) = isAbs n

-- | Not absent and used strictly. See Note [Strict demands]
isStrUsedDmd :: Demand -> Bool
isStrUsedDmd (n :* _) = isStrict n && not (isAbs n)

isSeqDmd :: Demand -> Bool
isSeqDmd (C_11 :* sd) = sd == seqSubDmd
isSeqDmd (C_1N :* sd) = sd == seqSubDmd -- I wonder if we need this case.
isSeqDmd _            = False

-- | Is the value used at most once?
isUsedOnceDmd :: Demand -> Bool
isUsedOnceDmd (n :* _) = isUsedOnce n

-- | We try to avoid tracking weak free variable demands in strictness
-- signatures for analysis performance reasons.
-- See Note [Lazy and unleashable free variables] in "GHC.Core.Opt.DmdAnal".
isWeakDmd :: Demand -> Bool
isWeakDmd dmd@(n :* _) = not (isStrict n) && is_plus_idem_dmd dmd
  where
    -- @is_plus_idem_* thing@ checks whether @thing `plus` thing = thing@,
    -- e.g. if @thing@ is idempotent wrt. to @plus@.
    is_plus_idem_card c = plusCard c c == c
    -- is_plus_idem_dmd dmd = plusDmd dmd dmd == dmd
    is_plus_idem_dmd (n :* sd) = is_plus_idem_card n && is_plus_idem_sub_dmd sd
    -- is_plus_idem_sub_dmd sd = plusSubDmd sd sd == sd
    is_plus_idem_sub_dmd (Poly n)   = is_plus_idem_card n
    is_plus_idem_sub_dmd (Prod ds)  = all is_plus_idem_dmd ds
    is_plus_idem_sub_dmd (Call n _) = is_plus_idem_card n -- See Note [Call demands are relative]

evalDmd :: Demand
evalDmd = C_1N :* topSubDmd

-- | First argument of 'GHC.Exts.maskAsyncExceptions#': @SCS(U)@.
-- Called exactly once.
strictOnceApply1Dmd :: Demand
strictOnceApply1Dmd = C_11 :* mkCall C_11 topSubDmd

-- | First argument of 'GHC.Exts.atomically#': @MCM(U)@.
-- Called at least once, possibly many times.
strictManyApply1Dmd :: Demand
strictManyApply1Dmd = C_1N :* mkCall C_1N topSubDmd

-- | First argument of catch#: @1C1(U)@.
-- Evaluates its arg lazily, but then applies it exactly once to one argument.
lazyApply1Dmd :: Demand
lazyApply1Dmd = C_01 :* mkCall C_01 topSubDmd

-- | Second argument of catch#: @1C1(CS(U))@.
-- Calls its arg lazily, but then applies it exactly once to an additional argument.
lazyApply2Dmd :: Demand
lazyApply2Dmd = C_01 :* mkCall C_01 (mkCall C_11 topSubDmd)

-- | Make a 'Demand' evaluated at-most-once.
oneifyDmd :: Demand -> Demand
oneifyDmd (n :* sd) = oneifyCard n :* sd

-- | Make a 'Demand' evaluated at-least-once (e.g. strict).
strictifyDmd :: Demand -> Demand
strictifyDmd (n :* sd) = plusCard C_10 n :* sd

-- | If the argument is a used non-newtype dictionary, give it strict demand.
-- Also split the product type & demand and recur in order to similarly
-- strictify the argument's contained used non-newtype superclass dictionaries.
-- We use the demand as our recursive measure to guarantee termination.
strictifyDictDmd :: Type -> Demand -> Demand
strictifyDictDmd ty (n :* Prod ds)
  | not (isAbs n)
  , Just field_tys <- as_non_newtype_dict ty
  = C_1N :* -- main idea: ensure it's strict
      if all (not . isAbsDmd) ds
        then topSubDmd -- abstract to strict w/ arbitrary component use,
                         -- since this smells like reboxing; results in CBV
                         -- boxed
                         --
                         -- TODO revisit this if we ever do boxity analysis
        else Prod (zipWith strictifyDictDmd field_tys ds)
  where
    -- | Return a TyCon and a list of field types if the given
    -- type is a non-newtype dictionary type
    as_non_newtype_dict ty
      | Just (tycon, _arg_tys, _data_con, map scaledThing -> inst_con_arg_tys)
          <- splitDataProductType_maybe ty
      , not (isNewTyCon tycon)
      , isClassTyCon tycon
      = Just inst_con_arg_tys
      | otherwise
      = Nothing
strictifyDictDmd _  dmd = dmd

-- | Wraps the 'SubDemand' with a one-shot call demand: @d@ -> @CS(d)@.
mkCalledOnceDmd :: SubDemand -> SubDemand
mkCalledOnceDmd sd = mkCall C_11 sd

-- | @mkCalledOnceDmds n d@ returns @CS(CS...(CS d))@ where there are @n@ @CS@'s.
mkCalledOnceDmds :: Arity -> SubDemand -> SubDemand
mkCalledOnceDmds arity sd = iterate mkCalledOnceDmd sd !! arity

-- | Peels one call level from the sub-demand, and also returns how many
-- times we entered the lambda body.
peelCallDmd :: SubDemand -> (Card, SubDemand)
peelCallDmd sd = viewCall sd `orElse` (topCard, topSubDmd)

-- Peels multiple nestings of 'Call' sub-demands and also returns
-- whether it was unsaturated in the form of a 'Card'inality, denoting
-- how many times the lambda body was entered.
-- See Note [Demands from unsaturated function calls].
peelManyCalls :: Int -> SubDemand -> Card
peelManyCalls 0 _                          = C_11
-- See Note [Call demands are relative]
peelManyCalls n (viewCall -> Just (m, sd)) = m `multCard` peelManyCalls (n-1) sd
peelManyCalls _ _                          = C_0N

-- See Note [Demand on the worker] in GHC.Core.Opt.WorkWrap
mkWorkerDemand :: Int -> Demand
mkWorkerDemand n = C_01 :* go n
  where go 0 = topSubDmd
        go n = Call C_01 $ go (n-1)

addCaseBndrDmd :: SubDemand -- On the case binder
               -> [Demand]  -- On the components of the constructor
               -> [Demand]  -- Final demands for the components of the constructor
addCaseBndrDmd (Poly n) alt_dmds
  | isAbs n   = alt_dmds
-- See Note [Demand on case-alternative binders]
addCaseBndrDmd sd       alt_dmds = zipWith plusDmd ds alt_dmds -- fuse ds!
  where
    Just ds = viewProd (length alt_dmds) sd -- Guaranteed not to be a call

argsOneShots :: StrictSig -> Arity -> [[OneShotInfo]]
-- ^ See Note [Computing one-shot info]
argsOneShots (StrictSig (DmdType _ arg_ds _)) n_val_args
  | unsaturated_call = []
  | otherwise = go arg_ds
  where
    unsaturated_call = arg_ds `lengthExceeds` n_val_args

    go []               = []
    go (arg_d : arg_ds) = argOneShots arg_d `cons` go arg_ds

    -- Avoid list tail like [ [], [], [] ]
    cons [] [] = []
    cons a  as = a:as

argOneShots :: Demand          -- ^ depending on saturation
            -> [OneShotInfo]
-- ^ See Note [Computing one-shot info]
argOneShots (_ :* sd) = go sd -- See Note [Call demands are relative]
  where
    go (Call n sd)
      | isUsedOnce n = OneShotLam    : go sd
      | otherwise    = NoOneShotInfo : go sd
    go _    = []

-- |
-- @saturatedByOneShots n C1(C1(...)) = True@
--   <=>
-- There are at least n nested C1(..) calls.
-- See Note [Demand on the worker] in GHC.Core.Opt.WorkWrap
saturatedByOneShots :: Int -> Demand -> Bool
saturatedByOneShots n (_ :* sd) = isUsedOnce (peelManyCalls n sd)

{- Note [Strict demands]
~~~~~~~~~~~~~~~~~~~~~~~~
'isStrUsedDmd' returns true only of demands that are
   both strict
   and  used
In particular, it is False for <B>, which can and does
arise in, say (#7319)
   f x = raise# <some exception>
Then 'x' is not used, so f gets strictness <B> -> .
Now the w/w generates
   fx = let x <B> = absentError "unused"
        in raise <some exception>
At this point we really don't want to convert to
   fx = case absentError "unused" of x -> raise <some exception>
Since the program is going to diverge, this swaps one error for another,
but it's really a bad idea to *ever* evaluate an absent argument.
In #7319 we get
   T7319.exe: Oops!  Entered absent arg w_s1Hd{v} [lid] [base:GHC.Base.String{tc 36u}]

Note [Call demands are relative]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The expression @if b then 0 else f 1 2 + f 3 4@ uses @f@ according to the demand
@UCU(CS(P(U)))@, meaning

  "f is called multiple times or not at all (CU), but each time it
   is called, it's called with *exactly one* (CS) more argument.
   Whenever it is called with two arguments, we have no info on how often
   the field of the product result is used (U)."

So the 'SubDemand' nested in a 'Call' demand is relative to exactly one call.
And that extends to the information we have how its results are used in each
call site. Consider (#18903)

  h :: Int -> Int
  h m =
    let g :: Int -> (Int,Int)
        g 1 = (m, 0)
        g n = (2 * n, 2 `div` n)
        {-# NOINLINE g #-}
    in case m of
      1 -> 0
      2 -> snd (g m)
      _ -> uncurry (+) (g m)

We want to give @g@ the demand @1C1(P(1P(U),SP(U)))@, so we see that in each call
site of @g@, we are strict in the second component of the returned pair.

This relative cardinality leads to an otherwise unexpected call to 'lubSubDmd'
in 'plusSubDmd', but if you do the math it's just the right thing.

There's one more subtlety: Since the nested demand is relative to exactly one
call, in the case where we have *at most zero calls* (e.g. CA(...)), the premise
is hurt and we can assume that the nested demand is 'botSubDmd'. That ensures
that @g@ above actually gets the @SP(U)@ demand on its second pair component,
rather than the lazy @1P(U)@ if we 'lub'bed with an absent demand.

Demand on case-alternative binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The demand on a binder in a case alternative comes
  (a) From the demand on the binder itself
  (b) From the demand on the case binder
Forgetting (b) led directly to #10148.

Example. Source code:
  f x@(p,_) = if p then foo x else True

  foo (p,True) = True
  foo (p,q)    = foo (q,p)

After strictness analysis:
  f = \ (x_an1 [Dmd=<SP(SL),1*UP(U,1*U)>] :: (Bool, Bool)) ->
      case x_an1
      of wild_X7 [Dmd=<L,1*UP(1*U,1*U)>]
      { (p_an2 [Dmd=<S,1*U>], ds_dnz [Dmd=<L,A>]) ->
      case p_an2 of _ {
        False -> GHC.Types.True;
        True -> foo wild_X7 }

It's true that ds_dnz is *itself* absent, but the use of wild_X7 means
that it is very much alive and demanded.  See #10148 for how the
consequences play out.

This is needed even for non-product types, in case the case-binder
is used but the components of the case alternative are not.

Note [Don't optimise UP(U,U,...) to U]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These two SubDemands:
   UP(U,U) (@Prod [topDmd, topDmd]@)   and   U (@topSubDmd@)
are semantically equivalent, but we do not turn the former into
the latter, for a regrettable-subtle reason.  Consider
  f p1@(x,y) = (y,x)
  g h p2@(_,_) = h p
We want to unbox @p1@ of @f@, but not @p2@ of @g@, because @g@ only uses
@p2@ boxed and we'd have to rebox. So we give @p1@ demand UP(U,U) and @p2@
demand @U@ to inform 'GHC.Core.Opt.WorkWrap.Utils.wantToUnbox', which will
say "unbox" for @p1@ and "don't unbox" for @p2@.

So the solution is: don't aggressively collapse @Prod [topDmd, topDmd]@ to
@topSubDmd@; instead leave it as-is. In effect we are using the UseDmd to do a
little bit of boxity analysis.  Not very nice.

Note [U should win]
~~~~~~~~~~~~~~~~~~~
Both in 'lubSubDmd' and 'plusSubDmd' we want @U `plusSubDmd` UP(..)) to be @U@.
Why?  Because U carries the implication the whole thing is used, box and all,
so we don't want to w/w it, cf. Note [Don't optimise UP(U,U,...) to U].
If we use it both boxed and unboxed, then we are definitely using the box,
and so we are quite likely to pay a reboxing cost. So we make U win here.
TODO: Investigate why since 2013, we don't.

Example is in the Buffer argument of GHC.IO.Handle.Internals.writeCharBuffer

Baseline: (A) Not making Used win (UProd wins)
Compare with: (B) making Used win for lub and both

            Min          -0.3%     -5.6%    -10.7%    -11.0%    -33.3%
            Max          +0.3%    +45.6%    +11.5%    +11.5%     +6.9%
 Geometric Mean          -0.0%     +0.5%     +0.3%     +0.2%     -0.8%

Baseline: (B) Making Used win for both lub and both
Compare with: (C) making Used win for plus, but UProd win for lub

            Min          -0.1%     -0.3%     -7.9%     -8.0%     -6.5%
            Max          +0.1%     +1.0%    +21.0%    +21.0%     +0.5%
 Geometric Mean          +0.0%     +0.0%     -0.0%     -0.1%     -0.1%

Note [Computing one-shot info]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider a call
    f (\pqr. e1) (\xyz. e2) e3
where f has usage signature
    C1(C(C1(U))) C1(U) U
Then argsOneShots returns a [[OneShotInfo]] of
    [[OneShot,NoOneShotInfo,OneShot],  [OneShot]]
The occurrence analyser propagates this one-shot infor to the
binders \pqr and \xyz;
see Note [Use one-shot information] in "GHC.Core.Opt.OccurAnal".
-}

{- *********************************************************************
*                                                                      *
                 Divergence: Whether evaluation surely diverges
*                                                                      *
********************************************************************* -}

-- | 'Divergence' characterises whether something surely diverges.
-- Models a subset lattice of the following exhaustive set of divergence
-- results:
--
-- [n] nontermination (e.g. loops)
-- [i] throws imprecise exception
-- [p] throws precise exceTtion
-- [c] converges (reduces to WHNF).
--
-- The different lattice elements correspond to different subsets, indicated by
-- juxtaposition of indicators (e.g. __nc__ definitely doesn't throw an
-- exception, and may or may not reduce to WHNF).
--
-- @
--             Dunno (nipc)
--                  |
--            ExnOrDiv (nip)
--                  |
--            Diverges (ni)
-- @
--
-- As you can see, we don't distinguish __n__ and __i__.
-- See Note [Precise exceptions and strictness analysis] for why __p__ is so
-- special compared to __i__.
data Divergence
  = Diverges -- ^ Definitely throws an imprecise exception or diverges.
  | ExnOrDiv -- ^ Definitely throws a *precise* exception, an imprecise
             --   exception or diverges. Never converges, hence 'isDeadEndDiv'!
             --   See scenario 1 in Note [Precise exceptions and strictness analysis].
  | Dunno    -- ^ Might diverge, throw any kind of exception or converge.
  deriving Eq

lubDivergence :: Divergence -> Divergence -> Divergence
lubDivergence Diverges div      = div
lubDivergence div      Diverges = div
lubDivergence ExnOrDiv ExnOrDiv = ExnOrDiv
lubDivergence _        _        = Dunno
-- This needs to commute with defaultFvDmd, i.e.
-- defaultFvDmd (r1 `lubDivergence` r2) = defaultFvDmd r1 `lubDmd` defaultFvDmd r2
-- (See Note [Default demand on free variables and arguments] for why)

-- | See Note [Asymmetry of 'plus*'], which concludes that 'plusDivergence'
-- needs to be symmetric.
-- Strictly speaking, we should have @plusDivergence Dunno Diverges = ExnOrDiv@.
-- But that regresses in too many places (every infinite loop, basically) to be
-- worth it and is only relevant in higher-order scenarios
-- (e.g. Divergence of @f (throwIO blah)@).
-- So 'plusDivergence' currently is 'glbDivergence', really.
plusDivergence :: Divergence -> Divergence -> Divergence
plusDivergence Dunno    Dunno    = Dunno
plusDivergence Diverges _        = Diverges
plusDivergence _        Diverges = Diverges
plusDivergence _        _        = ExnOrDiv

-- | In a non-strict scenario, we might not force the Divergence, in which case
-- we might converge, hence Dunno.
multDivergence :: Card -> Divergence -> Divergence
multDivergence n _ | not (isStrict n) = Dunno
multDivergence _ d                    = d

topDiv, exnDiv, botDiv :: Divergence
topDiv = Dunno
exnDiv = ExnOrDiv
botDiv = Diverges

-- | True if the 'Divergence' indicates that evaluation will not return.
-- See Note [Dead ends].
isDeadEndDiv :: Divergence -> Bool
isDeadEndDiv Diverges = True
isDeadEndDiv ExnOrDiv = True
isDeadEndDiv Dunno    = False

-- See Notes [Default demand on free variables and arguments]
-- and Scenario 1 in [Precise exceptions and strictness analysis]
defaultFvDmd :: Divergence -> Demand
defaultFvDmd Dunno    = absDmd
defaultFvDmd ExnOrDiv = absDmd -- This is the whole point of ExnOrDiv!
defaultFvDmd Diverges = botDmd -- Diverges

defaultArgDmd :: Divergence -> Demand
-- TopRes and BotRes are polymorphic, so that
--      BotRes === (Bot -> BotRes) === ...
--      TopRes === (Top -> TopRes) === ...
-- This function makes that concrete
-- Also see Note [Default demand on free variables and arguments]
defaultArgDmd Dunno    = topDmd
-- NB: not botDmd! We don't want to mask the precise exception by forcing the
-- argument. But it is still absent.
defaultArgDmd ExnOrDiv = absDmd
defaultArgDmd Diverges = botDmd

{- Note [Precise vs imprecise exceptions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An exception is considered to be /precise/ when it is thrown by the 'raiseIO#'
primop. It follows that all other primops (such as 'raise#' or
division-by-zero) throw /imprecise/ exceptions. Note that the actual type of
the exception thrown doesn't have any impact!

GHC undertakes some effort not to apply an optimisation that would mask a
/precise/ exception with some other source of nontermination, such as genuine
divergence or an imprecise exception, so that the user can reliably
intercept the precise exception with a catch handler before and after
optimisations.

See also the wiki page on precise exceptions:
https://gitlab.haskell.org/ghc/ghc/wikis/exceptions/precise-exceptions
Section 5 of "Tackling the awkward squad" talks about semantic concerns.
Imprecise exceptions are actually more interesting than precise ones (which are
fairly standard) from the perspective of semantics. See the paper "A Semantics
for Imprecise Exceptions" for more details.

Note [Dead ends]
~~~~~~~~~~~~~~~~
We call an expression that either diverges or throws a precise or imprecise
exception a "dead end". We used to call such an expression just "bottoming",
but with the measures we take to preserve precise exception semantics
(see Note [Precise exceptions and strictness analysis]), that is no longer
accurate: 'exnDiv' is no longer the bottom of the Divergence lattice.

Yet externally to demand analysis, we mostly care about being able to drop dead
code etc., which is all due to the property that such an expression never
returns, hence we consider throwing a precise exception to be a dead end.
See also 'isDeadEndDiv'.

Note [Precise exceptions and strictness analysis]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We have to take care to preserve precise exception semantics in strictness
analysis (#17676). There are two scenarios that need careful treatment.

The fixes were discussed at
https://gitlab.haskell.org/ghc/ghc/wikis/fixing-precise-exceptions

Recall that raiseIO# raises a *precise* exception, in contrast to raise# which
raises an *imprecise* exception. See Note [Precise vs imprecise exceptions].

Scenario 1: Precise exceptions in case alternatives
---------------------------------------------------
Unlike raise# (which returns botDiv), we want raiseIO# to return exnDiv.
Here's why. Consider this example from #13380 (similarly #17676):
  f x y | x>0       = raiseIO# Exc
        | y>0       = return 1
        | otherwise = return 2
Is 'f' strict in 'y'? One might be tempted to say yes! But that plays fast and
loose with the precise exception; after optimisation, (f 42 (error "boom"))
turns from throwing the precise Exc to throwing the imprecise user error
"boom". So, the defaultFvDmd of raiseIO# should be lazy (topDmd), which can be
achieved by giving it divergence exnDiv.
See Note [Default demand on free variables and arguments].

Why don't we just give it topDiv instead of introducing exnDiv?
Because then the simplifier will fail to discard raiseIO#'s continuation in
  case raiseIO# x s of { (# s', r #) -> <BIG> }
which we'd like to optimise to
  case raiseIO# x s of {}
Hence we came up with exnDiv. The default FV demand of exnDiv is lazy (and
its default arg dmd is absent), but otherwise (in terms of 'isDeadEndDiv') it
behaves exactly as botDiv, so that dead code elimination works as expected.
This is tracked by T13380b.

Scenario 2: Precise exceptions in case scrutinees
-------------------------------------------------
Consider (more complete examples in #148, #1592, testcase strun003)

  case foo x s of { (# s', r #) -> y }

Is this strict in 'y'? Often not! If @foo x s@ might throw a precise exception
(ultimately via raiseIO#), then we must not force 'y', which may fail to
terminate or throw an imprecise exception, until we have performed @foo x s@.

So we have to 'deferAfterPreciseException' (which 'lub's with 'exnDmdType' to
model the exceptional control flow) when @foo x s@ may throw a precise
exception. Motivated by T13380{d,e,f}.
See Note [Which scrutinees may throw precise exceptions] in "GHC.Core.Opt.DmdAnal".

We have to be careful not to discard dead-end Divergence from case
alternatives, though (#18086):

  m = putStrLn "foo" >> error "bar"

'm' should still have 'exnDiv', which is why it is not sufficient to lub with
'nopDmdType' (which has 'topDiv') in 'deferAfterPreciseException'.

Historical Note: This used to be called the "IO hack". But that term is rather
a bad fit because
1. It's easily confused with the "State hack", which also affects IO.
2. Neither "IO" nor "hack" is a good description of what goes on here, which
   is deferring strictness results after possibly throwing a precise exception.
   The "hack" is probably not having to defer when we can prove that the
   expression may not throw a precise exception (increasing precision of the
   analysis), but that's just a favourable guess.

Note [Exceptions and strictness]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We used to smart about catching exceptions, but we aren't anymore.
See #14998 for the way it's resolved at the moment.

Here's a historic breakdown:

Apparently, exception handling prim-ops didn't use to have any special
strictness signatures, thus defaulting to nopSig, which assumes they use their
arguments lazily. Joachim was the first to realise that we could provide richer
information. Thus, in 0558911f91c (Dec 13), he added signatures to
primops.txt.pp indicating that functions like `catch#` and `catchRetry#` call
their argument, which is useful information for usage analysis. Still with a
'Lazy' strictness demand (i.e. 'lazyApply1Dmd'), though, and the world was fine.

In 7c0fff4 (July 15), Simon argued that giving `catch#` et al. a
'strictApply1Dmd' leads to substantial performance gains. That was at the cost
of correctness, as #10712 proved. So, back to 'lazyApply1Dmd' in
28638dfe79e (Dec 15).

Motivated to reproduce the gains of 7c0fff4 without the breakage of #10712,
Ben opened #11222. Simon made the demand analyser "understand catch" in
9915b656 (Jan 16) by adding a new 'catchArgDmd', which basically said to call
its argument strictly, but also swallow any thrown exceptions in
'multDivergence'. This was realized by extending the 'Str' constructor of
'ArgStr' with a 'ExnStr' field, indicating that it catches the exception, and
adding a 'ThrowsExn' constructor to the 'Divergence' lattice as an element
between 'Dunno' and 'Diverges'. Then along came #11555 and finally #13330,
so we had to revert to 'lazyApply1Dmd' again in 701256df88c (Mar 17).

This left the other variants like 'catchRetry#' having 'catchArgDmd', which is
where #14998 picked up. Item 1 was concerned with measuring the impact of also
making `catchRetry#` and `catchSTM#` have 'lazyApply1Dmd'. The result was that
there was none. We removed the last usages of 'catchArgDmd' in 00b8ecb7
(Apr 18). There was a lot of dead code resulting from that change, that we
removed in ef6b283 (Jan 19): We got rid of 'ThrowsExn' and 'ExnStr' again and
removed any code that was dealing with the peculiarities.

Where did the speed-ups vanish to? In #14998, item 3 established that
turning 'catch#' strict in its first argument didn't bring back any of the
alleged performance benefits. Item 2 of that ticket finally found out that it
was entirely due to 'catchException's new (since #11555) definition, which
was simply

    catchException !io handler = catch io handler

While 'catchException' is arguably the saner semantics for 'catch', it is an
internal helper function in "GHC.IO". Its use in
"GHC.IO.Handle.Internals.do_operation" made for the huge allocation differences:
Remove the bang and you find the regressions we originally wanted to avoid with
'catchArgDmd'. See also #exceptions_and_strictness# in "GHC.IO".

So history keeps telling us that the only possibly correct strictness annotation
for the first argument of 'catch#' is 'lazyApply1Dmd', because 'catch#' really
is not strict in its argument: Just try this in GHCi

  :set -XScopedTypeVariables
  import Control.Exception
  catch undefined (\(_ :: SomeException) -> putStrLn "you'll see this")

Any analysis that assumes otherwise will be broken in some way or another
(beyond `-fno-pendantic-bottoms`).

But then #13380 and #17676 suggest (in Mar 20) that we need to re-introduce a
subtly different variant of `ThrowsExn` (which we call `ExnOrDiv` now) that is
only used by `raiseIO#` in order to preserve precise exceptions by strictness
analysis, while not impacting the ability to eliminate dead code.
See Note [Precise exceptions and strictness analysis].

Note [Default demand on free variables and arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Free variables not mentioned in the environment of a 'DmdType'
are demanded according to the demand type's Divergence:
  * In a Diverges (botDiv) context, that demand is botDmd
    (strict and absent).
  * In all other contexts, the demand is absDmd (lazy and absent).
This is recorded in 'defaultFvDmd'.

Similarly, we can eta-expand demand types to get demands on excess arguments
not accounted for in the type, by consulting 'defaultArgDmd':
  * In a Diverges (botDiv) context, that demand is again botDmd.
  * In a ExnOrDiv (exnDiv) context, that demand is absDmd: We surely diverge
    before evaluating the excess argument, but don't want to eagerly evaluate
    it (cf. Note [Precise exceptions and strictness analysis]).
  * In a Dunno context (topDiv), the demand is topDmd, because
    it's perfectly possible to enter the additional lambda and evaluate it
    in unforeseen ways (so, not absent).


************************************************************************
*                                                                      *
           Demand environments and types
*                                                                      *
************************************************************************
-}

-- Subject to Note [Default demand on free variables and arguments]
type DmdEnv = VarEnv Demand

emptyDmdEnv :: VarEnv Demand
emptyDmdEnv = emptyVarEnv

multDmdEnv :: Card -> DmdEnv -> DmdEnv
multDmdEnv n env
  | Just env' <- multTrivial n emptyDmdEnv env = env'
  | otherwise                                  = mapVarEnv (multDmd n) env

reuseEnv :: DmdEnv -> DmdEnv
reuseEnv = multDmdEnv C_1N

-- | @keepAliveDmdType dt vs@ makes sure that the Ids in @vs@ have
-- /some/ usage in the returned demand types -- they are not Absent.
-- See Note [Absence analysis for stable unfoldings and RULES]
--     in "GHC.Core.Opt.DmdAnal".
keepAliveDmdEnv :: DmdEnv -> IdSet -> DmdEnv
keepAliveDmdEnv env vs
  = nonDetStrictFoldVarSet add env vs
  where
    add :: Id -> DmdEnv -> DmdEnv
    add v env = extendVarEnv_C add_dmd env v topDmd

    add_dmd :: Demand -> Demand -> Demand
    -- If the existing usage is Absent, make it used
    -- Otherwise leave it alone
    add_dmd dmd _ | isAbsDmd dmd = topDmd
                  | otherwise    = dmd

-- | Characterises how an expression
--    * Evaluates its free variables ('dt_env')
--    * Evaluates its arguments ('dt_args')
--    * Diverges on every code path or not ('dt_div')
data DmdType
  = DmdType
  { dt_env  :: DmdEnv     -- ^ Demand on explicitly-mentioned free variables
  , dt_args :: [Demand]   -- ^ Demand on arguments
  , dt_div  :: Divergence -- ^ Whether evaluation diverges.
                          -- See Note [Demand type Divergence]
  }

instance Eq DmdType where
  (==) (DmdType fv1 ds1 div1)
       (DmdType fv2 ds2 div2) = nonDetUFMToList fv1 == nonDetUFMToList fv2
         -- It's OK to use nonDetUFMToList here because we're testing for
         -- equality and even though the lists will be in some arbitrary
         -- Unique order, it is the same order for both
                              && ds1 == ds2 && div1 == div2

-- | Compute the least upper bound of two 'DmdType's elicited /by the same
-- incoming demand/!
lubDmdType :: DmdType -> DmdType -> DmdType
lubDmdType d1 d2
  = DmdType lub_fv lub_ds lub_div
  where
    n = max (dmdTypeDepth d1) (dmdTypeDepth d2)
    (DmdType fv1 ds1 r1) = etaExpandDmdType n d1
    (DmdType fv2 ds2 r2) = etaExpandDmdType n d2

    lub_fv  = plusVarEnv_CD lubDmd fv1 (defaultFvDmd r1) fv2 (defaultFvDmd r2)
    lub_ds  = zipWithEqual "lubDmdType" lubDmd ds1 ds2
    lub_div = lubDivergence r1 r2

type PlusDmdArg = (DmdEnv, Divergence)

mkPlusDmdArg :: DmdEnv -> PlusDmdArg
mkPlusDmdArg env = (env, topDiv)

toPlusDmdArg :: DmdType -> PlusDmdArg
toPlusDmdArg (DmdType fv _ r) = (fv, r)

plusDmdType :: DmdType -> PlusDmdArg -> DmdType
plusDmdType (DmdType fv1 ds1 r1) (fv2, t2)
    -- See Note [Asymmetry of 'plus*']
    -- 'plus' takes the argument/result info from its *first* arg,
    -- using its second arg just for its free-var info.
  = DmdType (plusVarEnv_CD plusDmd fv1 (defaultFvDmd r1) fv2 (defaultFvDmd t2))
            ds1
            (r1 `plusDivergence` t2)

botDmdType :: DmdType
botDmdType = DmdType emptyDmdEnv [] botDiv

-- | The demand type of doing nothing (lazy, absent, no Divergence
-- information). Note that it is ''not'' the top of the lattice (which would be
-- "may use everything"), so it is (no longer) called topDmdType.
nopDmdType :: DmdType
nopDmdType = DmdType emptyDmdEnv [] topDiv

isTopDmdType :: DmdType -> Bool
isTopDmdType (DmdType env args div)
  = div == topDiv && null args && isEmptyVarEnv env

-- | The demand type of an unspecified expression that is guaranteed to
-- throw a (precise or imprecise) exception or diverge.
exnDmdType :: DmdType
exnDmdType = DmdType emptyDmdEnv [] exnDiv

dmdTypeDepth :: DmdType -> Arity
dmdTypeDepth = length . dt_args

-- | This makes sure we can use the demand type with n arguments after eta
-- expansion, where n must not be lower than the demand types depth.
-- It appends the argument list with the correct 'defaultArgDmd'.
etaExpandDmdType :: Arity -> DmdType -> DmdType
etaExpandDmdType n d@DmdType{dt_args = ds, dt_div = div}
  | n == depth = d
  | n >  depth = d{dt_args = inc_ds}
  | otherwise  = pprPanic "etaExpandDmdType: arity decrease" (ppr n $$ ppr d)
  where depth = length ds
        -- Arity increase:
        --  * Demands on FVs are still valid
        --  * Demands on args also valid, plus we can extend with defaultArgDmd
        --    as appropriate for the given Divergence
        --  * Divergence is still valid:
        --    - A dead end after 2 arguments stays a dead end after 3 arguments
        --    - The remaining case is Dunno, which is already topDiv
        inc_ds = take n (ds ++ repeat (defaultArgDmd div))

-- | A conservative approximation for a given 'DmdType' in case of an arity
-- decrease. Currently, it's just nopDmdType.
decreaseArityDmdType :: DmdType -> DmdType
decreaseArityDmdType _ = nopDmdType

splitDmdTy :: DmdType -> (Demand, DmdType)
-- Split off one function argument
-- We already have a suitable demand on all
-- free vars, so no need to add more!
splitDmdTy ty@DmdType{dt_args=dmd:args} = (dmd, ty{dt_args=args})
splitDmdTy ty@DmdType{dt_div=div}       = (defaultArgDmd div, ty)

multDmdType :: Card -> DmdType -> DmdType
multDmdType n (DmdType fv args res_ty)
  = -- pprTrace "multDmdType" (ppr n $$ ppr fv $$ ppr (multDmdEnv n fv)) $
    DmdType (multDmdEnv n fv)
            (map (multDmd n) args)
            (multDivergence n res_ty)

peelFV :: DmdType -> Var -> (DmdType, Demand)
peelFV (DmdType fv ds res) id = -- pprTrace "rfv" (ppr id <+> ppr dmd $$ ppr fv)
                               (DmdType fv' ds res, dmd)
  where
  fv' = fv `delVarEnv` id
  -- See Note [Default demand on free variables and arguments]
  dmd  = lookupVarEnv fv id `orElse` defaultFvDmd res

addDemand :: Demand -> DmdType -> DmdType
addDemand dmd (DmdType fv ds res) = DmdType fv (dmd:ds) res

findIdDemand :: DmdType -> Var -> Demand
findIdDemand (DmdType fv _ res) id
  = lookupVarEnv fv id `orElse` defaultFvDmd res

-- | When e is evaluated after executing an IO action that may throw a precise
-- exception, we act as if there is an additional control flow path that is
-- taken if e throws a precise exception. The demand type of this control flow
-- path
--   * is lazy and absent ('topDmd') in all free variables and arguments
--   * has 'exnDiv' 'Divergence' result
-- So we can simply take a variant of 'nopDmdType', 'exnDmdType'.
-- Why not 'nopDmdType'? Because then the result of 'e' can never be 'exnDiv'!
-- That means failure to drop dead-ends, see #18086.
-- See Note [Precise exceptions and strictness analysis]
deferAfterPreciseException :: DmdType -> DmdType
deferAfterPreciseException = lubDmdType exnDmdType

-- | See 'keepAliveDmdEnv'.
keepAliveDmdType :: DmdType -> VarSet -> DmdType
keepAliveDmdType (DmdType fvs ds res) vars =
  DmdType (fvs `keepAliveDmdEnv` vars) ds res

{-
Note [Demand type Divergence]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In contrast to StrictSigs, DmdTypes are elicited under a specific incoming demand.
This is described in detail in Note [Understanding DmdType and StrictSig].
Here, we'll focus on what that means for a DmdType's Divergence in a higher-order
scenario.

Consider
  err x y = x `seq` y `seq` error (show x)
this has a strictness signature of
  <SU><SU>b
meaning that we don't know what happens when we call err in weaker contexts than
CS(CS(U)), like @err `seq` ()@ (SU) and @err 1 `seq` ()@ (CS(U)). We
may not unleash the botDiv, hence assume topDiv. Of course, in
@err 1 2 `seq` ()@ the incoming demand CS(CS(S)) is strong enough and we see
that the expression diverges.

Now consider a function
  f g = g 1 2
with signature <CS(CS(U))>, and the expression
  f err `seq` ()
now f puts a strictness demand of CS(CS(U)) onto its argument, which is unleashed
on err via the App rule. In contrast to weaker head strictness, this demand is
strong enough to unleash err's signature and hence we see that the whole
expression diverges!

Note [Asymmetry of 'plus*']
~~~~~~~~~~~~~~~~~~~~~~~~~~~
'plus' for DmdTypes is *asymmetrical*, because there can only one
be one type contributing argument demands!  For example, given (e1 e2), we get
a DmdType dt1 for e1, use its arg demand to analyse e2 giving dt2, and then do
(dt1 `plusType` dt2). Similarly with
  case e of { p -> rhs }
we get dt_scrut from the scrutinee and dt_rhs from the RHS, and then
compute (dt_rhs `plusType` dt_scrut).

We
 1. combine the information on the free variables,
 2. take the demand on arguments from the first argument
 3. combine the termination results, as in plusDivergence.

Since we don't use argument demands of the second argument anyway, 'plus's
second argument is just a 'PlusDmdType'.

But note that the argument demand types are not guaranteed to be observed in
left to right order. For example, analysis of a case expression will pass the
demand type for the alts as the left argument and the type for the scrutinee as
the right argument. Also, it is not at all clear if there is such an order;
consider the LetUp case, where the RHS might be forced at any point while
evaluating the let body.
Therefore, it is crucial that 'plusDivergence' is symmetric!

Note [Demands from unsaturated function calls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider a demand transformer d1 -> d2 -> r for f.
If a sufficiently detailed demand is fed into this transformer,
e.g <CS(CS(U))> arising from "f x1 x2" in a strict, use-once context,
then d1 and d2 is precisely the demand unleashed onto x1 and x2 (similar for
the free variable environment) and furthermore the result information r is the
one we want to use.

An anonymous lambda is also an unsaturated function all (needs one argument,
none given), so this applies to that case as well.

But the demand fed into f might be less than CS(CS(U)). Then we have to
'multDmdType' the announced demand type. Examples:
 * Not strict enough, e.g. C1(C1(U)):
   - We have to multiply all argument and free variable demands with C_01,
     zapping strictness.
   - We have to multiply divergence with C_01. If r says that f Diverges for sure,
     then this holds when the demand guarantees that two arguments are going to
     be passed. If the demand is lower, we may just as well converge.
     If we were tracking definite convegence, than that would still hold under
     a weaker demand than expected by the demand transformer.
 * Used more than once, e.g. CM(CS(U)):
   - Multiply with C_1N. Even if f puts a used-once demand on any of its argument
     or free variables, if we call f multiple times, we may evaluate this
     argument or free variable multiple times.

In dmdTransformSig, we call peelManyCalls to find out the 'Card'inality with
which we have to multiply and then call multDmdType with that.

Similarly, dmdTransformDictSelSig and dmdAnal, when analyzing a Lambda, use
peelCallDmd, which peels only one level, but also returns the demand put on the
body of the function.
-}


{-
************************************************************************
*                                                                      *
                     Demand signatures
*                                                                      *
************************************************************************

In a let-bound Id we record its demand signature.
In principle, this demand signature is a demand transformer, mapping
a demand on the Id into a DmdType, which gives
        a) the free vars of the Id's value
        b) the Id's arguments
        c) an indication of the result of applying
           the Id to its arguments

However, in fact we store in the Id an extremely emascuated demand
transfomer, namely

                a single DmdType
(Nevertheless we dignify StrictSig as a distinct type.)

This DmdType gives the demands unleashed by the Id when it is applied
to as many arguments as are given in by the arg demands in the DmdType.
Also see Note [Demand type Divergence] for the meaning of a Divergence in a
strictness signature.

If an Id is applied to less arguments than its arity, it means that
the demand on the function at a call site is weaker than the vanilla
call demand, used for signature inference. Therefore we place a top
demand on all arguments. Otherwise, the demand is specified by Id's
signature.

For example, the demand transformer described by the demand signature
        StrictSig (DmdType {x -> <S,1*U>} <L,A><C_,(U,U)>m)
says that when the function is applied to two arguments, it
unleashes demand <S,1*U> on the free var x, <L,A> on the first arg,
and <C_,(U,U)> on the second, then returning a constructor.

If this same function is applied to one arg, all we can say is that it
uses x with <C_,>, and its arg with demand <C_,>.

Note [Understanding DmdType and StrictSig]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demand types are sound approximations of an expression's semantics relative to
the incoming demand we put the expression under. Consider the following
expression:

    \x y -> x `seq` (y, 2*x)

Here is a table with demand types resulting from different incoming demands we
put that expression under. Note the monotonicity; a stronger incoming demand
yields a more precise demand type:

    incoming demand   |  demand type
    --------------------------------
    SA                  |  <U><U>{}
    CS(CS(U))           |  <SP(U)><U>{}
    CS(CS(SP(SP(U),A))) |  <SP(A)><A>{}

Note that in the first example, the depth of the demand type was *higher* than
the arity of the incoming call demand due to the anonymous lambda.
The converse is also possible and happens when we unleash demand signatures.
In @f x y@, the incoming call demand on f has arity 2. But if all we have is a
demand signature with depth 1 for @f@ (which we can safely unleash, see below),
the demand type of @f@ under a call demand of arity 2 has a *lower* depth of 1.

So: Demand types are elicited by putting an expression under an incoming (call)
demand, the arity of which can be lower or higher than the depth of the
resulting demand type.
In contrast, a demand signature summarises a function's semantics *without*
immediately specifying the incoming demand it was produced under. Despite StrSig
being a newtype wrapper around DmdType, it actually encodes two things:

  * The threshold (i.e., minimum arity) to unleash the signature
  * A demand type that is sound to unleash when the minimum arity requirement is
    met.

Here comes the subtle part: The threshold is encoded in the wrapped demand
type's depth! So in mkStrictSigForArity we make sure to trim the list of
argument demands to the given threshold arity. Call sites will make sure that
this corresponds to the arity of the call demand that elicited the wrapped
demand type. See also Note [What are demand signatures?].
-}

-- | The depth of the wrapped 'DmdType' encodes the arity at which it is safe
-- to unleash. Better construct this through 'mkStrictSigForArity'.
-- See Note [Understanding DmdType and StrictSig]
newtype StrictSig
  = StrictSig DmdType
  deriving Eq

-- | Turns a 'DmdType' computed for the particular 'Arity' into a 'StrictSig'
-- unleashable at that arity. See Note [Understanding DmdType and StrictSig]
mkStrictSigForArity :: Arity -> DmdType -> StrictSig
mkStrictSigForArity arity dmd_ty@(DmdType fvs args div)
  | arity < dmdTypeDepth dmd_ty = StrictSig (DmdType fvs (take arity args) div)
  | otherwise                   = StrictSig (etaExpandDmdType arity dmd_ty)

mkClosedStrictSig :: [Demand] -> Divergence -> StrictSig
mkClosedStrictSig ds res = mkStrictSigForArity (length ds) (DmdType emptyDmdEnv ds res)

splitStrictSig :: StrictSig -> ([Demand], Divergence)
splitStrictSig (StrictSig (DmdType _ dmds res)) = (dmds, res)

strictSigDmdEnv :: StrictSig -> DmdEnv
strictSigDmdEnv (StrictSig (DmdType env _ _)) = env

hasDemandEnvSig :: StrictSig -> Bool
hasDemandEnvSig = not . isEmptyVarEnv . strictSigDmdEnv

botSig :: StrictSig
botSig = StrictSig botDmdType

nopSig :: StrictSig
nopSig = StrictSig nopDmdType

isTopSig :: StrictSig -> Bool
isTopSig (StrictSig ty) = isTopDmdType ty

-- | True if the signature diverges or throws an exception in a saturated call.
-- See Note [Dead ends].
isDeadEndSig :: StrictSig -> Bool
isDeadEndSig (StrictSig (DmdType _ _ res)) = isDeadEndDiv res

-- | Returns true if an application to n args would diverge or throw an
-- exception.
--
-- If a function having 'botDiv' is applied to a less number of arguments than
-- its syntactic arity, we cannot say for sure that it is going to diverge.
-- Hence this function conservatively returns False in that case.
-- See Note [Dead ends].
appIsDeadEnd :: StrictSig -> Int -> Bool
appIsDeadEnd (StrictSig (DmdType _ ds res)) n
  = isDeadEndDiv res && not (lengthExceeds ds n)

prependArgsStrictSig :: Int -> StrictSig -> StrictSig
-- ^ Add extra ('topDmd') arguments to a strictness signature.
-- In contrast to 'etaConvertStrictSig', this /prepends/ additional argument
-- demands. This is used by FloatOut.
prependArgsStrictSig new_args sig@(StrictSig dmd_ty@(DmdType env dmds res))
  | new_args == 0       = sig
  | isTopDmdType dmd_ty = sig
  | new_args < 0        = pprPanic "prependArgsStrictSig: negative new_args"
                                   (ppr new_args $$ ppr sig)
  | otherwise           = StrictSig (DmdType env dmds' res)
  where
    dmds' = replicate new_args topDmd ++ dmds

etaConvertStrictSig :: Arity -> StrictSig -> StrictSig
-- ^ We are expanding (\x y. e) to (\x y z. e z) or reducing from the latter to
-- the former (when the Simplifier identifies a new join points, for example).
-- In contrast to 'prependArgsStrictSig', this /appends/ extra arg demands if
-- necessary.
-- This works by looking at the 'DmdType' (which was produced under a call
-- demand for the old arity) and trying to transfer as many facts as we can to
-- the call demand of new arity.
-- An arity increase (resulting in a stronger incoming demand) can retain much
-- of the info, while an arity decrease (a weakening of the incoming demand)
-- must fall back to a conservative default.
etaConvertStrictSig arity (StrictSig dmd_ty)
  | arity < dmdTypeDepth dmd_ty = StrictSig $ decreaseArityDmdType dmd_ty
  | otherwise                   = StrictSig $ etaExpandDmdType arity dmd_ty

{-
************************************************************************
*                                                                      *
                     Demand transformers
*                                                                      *
************************************************************************
-}

-- | A /demand transformer/ is a monotone function from an incoming evaluation
-- context ('SubDemand') to a 'DmdType', describing how the denoted thing
-- (i.e. expression, function) uses its arguments and free variables, and
-- whether it diverges.
--
-- See Note [Understanding DmdType and StrictSig]
-- and Note [What are demand signatures?].
type DmdTransformer = SubDemand -> DmdType

-- | Extrapolate a demand signature ('StrictSig') into a 'DmdTransformer'.
--
-- Given a function's 'StrictSig' and a 'SubDemand' for the evaluation context,
-- return how the function evaluates its free variables and arguments.
dmdTransformSig :: StrictSig -> DmdTransformer
dmdTransformSig (StrictSig dmd_ty@(DmdType _ arg_ds _)) sd
  = multDmdType (peelManyCalls (length arg_ds) sd) dmd_ty
    -- see Note [Demands from unsaturated function calls]
    -- and Note [What are demand signatures?]

-- | A special 'DmdTransformer' for data constructors that feeds product
-- demands into the constructor arguments.
dmdTransformDataConSig :: Arity -> DmdTransformer
dmdTransformDataConSig arity sd = case go arity sd of
  Just dmds -> DmdType emptyDmdEnv dmds topDiv
  Nothing   -> nopDmdType -- Not saturated
  where
    go 0 sd                            = viewProd arity sd
    go n (viewCall -> Just (C_11, sd)) = go (n-1) sd  -- strict calls only!
    go _ _                             = Nothing

-- | A special 'DmdTransformer' for dictionary selectors that feeds the demand
-- on the result into the indicated dictionary component (if saturated).
dmdTransformDictSelSig :: StrictSig -> DmdTransformer
-- NB: This currently doesn't handle newtype dictionaries and it's unclear how
-- it could without additional parameters.
dmdTransformDictSelSig (StrictSig (DmdType _ [(_ :* sig_sd)] _)) call_sd
   | (n, sd') <- peelCallDmd call_sd
   , Prod sig_ds  <- sig_sd
   = multDmdType n $
     DmdType emptyDmdEnv [C_11 :* Prod (map (enhance sd') sig_ds)] topDiv
   | otherwise
   = nopDmdType -- See Note [Demand transformer for a dictionary selector]
  where
    enhance sd old | isAbsDmd old = old
                   | otherwise    = C_11 :* sd  -- This is the one!

dmdTransformDictSelSig sig sd = pprPanic "dmdTransformDictSelSig: no args" (ppr sig $$ ppr sd)

{-
Note [What are demand signatures?]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demand analysis interprets expressions in the abstract domain of demand
transformers. Given a (sub-)demand that denotes the evaluation context, the
abstract transformer of an expression gives us back a demand type denoting
how other things (like arguments and free vars) were used when the expression
was evaluated. Here's an example:

  f x y =
    if x + expensive
      then \z -> z + y * ...
      else \z -> z * ...

The abstract transformer (let's call it F_e) of the if expression (let's
call it e) would transform an incoming (undersaturated!) head demand SA into
a demand type like {x-><SU>,y-><U>}<U>. In pictures:

     Demand ---F_e---> DmdType
     <SA>              {x-><SU>,y-><U>}<U>

Let's assume that the demand transformers we compute for an expression are
correct wrt. to some concrete semantics for Core. How do demand signatures fit
in? They are strange beasts, given that they come with strict rules when to
it's sound to unleash them.

Fortunately, we can formalise the rules with Galois connections. Consider
f's strictness signature, {}<SU><U>. It's a single-point approximation of
the actual abstract transformer of f's RHS for arity 2. So, what happens is that
we abstract *once more* from the abstract domain we already are in, replacing
the incoming Demand by a simple lattice with two elements denoting incoming
arity: A_2 = {<2, >=2} (where '<2' is the top element and >=2 the bottom
element). Here's the diagram:

     A_2 -----f_f----> DmdType
      ^                   |
      | α               γ |
      |                   v
  SubDemand --F_f----> DmdType

With
  α(CS(CS(_))) = >=2
  α(_)         =  <2
  γ(ty)        =  ty
and F_f being the abstract transformer of f's RHS and f_f being the abstracted
abstract transformer computable from our demand signature simply by

  f_f(>=2) = {}<S,1*U><L,U>
  f_f(<2)  = multDmdType C_0N {}<S,1*U><L,U>

where multDmdType makes a proper top element out of the given demand type.

In practice, the A_n domain is not just a simple Bool, but a Card, which is
exactly the Card with which we have to multDmdType. The Card for arity n
is computed by calling @peelManyCalls n@, which corresponds to α above.

Note [Demand transformer for a dictionary selector]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we evaluate (op dict-expr) under demand 'd', then we can push the demand 'd'
into the appropriate field of the dictionary. What *is* the appropriate field?
We just look at the strictness signature of the class op, which will be
something like: UP(AAASAAAAA).  Then replace the 'S' by the demand 'd'.

For single-method classes, which are represented by newtypes the signature
of 'op' won't look like UP(...), so matching on Prod will fail.
That's fine: if we are doing strictness analysis we are also doing inlining,
so we'll have inlined 'op' into a cast.  So we can bale out in a conservative
way, returning nopDmdType.

It is (just.. #8329) possible to be running strictness analysis *without*
having inlined class ops from single-method classes.  Suppose you are using
ghc --make; and the first module has a local -O0 flag.  So you may load a class
without interface pragmas, ie (currently) without an unfolding for the class
ops.   Now if a subsequent module in the --make sweep has a local -O flag
you might do strictness analysis, but there is no inlining for the class op.
This is weird, so I'm not worried about whether this optimises brilliantly; but
it should not fall over.
-}

-- | Remove the demand environment from the signature.
zapDmdEnvSig :: StrictSig -> StrictSig
zapDmdEnvSig (StrictSig (DmdType _ ds r)) = mkClosedStrictSig ds r

zapUsageDemand :: Demand -> Demand
-- Remove the usage info, but not the strictness info, from the demand
zapUsageDemand = kill_usage $ KillFlags
    { kf_abs         = True
    , kf_used_once   = True
    , kf_called_once = True
    }

-- | Remove all 1* information (but not C1 information) from the demand
zapUsedOnceDemand :: Demand -> Demand
zapUsedOnceDemand = kill_usage $ KillFlags
    { kf_abs         = False
    , kf_used_once   = True
    , kf_called_once = False
    }

-- | Remove all 1* information (but not C1 information) from the strictness
--   signature
zapUsedOnceSig :: StrictSig -> StrictSig
zapUsedOnceSig (StrictSig (DmdType env ds r))
    = StrictSig (DmdType env (map zapUsedOnceDemand ds) r)

data KillFlags = KillFlags
    { kf_abs         :: Bool
    , kf_used_once   :: Bool
    , kf_called_once :: Bool
    }

kill_usage_card :: KillFlags -> Card -> Card
kill_usage_card kfs C_00 | kf_abs kfs       = C_0N
kill_usage_card kfs C_10 | kf_abs kfs       = C_1N
kill_usage_card kfs C_01 | kf_used_once kfs = C_0N
kill_usage_card kfs C_11 | kf_used_once kfs = C_1N
kill_usage_card _   n                       = n

kill_usage :: KillFlags -> Demand -> Demand
kill_usage kfs (n :* sd) = kill_usage_card kfs n :* kill_usage_sd kfs sd

kill_usage_sd :: KillFlags -> SubDemand -> SubDemand
kill_usage_sd kfs (Call n sd)
  | kf_called_once kfs      = mkCall (lubCard C_1N n) (kill_usage_sd kfs sd)
  | otherwise               = mkCall n                (kill_usage_sd kfs sd)
kill_usage_sd kfs (Prod ds) = Prod (map (kill_usage kfs) ds)
kill_usage_sd _   sd        = sd

{- *********************************************************************
*                                                                      *
               TypeShape and demand trimming
*                                                                      *
********************************************************************* -}


data TypeShape -- See Note [Trimming a demand to a type]
               --     in GHC.Core.Opt.DmdAnal
  = TsFun TypeShape
  | TsProd [TypeShape]
  | TsUnk

trimToType :: Demand -> TypeShape -> Demand
-- See Note [Trimming a demand to a type] in GHC.Core.Opt.DmdAnal
trimToType (n :* sd) ts
  = n :* go sd ts
  where
    go (Prod ds)   (TsProd tss)
      | equalLength ds tss    = Prod (zipWith trimToType ds tss)
    go (Call n sd) (TsFun ts) = mkCall n (go sd ts)
    go sd@Poly{}   _          = sd
    go _           _          = topSubDmd

{-
************************************************************************
*                                                                      *
                     'seq'ing demands
*                                                                      *
************************************************************************
-}

seqDemand :: Demand -> ()
seqDemand (_ :* sd) = seqSubDemand sd

seqSubDemand :: SubDemand -> ()
seqSubDemand (Prod ds)   = seqDemandList ds
seqSubDemand (Call _ sd) = seqSubDemand sd
seqSubDemand (Poly _)    = ()

seqDemandList :: [Demand] -> ()
seqDemandList = foldr (seq . seqDemand) ()

seqDmdType :: DmdType -> ()
seqDmdType (DmdType env ds res) =
  seqDmdEnv env `seq` seqDemandList ds `seq` res `seq` ()

seqDmdEnv :: DmdEnv -> ()
seqDmdEnv env = seqEltsUFM seqDemandList env

seqStrictSig :: StrictSig -> ()
seqStrictSig (StrictSig ty) = seqDmdType ty

{-
************************************************************************
*                                                                      *
                     Outputable and Binary instances
*                                                                      *
************************************************************************
-}

{- Note [Demand notation]
~~~~~~~~~~~~~~~~~~~~~~~~~
This Note should be kept up to date with the documentation of `-fstrictness`
in the user's guide.

For pretty-printing demands, we use quite a compact notation with some
abbreviations. Here's the BNF:

  card ::= B | A | 1 | U | S | M    {}, {0}, {0,1}, {0,1,n}, {1}, {1,n}

  d    ::= card sd                  The :* constructor, just juxtaposition
        |  card                     abbreviation: Same as "card card",
                                                  in code @polyDmd card@

  sd   ::= card                     @Poly card@
        |  P(d,d,..)                @Prod [d1,d2,..]@
        |  Ccard(sd)                @Call card sd@

So, U can denote a 'Card', polymorphic 'SubDemand' or polymorphic 'Demand',
but it's always clear from context which "overload" is meant. It's like
return-type inference of e.g. 'read'.

Examples are in the haddock for 'Demand'.

This is the syntax for demand signatures:

  div ::= <empty>      topDiv
       |  x            exnDiv
       |  b            botDiv

  sig ::= {x->dx,y->dy,z->dz...}<d1><d2><d3>...<dn>div
                  ^              ^   ^   ^      ^   ^
                  |              |   |   |      |   |
                  |              \---+---+------/   |
                  |                  |              |
             demand on free        demand on      divergence
               variables           arguments      information
           (omitted if empty)                     (omitted if
                                                no information)


-}

-- | See Note [Demand notation]
instance Outputable Card where
  ppr C_00 = char 'A'
  ppr C_01 = char '1'
  ppr C_0N = char 'U'
  ppr C_11 = char 'S'
  ppr C_1N = char 'M'
  ppr C_10 = char 'B'

-- | See Note [Demand notation]
instance Outputable Demand where
  ppr dmd@(n :* sd)
    | isAbs n          = ppr n   -- If absent, sd is arbitrary
    | dmd == polyDmd n = ppr n   -- Print UU as just U
    | otherwise        = ppr n <> ppr sd

-- | See Note [Demand notation]
instance Outputable SubDemand where
  ppr (Poly sd)   = ppr sd
  ppr (Call n sd) = char 'C' <> ppr n <> parens (ppr sd)
  ppr (Prod ds)   = char 'P' <> parens (fields ds)
    where
      fields []     = empty
      fields [x]    = ppr x
      fields (x:xs) = ppr x <> char ',' <> fields xs

instance Outputable Divergence where
  ppr Diverges = char 'b' -- for (b)ottom
  ppr ExnOrDiv = char 'x' -- for e(x)ception
  ppr Dunno    = empty

instance Outputable DmdType where
  ppr (DmdType fv ds res)
    = hsep [hcat (map (angleBrackets . ppr) ds) <> ppr res,
            if null fv_elts then empty
            else braces (fsep (map pp_elt fv_elts))]
    where
      pp_elt (uniq, dmd) = ppr uniq <> text "->" <> ppr dmd
      fv_elts = nonDetUFMToList fv
        -- It's OK to use nonDetUFMToList here because we only do it for
        -- pretty printing

instance Outputable StrictSig where
   ppr (StrictSig ty) = ppr ty

instance Outputable TypeShape where
  ppr TsUnk        = text "TsUnk"
  ppr (TsFun ts)   = text "TsFun" <> parens (ppr ts)
  ppr (TsProd tss) = parens (hsep $ punctuate comma $ map ppr tss)

instance Binary Card where
  put_ bh C_00 = putByte bh 0
  put_ bh C_01 = putByte bh 1
  put_ bh C_0N = putByte bh 2
  put_ bh C_11 = putByte bh 3
  put_ bh C_1N = putByte bh 4
  put_ bh C_10 = putByte bh 5
  get bh = do
    h <- getByte bh
    case h of
      0 -> return C_00
      1 -> return C_01
      2 -> return C_0N
      3 -> return C_11
      4 -> return C_1N
      5 -> return C_10
      _ -> pprPanic "Binary:Card" (ppr (fromIntegral h :: Int))

instance Binary Demand where
  put_ bh (n :* sd) = put_ bh n *> put_ bh sd
  get bh = (:*) <$> get bh <*> get bh

instance Binary SubDemand where
  put_ bh (Poly sd)   = putByte bh 0 *> put_ bh sd
  put_ bh (Call n sd) = putByte bh 1 *> put_ bh n *> put_ bh sd
  put_ bh (Prod ds)   = putByte bh 2 *> put_ bh ds
  get bh = do
    h <- getByte bh
    case h of
      0 -> Poly <$> get bh
      1 -> mkCall <$> get bh <*> get bh
      2 -> Prod <$> get bh
      _ -> pprPanic "Binary:SubDemand" (ppr (fromIntegral h :: Int))

instance Binary StrictSig where
  put_ bh (StrictSig aa) = put_ bh aa
  get bh = StrictSig <$> get bh

instance Binary DmdType where
  -- Ignore DmdEnv when spitting out the DmdType
  put_ bh (DmdType _ ds dr) = put_ bh ds *> put_ bh dr
  get bh = DmdType emptyDmdEnv <$> get bh <*> get bh

instance Binary Divergence where
  put_ bh Dunno    = putByte bh 0
  put_ bh ExnOrDiv = putByte bh 1
  put_ bh Diverges = putByte bh 2
  get bh = do
    h <- getByte bh
    case h of
      0 -> return Dunno
      1 -> return ExnOrDiv
      2 -> return Diverges
      _ -> pprPanic "Binary:Divergence" (ppr (fromIntegral h :: Int))