aboutsummaryrefslogtreecommitdiff
path: root/gcc/loop-iv.c
blob: e4d757a079875095d9b3f1039b714c8d2e167685 (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
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
/* Rtl-level induction variable analysis.
   Copyright (C) 2004 Free Software Foundation, Inc.
   
This file is part of GCC.
   
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.
   
GCC is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.
   
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING.  If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.  */

/* This is just a very simplistic analysis of induction variables of the loop.
   The major use is for determining the number of iterations of a loop for
   loop unrolling, doloop optimization and branch prediction.  For this we
   are only interested in bivs and a fairly limited set of givs that are
   needed in the exit condition.  We also only compute the iv information on
   demand.

   The interesting registers are determined.  A register is interesting if

   -- it is set only in the blocks that dominate the latch of the current loop
   -- all its sets are simple -- i.e. in the form we understand

   We also number the insns sequentially in each basic block.  For a use of the
   interesting reg, it is now easy to find a reaching definition (there may be
   only one).

   Induction variable is then simply analyzed by walking the use-def
   chains.
   
   Usage:

   iv_analysis_loop_init (loop);
   insn = iv_get_reaching_def (where, reg);
   if (iv_analyze (insn, reg, &iv))
     {
       ...
     }
   iv_analysis_done (); */

#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "rtl.h"
#include "hard-reg-set.h"
#include "basic-block.h"
#include "cfgloop.h"
#include "expr.h"
#include "output.h"

/* The insn information.  */

struct insn_info
{
  /* Id of the insn.  */
  unsigned luid;

  /* The previous definition of the register defined by the single
     set in the insn.  */
  rtx prev_def;

  /* The description of the iv.  */
  struct rtx_iv iv;
};

static struct insn_info *insn_info;

/* The last definition of register.  */

static rtx *last_def;

/* The bivs.  */

static struct rtx_iv *bivs;

/* Maximal insn number for that there is place in insn_info array.  */

static unsigned max_insn_no;

/* Maximal register number for that there is place in bivs and last_def
   arrays.  */

static unsigned max_reg_no;

/* Dumps information about IV to FILE.  */

extern void dump_iv_info (FILE *, struct rtx_iv *);
void
dump_iv_info (FILE *file, struct rtx_iv *iv)
{
  if (!iv->base)
    {
      fprintf (file, "not simple");
      return;
    }

  if (iv->step == const0_rtx
      && !iv->first_special)
    fprintf (file, "invariant ");

  print_rtl (file, iv->base);
  if (iv->step != const0_rtx)
    {
      fprintf (file, " + ");
      print_rtl (file, iv->step);
      fprintf (file, " * iteration");
    }
  fprintf (file, " (in %s)", GET_MODE_NAME (iv->mode));

  if (iv->mode != iv->extend_mode)
    fprintf (file, " %s to %s",
	     rtx_name[iv->extend],
	     GET_MODE_NAME (iv->extend_mode));

  if (iv->mult != const1_rtx)
    {
      fprintf (file, " * ");
      print_rtl (file, iv->mult);
    }
  if (iv->delta != const0_rtx)
    {
      fprintf (file, " + ");
      print_rtl (file, iv->delta);
    }
  if (iv->first_special)
    fprintf (file, " (first special)");
}

/* Assigns luids to insns in basic block BB.  */

static void
assign_luids (basic_block bb)
{
  unsigned i = 0, uid;
  rtx insn;

  FOR_BB_INSNS (bb, insn)
    {
      uid = INSN_UID (insn);
      insn_info[uid].luid = i++;
      insn_info[uid].prev_def = NULL_RTX;
      insn_info[uid].iv.analysed = false;
    }
}

/* Generates a subreg to get the least significant part of EXPR (in mode
   INNER_MODE) to OUTER_MODE.  */

static rtx
lowpart_subreg (enum machine_mode outer_mode, rtx expr,
		enum machine_mode inner_mode)
{
  return simplify_gen_subreg (outer_mode, expr, inner_mode,
			      subreg_lowpart_offset (outer_mode, inner_mode));
}

/* Checks whether REG is a well-behaved register.  */

static bool
simple_reg_p (rtx reg)
{
  unsigned r;

  if (GET_CODE (reg) == SUBREG)
    {
      if (!subreg_lowpart_p (reg))
	return false;
      reg = SUBREG_REG (reg);
    }

  if (!REG_P (reg))
    return false;

  r = REGNO (reg);
  if (HARD_REGISTER_NUM_P (r))
    return false;

  if (GET_MODE_CLASS (GET_MODE (reg)) != MODE_INT)
    return false;

  if (last_def[r] == const0_rtx)
    return false;

  return true;
}

/* Checks whether assignment LHS = RHS is simple enough for us to process.  */

static bool
simple_set_p (rtx lhs, rtx rhs)
{
  rtx op0, op1;

  if (!REG_P (lhs)
      || !simple_reg_p (lhs))
    return false;

  if (CONSTANT_P (rhs))
    return true;

  switch (GET_CODE (rhs))
    {
    case SUBREG:
    case REG:
      return simple_reg_p (rhs);

    case SIGN_EXTEND:
    case ZERO_EXTEND:
    case NEG:
      return simple_reg_p (XEXP (rhs, 0));

    case PLUS:
    case MINUS:
    case MULT:
    case ASHIFT:
      op0 = XEXP (rhs, 0);
      op1 = XEXP (rhs, 1);

      if (!simple_reg_p (op0)
	  && !CONSTANT_P (op0))
	return false;

      if (!simple_reg_p (op1)
	  && !CONSTANT_P (op1))
	return false;

      if (GET_CODE (rhs) == MULT
	  && !CONSTANT_P (op0)
	  && !CONSTANT_P (op1))
	return false;

      if (GET_CODE (rhs) == ASHIFT
	  && CONSTANT_P (op0))
	return false;

      return true;

    default:
      return false;
    }
}

/* Mark single SET in INSN.  */

static rtx
mark_single_set (rtx insn, rtx set)
{
  rtx def = SET_DEST (set), src;
  unsigned regno, uid;

  src = find_reg_equal_equiv_note (insn);
  if (src)
    src = XEXP (src, 0);
  else
    src = SET_SRC (set);

  if (!simple_set_p (SET_DEST (set), src))
    return NULL_RTX;

  regno = REGNO (def);
  uid = INSN_UID (insn);

  bivs[regno].analysed = false;
  insn_info[uid].prev_def = last_def[regno];
  last_def[regno] = insn;

  return def;
}

/* Invalidate register REG unless it is equal to EXCEPT.  */

static void
kill_sets (rtx reg, rtx by ATTRIBUTE_UNUSED, void *except)
{
  if (GET_CODE (reg) == SUBREG)
    reg = SUBREG_REG (reg);
  if (!REG_P (reg))
    return;
  if (reg == except)
    return;

  last_def[REGNO (reg)] = const0_rtx;
}

/* Marks sets in basic block BB.  If DOM is true, BB dominates the loop
   latch.  */

static void
mark_sets (basic_block bb, bool dom)
{
  rtx insn, set, def;

  FOR_BB_INSNS (bb, insn)
    {
      if (!INSN_P (insn))
	continue;

      if (dom
	  && (set = single_set (insn)))
	def = mark_single_set (insn, set);
      else
	def = NULL_RTX;

      note_stores (PATTERN (insn), kill_sets, def);
    }
}

/* Prepare the data for an induction variable analysis of a LOOP.  */

void
iv_analysis_loop_init (struct loop *loop)
{
  basic_block *body = get_loop_body_in_dom_order (loop);
  unsigned b;

  if ((unsigned) get_max_uid () >= max_insn_no)
    {
      /* Add some reserve for insns and registers produced in optimizations.  */
      max_insn_no = get_max_uid () + 100;
      if (insn_info)
	free (insn_info);
      insn_info = xmalloc (max_insn_no * sizeof (struct insn_info));
    }

  if ((unsigned) max_reg_num () >= max_reg_no)
    {
      max_reg_no = max_reg_num () + 100;
      if (last_def)
	free (last_def);
      last_def = xmalloc (max_reg_no * sizeof (rtx));
      if (bivs)
	free (bivs);
      bivs = xmalloc (max_reg_no * sizeof (struct rtx_iv));
    }

  memset (last_def, 0, max_reg_num () * sizeof (rtx));

  for (b = 0; b < loop->num_nodes; b++)
    {
      assign_luids (body[b]);
      mark_sets (body[b], just_once_each_iteration_p (loop, body[b]));
    }

  free (body);
}

/* Gets definition of REG reaching the INSN.  If REG is not simple, const0_rtx
   is returned.  If INSN is before the first def in the loop, NULL_RTX is
   returned.  */

rtx
iv_get_reaching_def (rtx insn, rtx reg)
{
  unsigned regno, luid, auid;
  rtx ainsn;
  basic_block bb, abb;

  if (GET_CODE (reg) == SUBREG)
    {
      if (!subreg_lowpart_p (reg))
	return const0_rtx;
      reg = SUBREG_REG (reg);
    }
  if (!REG_P (reg))
    return NULL_RTX;

  regno = REGNO (reg);
  if (!last_def[regno]
      || last_def[regno] == const0_rtx)
    return last_def[regno];

  bb = BLOCK_FOR_INSN (insn);
  luid = insn_info[INSN_UID (insn)].luid;

  ainsn = last_def[regno];
  while (1)
    {
      abb = BLOCK_FOR_INSN (ainsn);

      if (dominated_by_p (CDI_DOMINATORS, bb, abb))
	break;

      auid = INSN_UID (ainsn);
      ainsn = insn_info[auid].prev_def;

      if (!ainsn)
	return NULL_RTX;
    }

  while (1)
    {
      abb = BLOCK_FOR_INSN (ainsn);
      if (abb != bb)
	return ainsn;

      auid = INSN_UID (ainsn);
      if (luid > insn_info[auid].luid)
	return ainsn;

      ainsn = insn_info[auid].prev_def;
      if (!ainsn)
	return NULL_RTX;
    }
}

/* Sets IV to invariant CST in MODE.  Always returns true (just for
   consistency with other iv manipulation functions that may fail).  */

static bool
iv_constant (struct rtx_iv *iv, rtx cst, enum machine_mode mode)
{
  if (mode == VOIDmode)
    mode = GET_MODE (cst);

  iv->analysed = true;
  iv->mode = mode;
  iv->base = cst;
  iv->step = const0_rtx;
  iv->first_special = false;
  iv->extend = UNKNOWN;
  iv->extend_mode = iv->mode;
  iv->delta = const0_rtx;
  iv->mult = const1_rtx;

  return true;
}

/* Evaluates application of subreg to MODE on IV.  */

static bool
iv_subreg (struct rtx_iv *iv, enum machine_mode mode)
{
  /* If iv is invariant, just calculate the new value.  */
  if (iv->step == const0_rtx
      && !iv->first_special)
    {
      rtx val = get_iv_value (iv, const0_rtx);
      val = lowpart_subreg (mode, val, iv->extend_mode);

      iv->base = val;
      iv->extend = UNKNOWN;
      iv->mode = iv->extend_mode = mode;
      iv->delta = const0_rtx;
      iv->mult = const1_rtx;
      return true;
    }

  if (iv->extend_mode == mode)
    return true;

  if (GET_MODE_BITSIZE (mode) > GET_MODE_BITSIZE (iv->mode))
    return false;

  iv->extend = UNKNOWN;
  iv->mode = mode;

  iv->base = simplify_gen_binary (PLUS, iv->extend_mode, iv->delta,
				  simplify_gen_binary (MULT, iv->extend_mode,
						       iv->base, iv->mult));
  iv->step = simplify_gen_binary (MULT, iv->extend_mode, iv->step, iv->mult);
  iv->mult = const1_rtx;
  iv->delta = const0_rtx;
  iv->first_special = false;

  return true;
}

/* Evaluates application of EXTEND to MODE on IV.  */

static bool
iv_extend (struct rtx_iv *iv, enum rtx_code extend, enum machine_mode mode)
{
  /* If iv is invariant, just calculate the new value.  */
  if (iv->step == const0_rtx
      && !iv->first_special)
    {
      rtx val = get_iv_value (iv, const0_rtx);
      val = simplify_gen_unary (extend, mode, val, iv->extend_mode);

      iv->base = val;
      iv->extend = UNKNOWN;
      iv->mode = iv->extend_mode = mode;
      iv->delta = const0_rtx;
      iv->mult = const1_rtx;
      return true;
    }

  if (mode != iv->extend_mode)
    return false;

  if (iv->extend != UNKNOWN
      && iv->extend != extend)
    return false;

  iv->extend = extend;

  return true;
}

/* Evaluates negation of IV.  */

static bool
iv_neg (struct rtx_iv *iv)
{
  if (iv->extend == UNKNOWN)
    {
      iv->base = simplify_gen_unary (NEG, iv->extend_mode,
				     iv->base, iv->extend_mode);
      iv->step = simplify_gen_unary (NEG, iv->extend_mode,
				     iv->step, iv->extend_mode);
    }
  else
    {
      iv->delta = simplify_gen_unary (NEG, iv->extend_mode,
				      iv->delta, iv->extend_mode);
      iv->mult = simplify_gen_unary (NEG, iv->extend_mode,
				     iv->mult, iv->extend_mode);
    }

  return true;
}

/* Evaluates addition or subtraction (according to OP) of IV1 to IV0.  */

static bool
iv_add (struct rtx_iv *iv0, struct rtx_iv *iv1, enum rtx_code op)
{
  enum machine_mode mode;
  rtx arg;

  /* Extend the constant to extend_mode of the other operand if necessary.  */
  if (iv0->extend == UNKNOWN
      && iv0->mode == iv0->extend_mode
      && iv0->step == const0_rtx
      && GET_MODE_SIZE (iv0->extend_mode) < GET_MODE_SIZE (iv1->extend_mode))
    {
      iv0->extend_mode = iv1->extend_mode;
      iv0->base = simplify_gen_unary (ZERO_EXTEND, iv0->extend_mode,
				      iv0->base, iv0->mode);
    }
  if (iv1->extend == UNKNOWN
      && iv1->mode == iv1->extend_mode
      && iv1->step == const0_rtx
      && GET_MODE_SIZE (iv1->extend_mode) < GET_MODE_SIZE (iv0->extend_mode))
    {
      iv1->extend_mode = iv0->extend_mode;
      iv1->base = simplify_gen_unary (ZERO_EXTEND, iv1->extend_mode,
				      iv1->base, iv1->mode);
    }

  mode = iv0->extend_mode;
  if (mode != iv1->extend_mode)
    return false;

  if (iv0->extend == UNKNOWN && iv1->extend == UNKNOWN)
    {
      if (iv0->mode != iv1->mode)
	return false;

      iv0->base = simplify_gen_binary (op, mode, iv0->base, iv1->base);
      iv0->step = simplify_gen_binary (op, mode, iv0->step, iv1->step);

      return true;
    }

  /* Handle addition of constant.  */
  if (iv1->extend == UNKNOWN
      && iv1->mode == mode
      && iv1->step == const0_rtx)
    {
      iv0->delta = simplify_gen_binary (op, mode, iv0->delta, iv1->base);
      return true;
    }

  if (iv0->extend == UNKNOWN
      && iv0->mode == mode
      && iv0->step == const0_rtx)
    {
      arg = iv0->base;
      *iv0 = *iv1;
      if (op == MINUS
	  && !iv_neg (iv0))
	return false;

      iv0->delta = simplify_gen_binary (PLUS, mode, iv0->delta, arg);
      return true;
    }

  return false;
}

/* Evaluates multiplication of IV by constant CST.  */

static bool
iv_mult (struct rtx_iv *iv, rtx mby)
{
  enum machine_mode mode = iv->extend_mode;

  if (GET_MODE (mby) != VOIDmode
      && GET_MODE (mby) != mode)
    return false;

  if (iv->extend == UNKNOWN)
    {
      iv->base = simplify_gen_binary (MULT, mode, iv->base, mby);
      iv->step = simplify_gen_binary (MULT, mode, iv->step, mby);
    }
  else
    {
      iv->delta = simplify_gen_binary (MULT, mode, iv->delta, mby);
      iv->mult = simplify_gen_binary (MULT, mode, iv->mult, mby);
    }

  return true;
}

/* Evaluates shift of IV by constant CST.  */

static bool
iv_shift (struct rtx_iv *iv, rtx mby)
{
  enum machine_mode mode = iv->extend_mode;

  if (GET_MODE (mby) != VOIDmode
      && GET_MODE (mby) != mode)
    return false;

  if (iv->extend == UNKNOWN)
    {
      iv->base = simplify_gen_binary (ASHIFT, mode, iv->base, mby);
      iv->step = simplify_gen_binary (ASHIFT, mode, iv->step, mby);
    }
  else
    {
      iv->delta = simplify_gen_binary (ASHIFT, mode, iv->delta, mby);
      iv->mult = simplify_gen_binary (ASHIFT, mode, iv->mult, mby);
    }

  return true;
}

/* The recursive part of get_biv_step.  Gets the value of the single value
   defined in INSN wrto initial value of REG inside loop, in shape described
   at get_biv_step.  */

static bool
get_biv_step_1 (rtx insn, rtx reg,
		rtx *inner_step, enum machine_mode *inner_mode,
		enum rtx_code *extend, enum machine_mode outer_mode,
		rtx *outer_step)
{
  rtx set, lhs, rhs, op0 = NULL_RTX, op1 = NULL_RTX;
  rtx next, nextr, def_insn, tmp;
  enum rtx_code code;

  set = single_set (insn);
  rhs = find_reg_equal_equiv_note (insn);
  if (rhs)
    rhs = XEXP (rhs, 0);
  else
    rhs = SET_SRC (set);
  lhs = SET_DEST (set);

  code = GET_CODE (rhs);
  switch (code)
    {
    case SUBREG:
    case REG:
      next = rhs;
      break;

    case PLUS:
    case MINUS:
      op0 = XEXP (rhs, 0);
      op1 = XEXP (rhs, 1);

      if (code == PLUS && CONSTANT_P (op0))
	{
	  tmp = op0; op0 = op1; op1 = tmp;
	}

      if (!simple_reg_p (op0)
	  || !CONSTANT_P (op1))
	return false;

      if (GET_MODE (rhs) != outer_mode)
	{
	  /* ppc64 uses expressions like

	     (set x:SI (plus:SI (subreg:SI y:DI) 1)).

	     this is equivalent to

	     (set x':DI (plus:DI y:DI 1))
	     (set x:SI (subreg:SI (x':DI)).  */
	  if (GET_CODE (op0) != SUBREG)
	    return false;
	  if (GET_MODE (SUBREG_REG (op0)) != outer_mode)
	    return false;
	}

      next = op0;
      break;

    case SIGN_EXTEND:
    case ZERO_EXTEND:
      if (GET_MODE (rhs) != outer_mode)
	return false;

      op0 = XEXP (rhs, 0);
      if (!simple_reg_p (op0))
	return false;

      next = op0;
      break;

    default:
      return false;
    }

  if (GET_CODE (next) == SUBREG)
    {
      if (!subreg_lowpart_p (next))
	return false;

      nextr = SUBREG_REG (next);
      if (GET_MODE (nextr) != outer_mode)
	return false;
    }
  else
    nextr = next;

  def_insn = iv_get_reaching_def (insn, nextr);
  if (def_insn == const0_rtx)
    return false;

  if (!def_insn)
    {
      if (!rtx_equal_p (nextr, reg))
	return false;

      *inner_step = const0_rtx;
      *extend = UNKNOWN;
      *inner_mode = outer_mode;
      *outer_step = const0_rtx;
    }
  else if (!get_biv_step_1 (def_insn, reg,
			    inner_step, inner_mode, extend, outer_mode,
			    outer_step))
    return false;

  if (GET_CODE (next) == SUBREG)
    {
      enum machine_mode amode = GET_MODE (next);

      if (GET_MODE_SIZE (amode) > GET_MODE_SIZE (*inner_mode))
	return false;

      *inner_mode = amode;
      *inner_step = simplify_gen_binary (PLUS, outer_mode,
					 *inner_step, *outer_step);
      *outer_step = const0_rtx;
      *extend = UNKNOWN;
    }

  switch (code)
    {
    case REG:
    case SUBREG:
      break;

    case PLUS:
    case MINUS:
      if (*inner_mode == outer_mode
	  /* See comment in previous switch.  */
	  || GET_MODE (rhs) != outer_mode)
	*inner_step = simplify_gen_binary (code, outer_mode,
					   *inner_step, op1);
      else
	*outer_step = simplify_gen_binary (code, outer_mode,
					   *outer_step, op1);
      break;

    case SIGN_EXTEND:
    case ZERO_EXTEND:
      if (GET_MODE (op0) != *inner_mode
	  || *extend != UNKNOWN
	  || *outer_step != const0_rtx)
	abort ();

      *extend = code;
      break;

    default:
      abort ();
    }

  return true;
}

/* Gets the operation on register REG inside loop, in shape

   OUTER_STEP + EXTEND_{OUTER_MODE} (SUBREG_{INNER_MODE} (REG + INNER_STEP))

   If the operation cannot be described in this shape, return false.  */

static bool
get_biv_step (rtx reg, rtx *inner_step, enum machine_mode *inner_mode,
	      enum rtx_code *extend, enum machine_mode *outer_mode,
	      rtx *outer_step)
{
  *outer_mode = GET_MODE (reg);

  if (!get_biv_step_1 (last_def[REGNO (reg)], reg,
		       inner_step, inner_mode, extend, *outer_mode,
		       outer_step))
    return false;

  if (*inner_mode != *outer_mode
      && *extend == UNKNOWN)
    abort ();

  if (*inner_mode == *outer_mode
      && *extend != UNKNOWN)
    abort ();

  if (*inner_mode == *outer_mode
      && *outer_step != const0_rtx)
    abort ();

  return true;
}

/* Determines whether DEF is a biv and if so, stores its description
   to *IV.  */

static bool
iv_analyze_biv (rtx def, struct rtx_iv *iv)
{
  unsigned regno;
  rtx inner_step, outer_step;
  enum machine_mode inner_mode, outer_mode;
  enum rtx_code extend;

  if (dump_file)
    {
      fprintf (dump_file, "Analysing ");
      print_rtl (dump_file, def);
      fprintf (dump_file, " for bivness.\n");
    }
    
  if (!REG_P (def))
    {
      if (!CONSTANT_P (def))
	return false;

      return iv_constant (iv, def, VOIDmode);
    }

  regno = REGNO (def);
  if (last_def[regno] == const0_rtx)
    {
      if (dump_file)
	fprintf (dump_file, "  not simple.\n");
      return false;
    }

  if (last_def[regno] && bivs[regno].analysed)
    {
      if (dump_file)
	fprintf (dump_file, "  already analysed.\n");

      *iv = bivs[regno];
      return iv->base != NULL_RTX;
    }

  if (!last_def[regno])
    {
      iv_constant (iv, def, VOIDmode);
      goto end;
    }

  iv->analysed = true;
  if (!get_biv_step (def, &inner_step, &inner_mode, &extend,
		     &outer_mode, &outer_step))
    {
      iv->base = NULL_RTX;
      goto end;
    }

  /* Loop transforms base to es (base + inner_step) + outer_step,
     where es means extend of subreg between inner_mode and outer_mode.
     The corresponding induction variable is

     es ((base - outer_step) + i * (inner_step + outer_step)) + outer_step  */

  iv->base = simplify_gen_binary (MINUS, outer_mode, def, outer_step);
  iv->step = simplify_gen_binary (PLUS, outer_mode, inner_step, outer_step);
  iv->mode = inner_mode;
  iv->extend_mode = outer_mode;
  iv->extend = extend;
  iv->mult = const1_rtx;
  iv->delta = outer_step;
  iv->first_special = inner_mode != outer_mode;

 end:
  if (dump_file)
    {
      fprintf (dump_file, "  ");
      dump_iv_info (dump_file, iv);
      fprintf (dump_file, "\n");
    }

  bivs[regno] = *iv;

  return iv->base != NULL_RTX;
}

/* Analyzes operand OP of INSN and stores the result to *IV.  */

static bool
iv_analyze_op (rtx insn, rtx op, struct rtx_iv *iv)
{
  rtx def_insn;
  unsigned regno;
  bool inv = CONSTANT_P (op);

  if (dump_file)
    {
      fprintf (dump_file, "Analysing operand ");
      print_rtl (dump_file, op);
      fprintf (dump_file, " of insn ");
      print_rtl_single (dump_file, insn);
    }

  if (GET_CODE (op) == SUBREG)
    {
      if (!subreg_lowpart_p (op))
	return false;

      if (!iv_analyze_op (insn, SUBREG_REG (op), iv))
	return false;

      return iv_subreg (iv, GET_MODE (op));
    }

  if (!inv)
    {
      regno = REGNO (op);
      if (!last_def[regno])
	inv = true;
      else if (last_def[regno] == const0_rtx)
	{
	  if (dump_file)
	    fprintf (dump_file, "  not simple.\n");
	  return false;
	}
    }

  if (inv)
    {
      iv_constant (iv, op, VOIDmode);

      if (dump_file)
	{
	  fprintf (dump_file, "  ");
	  dump_iv_info (dump_file, iv);
	  fprintf (dump_file, "\n");
	}
      return true;
    }

  def_insn = iv_get_reaching_def (insn, op);
  if (def_insn == const0_rtx)
    {
      if (dump_file)
	fprintf (dump_file, "  not simple.\n");
      return false;
    }

  return iv_analyze (def_insn, op, iv);
}

/* Analyzes iv DEF defined in INSN and stores the result to *IV.  */

bool
iv_analyze (rtx insn, rtx def, struct rtx_iv *iv)
{
  unsigned uid;
  rtx set, rhs, mby = NULL_RTX, tmp;
  rtx op0 = NULL_RTX, op1 = NULL_RTX;
  struct rtx_iv iv0, iv1;
  enum machine_mode amode;
  enum rtx_code code;

  if (insn == const0_rtx)
    return false;

  if (GET_CODE (def) == SUBREG)
    {
      if (!subreg_lowpart_p (def))
	return false;

      if (!iv_analyze (insn, SUBREG_REG (def), iv))
	return false;

      return iv_subreg (iv, GET_MODE (def));
    }

  if (!insn)
    return iv_analyze_biv (def, iv);

  if (dump_file)
    {
      fprintf (dump_file, "Analysing def of ");
      print_rtl (dump_file, def);
      fprintf (dump_file, " in insn ");
      print_rtl_single (dump_file, insn);
    }

  uid = INSN_UID (insn);
  if (insn_info[uid].iv.analysed)
    {
      if (dump_file)
	fprintf (dump_file, "  already analysed.\n");
      *iv = insn_info[uid].iv;
      return iv->base != NULL_RTX;
    }

  iv->mode = VOIDmode;
  iv->base = NULL_RTX;
  iv->step = NULL_RTX;

  set = single_set (insn);
  rhs = find_reg_equal_equiv_note (insn);
  if (rhs)
    rhs = XEXP (rhs, 0);
  else
    rhs = SET_SRC (set);
  code = GET_CODE (rhs);

  if (CONSTANT_P (rhs))
    {
      op0 = rhs;
      amode = GET_MODE (def);
    }
  else
    {
      switch (code)
	{
	case SUBREG:
	  if (!subreg_lowpart_p (rhs))
	    goto end;
	  op0 = rhs;
	  break;
	  
	case REG:
	  op0 = rhs;
	  break;

	case SIGN_EXTEND:
	case ZERO_EXTEND:
	case NEG:
	  op0 = XEXP (rhs, 0);
	  break;

	case PLUS:
	case MINUS:
	  op0 = XEXP (rhs, 0);
	  op1 = XEXP (rhs, 1);
	  break;

	case MULT:
	  op0 = XEXP (rhs, 0);
	  mby = XEXP (rhs, 1);
	  if (!CONSTANT_P (mby))
	    {
	      if (!CONSTANT_P (op0))
		abort ();
	      tmp = op0;
	      op0 = mby;
	      mby = tmp;
	    }
	  break;

	case ASHIFT:
	  if (CONSTANT_P (XEXP (rhs, 0)))
	    abort ();
	  op0 = XEXP (rhs, 0);
	  mby = XEXP (rhs, 1);
	  break;

	default:
	  abort ();
	}

      amode = GET_MODE (rhs);
    }

  if (op0)
    {
      if (!iv_analyze_op (insn, op0, &iv0))
	goto end;
	
      if (iv0.mode == VOIDmode)
	{
	  iv0.mode = amode;
	  iv0.extend_mode = amode;
	}
    }

  if (op1)
    {
      if (!iv_analyze_op (insn, op1, &iv1))
	goto end;

      if (iv1.mode == VOIDmode)
	{
	  iv1.mode = amode;
	  iv1.extend_mode = amode;
	}
    }

  switch (code)
    {
    case SIGN_EXTEND:
    case ZERO_EXTEND:
      if (!iv_extend (&iv0, code, amode))
	goto end;
      break;

    case NEG:
      if (!iv_neg (&iv0))
	goto end;
      break;

    case PLUS:
    case MINUS:
      if (!iv_add (&iv0, &iv1, code))
	goto end;
      break;

    case MULT:
      if (!iv_mult (&iv0, mby))
	goto end;
      break;

    case ASHIFT:
      if (!iv_shift (&iv0, mby))
	goto end;
      break;

    default:
      break;
    }

  *iv = iv0;

 end:
  iv->analysed = true;
  insn_info[uid].iv = *iv;

  if (dump_file)
    {
      print_rtl (dump_file, def);
      fprintf (dump_file, " in insn ");
      print_rtl_single (dump_file, insn);
      fprintf (dump_file, "  is ");
      dump_iv_info (dump_file, iv);
      fprintf (dump_file, "\n");
    }

  return iv->base != NULL_RTX;
}

/* Checks whether definition of register REG in INSN a basic induction
   variable.  IV analysis must have been initialized (via a call to
   iv_analysis_loop_init) for this function to produce a result.  */

bool
biv_p (rtx insn, rtx reg)
{
  struct rtx_iv iv;

  if (!REG_P (reg))
    return false;

  if (last_def[REGNO (reg)] != insn)
    return false;

  return iv_analyze_biv (reg, &iv);
}

/* Calculates value of IV at ITERATION-th iteration.  */

rtx
get_iv_value (struct rtx_iv *iv, rtx iteration)
{
  rtx val;

  /* We would need to generate some if_then_else patterns, and so far
     it is not needed anywhere.  */
  if (iv->first_special)
    abort ();

  if (iv->step != const0_rtx && iteration != const0_rtx)
    val = simplify_gen_binary (PLUS, iv->extend_mode, iv->base,
			       simplify_gen_binary (MULT, iv->extend_mode,
						    iv->step, iteration));
  else
    val = iv->base;

  if (iv->extend_mode == iv->mode)
    return val;

  val = lowpart_subreg (iv->mode, val, iv->extend_mode);

  if (iv->extend == UNKNOWN)
    return val;

  val = simplify_gen_unary (iv->extend, iv->extend_mode, val, iv->mode);
  val = simplify_gen_binary (PLUS, iv->extend_mode, iv->delta,
			     simplify_gen_binary (MULT, iv->extend_mode,
						  iv->mult, val));

  return val;
}

/* Free the data for an induction variable analysis.  */

void
iv_analysis_done (void)
{
  max_insn_no = 0;
  max_reg_no = 0;
  if (insn_info)
    {
      free (insn_info);
      insn_info = NULL;
    }
  if (last_def)
    {
      free (last_def);
      last_def = NULL;
    }
  if (bivs)
    {
      free (bivs);
      bivs = NULL;
    }
}

/* Computes inverse to X modulo (1 << MOD).  */

static unsigned HOST_WIDEST_INT
inverse (unsigned HOST_WIDEST_INT x, int mod)
{
  unsigned HOST_WIDEST_INT mask =
	  ((unsigned HOST_WIDEST_INT) 1 << (mod - 1) << 1) - 1;
  unsigned HOST_WIDEST_INT rslt = 1;
  int i;

  for (i = 0; i < mod - 1; i++)
    {
      rslt = (rslt * x) & mask;
      x = (x * x) & mask;
    }

  return rslt;
}

/* Tries to estimate the maximum number of iterations.  */

static unsigned HOST_WIDEST_INT
determine_max_iter (struct niter_desc *desc)
{
  rtx niter = desc->niter_expr;
  rtx mmin, mmax, left, right;
  unsigned HOST_WIDEST_INT nmax, inc;

  if (GET_CODE (niter) == AND
      && GET_CODE (XEXP (niter, 0)) == CONST_INT)
    {
      nmax = INTVAL (XEXP (niter, 0));
      if (!(nmax & (nmax + 1)))
	{
	  desc->niter_max = nmax;
	  return nmax;
	}
    }

  get_mode_bounds (desc->mode, desc->signed_p, desc->mode, &mmin, &mmax);
  nmax = INTVAL (mmax) - INTVAL (mmin);

  if (GET_CODE (niter) == UDIV)
    {
      if (GET_CODE (XEXP (niter, 1)) != CONST_INT)
	{
	  desc->niter_max = nmax;
	  return nmax;
	}
      inc = INTVAL (XEXP (niter, 1));
      niter = XEXP (niter, 0);
    }
  else
    inc = 1;

  if (GET_CODE (niter) == PLUS)
    {
      left = XEXP (niter, 0);
      right = XEXP (niter, 0);

      if (GET_CODE (right) == CONST_INT)
	right = GEN_INT (-INTVAL (right));
    }
  else if (GET_CODE (niter) == MINUS)
    {
      left = XEXP (niter, 0);
      right = XEXP (niter, 0);
    }
  else
    {
      left = niter;
      right = mmin;
    }

  if (GET_CODE (left) == CONST_INT)
    mmax = left;
  if (GET_CODE (right) == CONST_INT)
    mmin = right;
  nmax = INTVAL (mmax) - INTVAL (mmin);

  desc->niter_max = nmax / inc;
  return nmax / inc;
}

/* Checks whether register *REG is in set ALT.  Callback for for_each_rtx.  */

static int
altered_reg_used (rtx *reg, void *alt)
{
  if (!REG_P (*reg))
    return 0;

  return REGNO_REG_SET_P (alt, REGNO (*reg));
}

/* Marks registers altered by EXPR in set ALT.  */

static void
mark_altered (rtx expr, rtx by ATTRIBUTE_UNUSED, void *alt)
{
  if (GET_CODE (expr) == SUBREG)
    expr = SUBREG_REG (expr);
  if (!REG_P (expr))
    return;

  SET_REGNO_REG_SET (alt, REGNO (expr));
}

/* Checks whether RHS is simple enough to process.  */

static bool
simple_rhs_p (rtx rhs)
{
  rtx op0, op1;

  if (CONSTANT_P (rhs)
      || REG_P (rhs))
    return true;

  switch (GET_CODE (rhs))
    {
    case PLUS:
    case MINUS:
      op0 = XEXP (rhs, 0);
      op1 = XEXP (rhs, 1);
      /* Allow reg + const sets only.  */
      if (REG_P (op0) && CONSTANT_P (op1))
	return true;
      if (REG_P (op1) && CONSTANT_P (op0))
	return true;

      return false;

    default:
      return false;
    }
}

/* Simplifies *EXPR using assignment in INSN.  ALTERED is the set of registers
   altered so far.  */

static void
simplify_using_assignment (rtx insn, rtx *expr, regset altered)
{
  rtx set = single_set (insn);
  rtx lhs = NULL_RTX, rhs;
  bool ret = false;

  if (set)
    {
      lhs = SET_DEST (set);
      if (!REG_P (lhs)
	  || altered_reg_used (&lhs, altered))
	ret = true;
    }
  else
    ret = true;

  note_stores (PATTERN (insn), mark_altered, altered);
  if (CALL_P (insn))
    {
      int i;

      /* Kill all call clobbered registers.  */
      for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
	if (TEST_HARD_REG_BIT (regs_invalidated_by_call, i))
	  SET_REGNO_REG_SET (altered, i);
    }

  if (ret)
    return;

  rhs = find_reg_equal_equiv_note (insn);
  if (rhs)
    rhs = XEXP (rhs, 0);
  else
    rhs = SET_SRC (set);

  if (!simple_rhs_p (rhs))
    return;

  if (for_each_rtx (&rhs, altered_reg_used, altered))
    return;

  *expr = simplify_replace_rtx (*expr, lhs, rhs);
}

/* Checks whether A implies B.  */

static bool
implies_p (rtx a, rtx b)
{
  rtx op0, op1, opb0, opb1, r;
  enum machine_mode mode;

  if (GET_CODE (a) == EQ)
    {
      op0 = XEXP (a, 0);
      op1 = XEXP (a, 1);

      if (REG_P (op0))
	{
	  r = simplify_replace_rtx (b, op0, op1);
	  if (r == const_true_rtx)
	    return true;
	}

      if (REG_P (op1))
	{
	  r = simplify_replace_rtx (b, op1, op0);
	  if (r == const_true_rtx)
	    return true;
	}
    }

  /* A < B implies A + 1 <= B.  */
  if ((GET_CODE (a) == GT || GET_CODE (a) == LT)
      && (GET_CODE (b) == GE || GET_CODE (b) == LE))
    {
      op0 = XEXP (a, 0);
      op1 = XEXP (a, 1);
      opb0 = XEXP (b, 0);
      opb1 = XEXP (b, 1);

      if (GET_CODE (a) == GT)
	{
	  r = op0;
	  op0 = op1;
	  op1 = r;
	}

      if (GET_CODE (b) == GE)
	{
	  r = opb0;
	  opb0 = opb1;
	  opb1 = r;
	}

      mode = GET_MODE (op0);
      if (mode != GET_MODE (opb0))
	mode = VOIDmode;
      else if (mode == VOIDmode)
	{
	  mode = GET_MODE (op1);
	  if (mode != GET_MODE (opb1))
	    mode = VOIDmode;
	}

      if (mode != VOIDmode
	  && rtx_equal_p (op1, opb1)
	  && simplify_gen_binary (MINUS, mode, opb0, op0) == const1_rtx)
	return true;
    }

  return false;
}

/* Canonicalizes COND so that

   (1) Ensure that operands are ordered according to
       swap_commutative_operands_p.
   (2) (LE x const) will be replaced with (LT x <const+1>) and similarly
       for GE, GEU, and LEU.  */

rtx
canon_condition (rtx cond)
{
  rtx tem;
  rtx op0, op1;
  enum rtx_code code;
  enum machine_mode mode;

  code = GET_CODE (cond);
  op0 = XEXP (cond, 0);
  op1 = XEXP (cond, 1);

  if (swap_commutative_operands_p (op0, op1))
    {
      code = swap_condition (code);
      tem = op0;
      op0 = op1;
      op1 = tem;
    }

  mode = GET_MODE (op0);
  if (mode == VOIDmode)
    mode = GET_MODE (op1);
  if (mode == VOIDmode)
    abort ();

  if (GET_CODE (op1) == CONST_INT
      && GET_MODE_CLASS (mode) != MODE_CC
      && GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
    {
      HOST_WIDE_INT const_val = INTVAL (op1);
      unsigned HOST_WIDE_INT uconst_val = const_val;
      unsigned HOST_WIDE_INT max_val
	= (unsigned HOST_WIDE_INT) GET_MODE_MASK (mode);

      switch (code)
	{
	case LE:
	  if ((unsigned HOST_WIDE_INT) const_val != max_val >> 1)
	    code = LT, op1 = gen_int_mode (const_val + 1, GET_MODE (op0));
	  break;

	/* When cross-compiling, const_val might be sign-extended from
	   BITS_PER_WORD to HOST_BITS_PER_WIDE_INT */
	case GE:
	  if ((HOST_WIDE_INT) (const_val & max_val)
	      != (((HOST_WIDE_INT) 1
		   << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
	    code = GT, op1 = gen_int_mode (const_val - 1, mode);
	  break;

	case LEU:
	  if (uconst_val < max_val)
	    code = LTU, op1 = gen_int_mode (uconst_val + 1, mode);
	  break;

	case GEU:
	  if (uconst_val != 0)
	    code = GTU, op1 = gen_int_mode (uconst_val - 1, mode);
	  break;

	default:
	  break;
	}
    }

  if (op0 != XEXP (cond, 0)
      || op1 != XEXP (cond, 1)
      || code != GET_CODE (cond)
      || GET_MODE (cond) != SImode)
    cond = gen_rtx_fmt_ee (code, SImode, op0, op1);

  return cond;
}

/* Tries to use the fact that COND holds to simplify EXPR.  ALTERED is the
   set of altered regs.  */

void
simplify_using_condition (rtx cond, rtx *expr, regset altered)
{
  rtx rev, reve, exp = *expr;

  if (!COMPARISON_P (exp))
    return;

  /* If some register gets altered later, we do not really speak about its
     value at the time of comparison.  */
  if (altered
      && for_each_rtx (&cond, altered_reg_used, altered))
    return;

  rev = reversed_condition (cond);
  reve = reversed_condition (exp);

  cond = canon_condition (cond);
  exp = canon_condition (exp);
  if (rev)
    rev = canon_condition (rev);
  if (reve)
    reve = canon_condition (reve);

  if (rtx_equal_p (exp, cond))
    {
      *expr = const_true_rtx;
      return;
    }


  if (rev && rtx_equal_p (exp, rev))
    {
      *expr = const0_rtx;
      return;
    }

  if (implies_p (cond, exp))
    {
      *expr = const_true_rtx;
      return;
    }
  
  if (reve && implies_p (cond, reve))
    {
      *expr = const0_rtx;
      return;
    }

  /* A proof by contradiction.  If *EXPR implies (not cond), *EXPR must
     be false.  */
  if (rev && implies_p (exp, rev))
    {
      *expr = const0_rtx;
      return;
    }

  /* Similarly, If (not *EXPR) implies (not cond), *EXPR must be true.  */
  if (rev && reve && implies_p (reve, rev))
    {
      *expr = const_true_rtx;
      return;
    }

  /* We would like to have some other tests here.  TODO.  */

  return;
}

/* Use relationship between A and *B to eventually eliminate *B.
   OP is the operation we consider.  */

static void
eliminate_implied_condition (enum rtx_code op, rtx a, rtx *b)
{
  if (op == AND)
    {
      /* If A implies *B, we may replace *B by true.  */
      if (implies_p (a, *b))
	*b = const_true_rtx;
    }
  else if (op == IOR)
    {
      /* If *B implies A, we may replace *B by false.  */
      if (implies_p (*b, a))
	*b = const0_rtx;
    }
  else
    abort ();
}

/* Eliminates the conditions in TAIL that are implied by HEAD.  OP is the
   operation we consider.  */

static void
eliminate_implied_conditions (enum rtx_code op, rtx *head, rtx tail)
{
  rtx elt;

  for (elt = tail; elt; elt = XEXP (elt, 1))
    eliminate_implied_condition (op, *head, &XEXP (elt, 0));
  for (elt = tail; elt; elt = XEXP (elt, 1))
    eliminate_implied_condition (op, XEXP (elt, 0), head);
}

/* Simplifies *EXPR using initial values at the start of the LOOP.  If *EXPR
   is a list, its elements are assumed to be combined using OP.  */

static void
simplify_using_initial_values (struct loop *loop, enum rtx_code op, rtx *expr)
{
  rtx head, tail, insn;
  rtx neutral, aggr;
  regset altered;
  regset_head altered_head;
  edge e;

  if (!*expr)
    return;

  if (CONSTANT_P (*expr))
    return;

  if (GET_CODE (*expr) == EXPR_LIST)
    {
      head = XEXP (*expr, 0);
      tail = XEXP (*expr, 1);

      eliminate_implied_conditions (op, &head, tail);

      if (op == AND)
	{
	  neutral = const_true_rtx;
	  aggr = const0_rtx;
	}
      else if (op == IOR)
	{
	  neutral = const0_rtx;
	  aggr = const_true_rtx;
	}
      else
	abort ();

      simplify_using_initial_values (loop, UNKNOWN, &head);
      if (head == aggr)
	{
	  XEXP (*expr, 0) = aggr;
	  XEXP (*expr, 1) = NULL_RTX;
	  return;
	}
      else if (head == neutral)
	{
	  *expr = tail;
	  simplify_using_initial_values (loop, op, expr);
	  return;
	}
      simplify_using_initial_values (loop, op, &tail);

      if (tail && XEXP (tail, 0) == aggr)
	{
	  *expr = tail;
	  return;
	}
  
      XEXP (*expr, 0) = head;
      XEXP (*expr, 1) = tail;
      return;
    }

  if (op != UNKNOWN)
    abort ();

  e = loop_preheader_edge (loop);
  if (e->src == ENTRY_BLOCK_PTR)
    return;

  altered = INITIALIZE_REG_SET (altered_head);

  while (1)
    {
      basic_block tmp_bb;

      insn = BB_END (e->src);
      if (any_condjump_p (insn))
	{
	  rtx cond = get_condition (BB_END (e->src), NULL, false, true);
      
	  if (cond && (e->flags & EDGE_FALLTHRU))
	    cond = reversed_condition (cond);
	  if (cond)
	    {
	      simplify_using_condition (cond, expr, altered);
	      if (CONSTANT_P (*expr))
		{
		  FREE_REG_SET (altered);
		  return;
		}
	    }
	}

      FOR_BB_INSNS_REVERSE (e->src, insn)
	{
	  if (!INSN_P (insn))
	    continue;
	    
	  simplify_using_assignment (insn, expr, altered);
	  if (CONSTANT_P (*expr))
	    {
	      FREE_REG_SET (altered);
	      return;
	    }
	}

      /* This is a bit subtle.  Store away e->src in tmp_bb, since we
	 modify `e' and this can invalidate the subsequent count of
	 e->src's predecessors by looking at the wrong block.  */
      tmp_bb = e->src;
      e = EDGE_PRED (tmp_bb, 0);
      if (EDGE_COUNT (tmp_bb->preds) > 1
	  || e->src == ENTRY_BLOCK_PTR)
	break;
    }

  FREE_REG_SET (altered);
}

/* Transforms invariant IV into MODE.  Adds assumptions based on the fact
   that IV occurs as left operands of comparison COND and its signedness
   is SIGNED_P to DESC.  */

static void
shorten_into_mode (struct rtx_iv *iv, enum machine_mode mode,
		   enum rtx_code cond, bool signed_p, struct niter_desc *desc)
{
  rtx mmin, mmax, cond_over, cond_under;

  get_mode_bounds (mode, signed_p, iv->extend_mode, &mmin, &mmax);
  cond_under = simplify_gen_relational (LT, SImode, iv->extend_mode,
					iv->base, mmin);
  cond_over = simplify_gen_relational (GT, SImode, iv->extend_mode,
				       iv->base, mmax);

  switch (cond)
    {
      case LE:
      case LT:
      case LEU:
      case LTU:
	if (cond_under != const0_rtx)
	  desc->infinite =
		  alloc_EXPR_LIST (0, cond_under, desc->infinite);
	if (cond_over != const0_rtx)
	  desc->noloop_assumptions =
		  alloc_EXPR_LIST (0, cond_over, desc->noloop_assumptions);
	break;

      case GE:
      case GT:
      case GEU:
      case GTU:
	if (cond_over != const0_rtx)
	  desc->infinite =
		  alloc_EXPR_LIST (0, cond_over, desc->infinite);
	if (cond_under != const0_rtx)
	  desc->noloop_assumptions =
		  alloc_EXPR_LIST (0, cond_under, desc->noloop_assumptions);
	break;

      case NE:
	if (cond_over != const0_rtx)
	  desc->infinite =
		  alloc_EXPR_LIST (0, cond_over, desc->infinite);
	if (cond_under != const0_rtx)
	  desc->infinite =
		  alloc_EXPR_LIST (0, cond_under, desc->infinite);
	break;

      default:
	abort ();
    }

  iv->mode = mode;
  iv->extend = signed_p ? SIGN_EXTEND : ZERO_EXTEND;
}

/* Transforms IV0 and IV1 compared by COND so that they are both compared as
   subregs of the same mode if possible (sometimes it is necessary to add
   some assumptions to DESC).  */

static bool
canonicalize_iv_subregs (struct rtx_iv *iv0, struct rtx_iv *iv1,
			 enum rtx_code cond, struct niter_desc *desc)
{
  enum machine_mode comp_mode;
  bool signed_p;

  /* If the ivs behave specially in the first iteration, or are
     added/multiplied after extending, we ignore them.  */
  if (iv0->first_special || iv0->mult != const1_rtx || iv0->delta != const0_rtx)
    return false;
  if (iv1->first_special || iv1->mult != const1_rtx || iv1->delta != const0_rtx)
    return false;

  /* If there is some extend, it must match signedness of the comparison.  */
  switch (cond)
    {
      case LE:
      case LT:
	if (iv0->extend == ZERO_EXTEND
	    || iv1->extend == ZERO_EXTEND)
	  return false;
	signed_p = true;
	break;

      case LEU:
      case LTU:
	if (iv0->extend == SIGN_EXTEND
	    || iv1->extend == SIGN_EXTEND)
	  return false;
	signed_p = false;
	break;

      case NE:
	if (iv0->extend != UNKNOWN
	    && iv1->extend != UNKNOWN
	    && iv0->extend != iv1->extend)
	  return false;

	signed_p = false;
	if (iv0->extend != UNKNOWN)
	  signed_p = iv0->extend == SIGN_EXTEND;
	if (iv1->extend != UNKNOWN)
	  signed_p = iv1->extend == SIGN_EXTEND;
	break;

      default:
	abort ();
    }

  /* Values of both variables should be computed in the same mode.  These
     might indeed be different, if we have comparison like

     (compare (subreg:SI (iv0)) (subreg:SI (iv1)))

     and iv0 and iv1 are both ivs iterating in SI mode, but calculated
     in different modes.  This does not seem impossible to handle, but
     it hardly ever occurs in practice.
     
     The only exception is the case when one of operands is invariant.
     For example pentium 3 generates comparisons like
     (lt (subreg:HI (reg:SI)) 100).  Here we assign HImode to 100, but we
     definitely do not want this prevent the optimization.  */
  comp_mode = iv0->extend_mode;
  if (GET_MODE_BITSIZE (comp_mode) < GET_MODE_BITSIZE (iv1->extend_mode))
    comp_mode = iv1->extend_mode;

  if (iv0->extend_mode != comp_mode)
    {
      if (iv0->mode != iv0->extend_mode
	  || iv0->step != const0_rtx)
	return false;

      iv0->base = simplify_gen_unary (signed_p ? SIGN_EXTEND : ZERO_EXTEND,
				      comp_mode, iv0->base, iv0->mode);
      iv0->extend_mode = comp_mode;
    }

  if (iv1->extend_mode != comp_mode)
    {
      if (iv1->mode != iv1->extend_mode
	  || iv1->step != const0_rtx)
	return false;

      iv1->base = simplify_gen_unary (signed_p ? SIGN_EXTEND : ZERO_EXTEND,
				      comp_mode, iv1->base, iv1->mode);
      iv1->extend_mode = comp_mode;
    }

  /* Check that both ivs belong to a range of a single mode.  If one of the
     operands is an invariant, we may need to shorten it into the common
     mode.  */
  if (iv0->mode == iv0->extend_mode
      && iv0->step == const0_rtx
      && iv0->mode != iv1->mode)
    shorten_into_mode (iv0, iv1->mode, cond, signed_p, desc);

  if (iv1->mode == iv1->extend_mode
      && iv1->step == const0_rtx
      && iv0->mode != iv1->mode)
    shorten_into_mode (iv1, iv0->mode, swap_condition (cond), signed_p, desc);

  if (iv0->mode != iv1->mode)
    return false;

  desc->mode = iv0->mode;
  desc->signed_p = signed_p;

  return true;
}

/* Computes number of iterations of the CONDITION in INSN in LOOP and stores
   the result into DESC.  Very similar to determine_number_of_iterations
   (basically its rtl version), complicated by things like subregs.  */

void
iv_number_of_iterations (struct loop *loop, rtx insn, rtx condition,
			 struct niter_desc *desc)
{
  rtx op0, op1, delta, step, bound, may_xform, def_insn, tmp, tmp0, tmp1;
  struct rtx_iv iv0, iv1, tmp_iv;
  rtx assumption, may_not_xform;
  enum rtx_code cond;
  enum machine_mode mode, comp_mode;
  rtx mmin, mmax, mode_mmin, mode_mmax;
  unsigned HOST_WIDEST_INT s, size, d, inv;
  HOST_WIDEST_INT up, down, inc;
  int was_sharp = false;
  rtx old_niter;

  /* The meaning of these assumptions is this:
     if !assumptions
       then the rest of information does not have to be valid
     if noloop_assumptions then the loop does not roll
     if infinite then this exit is never used */

  desc->assumptions = NULL_RTX;
  desc->noloop_assumptions = NULL_RTX;
  desc->infinite = NULL_RTX;
  desc->simple_p = true;

  desc->const_iter = false;
  desc->niter_expr = NULL_RTX;
  desc->niter_max = 0;

  cond = GET_CODE (condition);
  if (!COMPARISON_P (condition))
    abort ();

  mode = GET_MODE (XEXP (condition, 0));
  if (mode == VOIDmode)
    mode = GET_MODE (XEXP (condition, 1));
  /* The constant comparisons should be folded.  */
  if (mode == VOIDmode)
    abort ();

  /* We only handle integers or pointers.  */
  if (GET_MODE_CLASS (mode) != MODE_INT
      && GET_MODE_CLASS (mode) != MODE_PARTIAL_INT)
    goto fail;

  op0 = XEXP (condition, 0);
  def_insn = iv_get_reaching_def (insn, op0);
  if (!iv_analyze (def_insn, op0, &iv0))
    goto fail;
  if (iv0.extend_mode == VOIDmode)
    iv0.mode = iv0.extend_mode = mode;
  
  op1 = XEXP (condition, 1);
  def_insn = iv_get_reaching_def (insn, op1);
  if (!iv_analyze (def_insn, op1, &iv1))
    goto fail;
  if (iv1.extend_mode == VOIDmode)
    iv1.mode = iv1.extend_mode = mode;

  if (GET_MODE_BITSIZE (iv0.extend_mode) > HOST_BITS_PER_WIDE_INT
      || GET_MODE_BITSIZE (iv1.extend_mode) > HOST_BITS_PER_WIDE_INT)
    goto fail;

  /* Check condition and normalize it.  */

  switch (cond)
    {
      case GE:
      case GT:
      case GEU:
      case GTU:
	tmp_iv = iv0; iv0 = iv1; iv1 = tmp_iv;
	cond = swap_condition (cond);
	break;
      case NE:
      case LE:
      case LEU:
      case LT:
      case LTU:
	break;
      default:
	goto fail;
    }

  /* Handle extends.  This is relatively nontrivial, so we only try in some
     easy cases, when we can canonicalize the ivs (possibly by adding some
     assumptions) to shape subreg (base + i * step).  This function also fills
     in desc->mode and desc->signed_p.  */

  if (!canonicalize_iv_subregs (&iv0, &iv1, cond, desc))
    goto fail;

  comp_mode = iv0.extend_mode;
  mode = iv0.mode;
  size = GET_MODE_BITSIZE (mode);
  get_mode_bounds (mode, (cond == LE || cond == LT), comp_mode, &mmin, &mmax);
  mode_mmin = lowpart_subreg (mode, mmin, comp_mode);
  mode_mmax = lowpart_subreg (mode, mmax, comp_mode);

  if (GET_CODE (iv0.step) != CONST_INT || GET_CODE (iv1.step) != CONST_INT)
    goto fail;

  /* We can take care of the case of two induction variables chasing each other
     if the test is NE. I have never seen a loop using it, but still it is
     cool.  */
  if (iv0.step != const0_rtx && iv1.step != const0_rtx)
    {
      if (cond != NE)
	goto fail;

      iv0.step = simplify_gen_binary (MINUS, comp_mode, iv0.step, iv1.step);
      iv1.step = const0_rtx;
    }

  /* This is either infinite loop or the one that ends immediately, depending
     on initial values.  Unswitching should remove this kind of conditions.  */
  if (iv0.step == const0_rtx && iv1.step == const0_rtx)
    goto fail;

  /* Ignore loops of while (i-- < 10) type.  */
  if (cond != NE
      && (INTVAL (iv0.step) < 0 || INTVAL (iv1.step) > 0))
    goto fail;

  /* Some more condition normalization.  We must record some assumptions
     due to overflows.  */
  switch (cond)
    {
      case LT:
      case LTU:
	/* We want to take care only of non-sharp relationals; this is easy,
	   as in cases the overflow would make the transformation unsafe
	   the loop does not roll.  Seemingly it would make more sense to want
	   to take care of sharp relationals instead, as NE is more similar to
	   them, but the problem is that here the transformation would be more
	   difficult due to possibly infinite loops.  */
	if (iv0.step == const0_rtx)
	  {
	    tmp = lowpart_subreg (mode, iv0.base, comp_mode);
	    assumption = simplify_gen_relational (EQ, SImode, mode, tmp,
						  mode_mmax);
	    if (assumption == const_true_rtx)
	      goto zero_iter;
	    iv0.base = simplify_gen_binary (PLUS, comp_mode,
					    iv0.base, const1_rtx);
	  }
	else
	  {
	    tmp = lowpart_subreg (mode, iv1.base, comp_mode);
	    assumption = simplify_gen_relational (EQ, SImode, mode, tmp,
						  mode_mmin);
	    if (assumption == const_true_rtx)
	      goto zero_iter;
	    iv1.base = simplify_gen_binary (PLUS, comp_mode,
					    iv1.base, constm1_rtx);
	  }

	if (assumption != const0_rtx)
	  desc->noloop_assumptions =
		  alloc_EXPR_LIST (0, assumption, desc->noloop_assumptions);
	cond = (cond == LT) ? LE : LEU;

	/* It will be useful to be able to tell the difference once more in
	   LE -> NE reduction.  */
	was_sharp = true;
	break;
      default: ;
    }

  /* Take care of trivially infinite loops.  */
  if (cond != NE)
    {
      if (iv0.step == const0_rtx)
	{
	  tmp = lowpart_subreg (mode, iv0.base, comp_mode);
	  if (rtx_equal_p (tmp, mode_mmin))
	    {
	      desc->infinite =
		      alloc_EXPR_LIST (0, const_true_rtx, NULL_RTX);
	      return;
	    }
	}
      else
	{
	  tmp = lowpart_subreg (mode, iv1.base, comp_mode);
	  if (rtx_equal_p (tmp, mode_mmax))
	    {
	      desc->infinite =
		      alloc_EXPR_LIST (0, const_true_rtx, NULL_RTX);
	      return;
	    }
	}
    }

  /* If we can we want to take care of NE conditions instead of size
     comparisons, as they are much more friendly (most importantly
     this takes care of special handling of loops with step 1).  We can
     do it if we first check that upper bound is greater or equal to
     lower bound, their difference is constant c modulo step and that
     there is not an overflow.  */
  if (cond != NE)
    {
      if (iv0.step == const0_rtx)
	step = simplify_gen_unary (NEG, comp_mode, iv1.step, comp_mode);
      else
	step = iv0.step;
      delta = simplify_gen_binary (MINUS, comp_mode, iv1.base, iv0.base);
      delta = lowpart_subreg (mode, delta, comp_mode);
      delta = simplify_gen_binary (UMOD, mode, delta, step);
      may_xform = const0_rtx;
      may_not_xform = const_true_rtx;

      if (GET_CODE (delta) == CONST_INT)
	{
	  if (was_sharp && INTVAL (delta) == INTVAL (step) - 1)
	    {
	      /* A special case.  We have transformed condition of type
		 for (i = 0; i < 4; i += 4)
		 into
		 for (i = 0; i <= 3; i += 4)
		 obviously if the test for overflow during that transformation
		 passed, we cannot overflow here.  Most importantly any
		 loop with sharp end condition and step 1 falls into this
		 category, so handling this case specially is definitely
		 worth the troubles.  */
	      may_xform = const_true_rtx;
	    }
	  else if (iv0.step == const0_rtx)
	    {
	      bound = simplify_gen_binary (PLUS, comp_mode, mmin, step);
	      bound = simplify_gen_binary (MINUS, comp_mode, bound, delta);
	      bound = lowpart_subreg (mode, bound, comp_mode);
	      tmp = lowpart_subreg (mode, iv0.base, comp_mode);
	      may_xform = simplify_gen_relational (cond, SImode, mode,
						   bound, tmp);
	      may_not_xform = simplify_gen_relational (reverse_condition (cond),
						       SImode, mode,
						       bound, tmp);
	    }
	  else
	    {
	      bound = simplify_gen_binary (MINUS, comp_mode, mmax, step);
	      bound = simplify_gen_binary (PLUS, comp_mode, bound, delta);
	      bound = lowpart_subreg (mode, bound, comp_mode);
	      tmp = lowpart_subreg (mode, iv1.base, comp_mode);
	      may_xform = simplify_gen_relational (cond, SImode, mode,
						   tmp, bound);
	      may_not_xform = simplify_gen_relational (reverse_condition (cond),
						       SImode, mode,
						       tmp, bound);
	    }
	}

      if (may_xform != const0_rtx)
	{
	  /* We perform the transformation always provided that it is not
	     completely senseless.  This is OK, as we would need this assumption
	     to determine the number of iterations anyway.  */
	  if (may_xform != const_true_rtx)
	    {
	      /* If the step is a power of two and the final value we have
		 computed overflows, the cycle is infinite.  Otherwise it
		 is nontrivial to compute the number of iterations.  */
	      s = INTVAL (step);
	      if ((s & (s - 1)) == 0)
		desc->infinite = alloc_EXPR_LIST (0, may_not_xform,
						  desc->infinite);
	      else
		desc->assumptions = alloc_EXPR_LIST (0, may_xform,
						     desc->assumptions);
	    }

	  /* We are going to lose some information about upper bound on
	     number of iterations in this step, so record the information
	     here.  */
	  inc = INTVAL (iv0.step) - INTVAL (iv1.step);
	  if (GET_CODE (iv1.base) == CONST_INT)
	    up = INTVAL (iv1.base);
	  else
	    up = INTVAL (mode_mmax) - inc;
	  down = INTVAL (GET_CODE (iv0.base) == CONST_INT
			 ? iv0.base
			 : mode_mmin);
	  desc->niter_max = (up - down) / inc + 1;

	  if (iv0.step == const0_rtx)
	    {
	      iv0.base = simplify_gen_binary (PLUS, comp_mode, iv0.base, delta);
	      iv0.base = simplify_gen_binary (MINUS, comp_mode, iv0.base, step);
	    }
	  else
	    {
	      iv1.base = simplify_gen_binary (MINUS, comp_mode, iv1.base, delta);
	      iv1.base = simplify_gen_binary (PLUS, comp_mode, iv1.base, step);
	    }

	  tmp0 = lowpart_subreg (mode, iv0.base, comp_mode);
	  tmp1 = lowpart_subreg (mode, iv1.base, comp_mode);
	  assumption = simplify_gen_relational (reverse_condition (cond),
						SImode, mode, tmp0, tmp1);
	  if (assumption == const_true_rtx)
	    goto zero_iter;
	  else if (assumption != const0_rtx)
	    desc->noloop_assumptions =
		    alloc_EXPR_LIST (0, assumption, desc->noloop_assumptions);
	  cond = NE;
	}
    }

  /* Count the number of iterations.  */
  if (cond == NE)
    {
      /* Everything we do here is just arithmetics modulo size of mode.  This
	 makes us able to do more involved computations of number of iterations
	 than in other cases.  First transform the condition into shape
	 s * i <> c, with s positive.  */
      iv1.base = simplify_gen_binary (MINUS, comp_mode, iv1.base, iv0.base);
      iv0.base = const0_rtx;
      iv0.step = simplify_gen_binary (MINUS, comp_mode, iv0.step, iv1.step);
      iv1.step = const0_rtx;
      if (INTVAL (iv0.step) < 0)
	{
	  iv0.step = simplify_gen_unary (NEG, comp_mode, iv0.step, mode);
	  iv1.base = simplify_gen_unary (NEG, comp_mode, iv1.base, mode);
	}
      iv0.step = lowpart_subreg (mode, iv0.step, comp_mode);

      /* Let nsd (s, size of mode) = d.  If d does not divide c, the loop
	 is infinite.  Otherwise, the number of iterations is
	 (inverse(s/d) * (c/d)) mod (size of mode/d).  */
      s = INTVAL (iv0.step); d = 1;
      while (s % 2 != 1)
	{
	  s /= 2;
	  d *= 2;
	  size--;
	}
      bound = GEN_INT (((unsigned HOST_WIDEST_INT) 1 << (size - 1 ) << 1) - 1);

      tmp1 = lowpart_subreg (mode, iv1.base, comp_mode);
      tmp = simplify_gen_binary (UMOD, mode, tmp1, GEN_INT (d));
      assumption = simplify_gen_relational (NE, SImode, mode, tmp, const0_rtx);
      desc->infinite = alloc_EXPR_LIST (0, assumption, desc->infinite);

      tmp = simplify_gen_binary (UDIV, mode, tmp1, GEN_INT (d));
      inv = inverse (s, size);
      inv = trunc_int_for_mode (inv, mode);
      tmp = simplify_gen_binary (MULT, mode, tmp, GEN_INT (inv));
      desc->niter_expr = simplify_gen_binary (AND, mode, tmp, bound);
    }
  else
    {
      if (iv1.step == const0_rtx)
	/* Condition in shape a + s * i <= b
	   We must know that b + s does not overflow and a <= b + s and then we
	   can compute number of iterations as (b + s - a) / s.  (It might
	   seem that we in fact could be more clever about testing the b + s
	   overflow condition using some information about b - a mod s,
	   but it was already taken into account during LE -> NE transform).  */
	{
	  step = iv0.step;
	  tmp0 = lowpart_subreg (mode, iv0.base, comp_mode);
	  tmp1 = lowpart_subreg (mode, iv1.base, comp_mode);

	  bound = simplify_gen_binary (MINUS, mode, mode_mmax,
				       lowpart_subreg (mode, step, comp_mode));
	  assumption = simplify_gen_relational (cond, SImode, mode,
						tmp1, bound);
	  desc->assumptions =
		  alloc_EXPR_LIST (0, assumption, desc->assumptions);

	  tmp = simplify_gen_binary (PLUS, comp_mode, iv1.base, iv0.step);
	  tmp = lowpart_subreg (mode, tmp, comp_mode);
	  assumption = simplify_gen_relational (reverse_condition (cond),
						SImode, mode, tmp0, tmp);

	  delta = simplify_gen_binary (PLUS, mode, tmp1, step);
	  delta = simplify_gen_binary (MINUS, mode, delta, tmp0);
	}
      else
	{
	  /* Condition in shape a <= b - s * i
	     We must know that a - s does not overflow and a - s <= b and then
	     we can again compute number of iterations as (b - (a - s)) / s.  */
	  step = simplify_gen_unary (NEG, mode, iv1.step, mode);
	  tmp0 = lowpart_subreg (mode, iv0.base, comp_mode);
	  tmp1 = lowpart_subreg (mode, iv1.base, comp_mode);

	  bound = simplify_gen_binary (MINUS, mode, mode_mmin,
				       lowpart_subreg (mode, step, comp_mode));
	  assumption = simplify_gen_relational (cond, SImode, mode,
						bound, tmp0);
	  desc->assumptions =
		  alloc_EXPR_LIST (0, assumption, desc->assumptions);

	  tmp = simplify_gen_binary (PLUS, comp_mode, iv0.base, iv1.step);
	  tmp = lowpart_subreg (mode, tmp, comp_mode);
	  assumption = simplify_gen_relational (reverse_condition (cond),
						SImode, mode,
						tmp, tmp1);
	  delta = simplify_gen_binary (MINUS, mode, tmp0, step);
	  delta = simplify_gen_binary (MINUS, mode, tmp1, delta);
	}
      if (assumption == const_true_rtx)
	goto zero_iter;
      else if (assumption != const0_rtx)
	desc->noloop_assumptions =
		alloc_EXPR_LIST (0, assumption, desc->noloop_assumptions);
      delta = simplify_gen_binary (UDIV, mode, delta, step);
      desc->niter_expr = delta;
    }

  old_niter = desc->niter_expr;

  simplify_using_initial_values (loop, AND, &desc->assumptions);
  if (desc->assumptions
      && XEXP (desc->assumptions, 0) == const0_rtx)
    goto fail;
  simplify_using_initial_values (loop, IOR, &desc->noloop_assumptions);
  simplify_using_initial_values (loop, IOR, &desc->infinite);
  simplify_using_initial_values (loop, UNKNOWN, &desc->niter_expr);

  /* Rerun the simplification.  Consider code (created by copying loop headers)

     i = 0;

     if (0 < n)
       {
         do
	   {
	     i++;
	   } while (i < n);
       }

    The first pass determines that i = 0, the second pass uses it to eliminate
    noloop assumption.  */

  simplify_using_initial_values (loop, AND, &desc->assumptions);
  if (desc->assumptions
      && XEXP (desc->assumptions, 0) == const0_rtx)
    goto fail;
  simplify_using_initial_values (loop, IOR, &desc->noloop_assumptions);
  simplify_using_initial_values (loop, IOR, &desc->infinite);
  simplify_using_initial_values (loop, UNKNOWN, &desc->niter_expr);

  if (desc->noloop_assumptions
      && XEXP (desc->noloop_assumptions, 0) == const_true_rtx)
    goto zero_iter;

  if (GET_CODE (desc->niter_expr) == CONST_INT)
    {
      unsigned HOST_WIDEST_INT val = INTVAL (desc->niter_expr);

      desc->const_iter = true;
      desc->niter_max = desc->niter = val & GET_MODE_MASK (desc->mode);
    }
  else
    {
      if (!desc->niter_max)
	desc->niter_max = determine_max_iter (desc);

      /* simplify_using_initial_values does a copy propagation on the registers
	 in the expression for the number of iterations.  This prolongs life
	 ranges of registers and increases register pressure, and usually
	 brings no gain (and if it happens to do, the cse pass will take care
	 of it anyway).  So prevent this behavior, unless it enabled us to
	 derive that the number of iterations is a constant.  */
      desc->niter_expr = old_niter;
    }

  return;

fail:
  desc->simple_p = false;
  return;

zero_iter:
  desc->const_iter = true;
  desc->niter = 0;
  desc->niter_max = 0;
  desc->niter_expr = const0_rtx;
  return;
}

/* Checks whether E is a simple exit from LOOP and stores its description
   into DESC.  */

static void
check_simple_exit (struct loop *loop, edge e, struct niter_desc *desc)
{
  basic_block exit_bb;
  rtx condition, at;
  edge ein;

  exit_bb = e->src;
  desc->simple_p = false;

  /* It must belong directly to the loop.  */
  if (exit_bb->loop_father != loop)
    return;

  /* It must be tested (at least) once during any iteration.  */
  if (!dominated_by_p (CDI_DOMINATORS, loop->latch, exit_bb))
    return;

  /* It must end in a simple conditional jump.  */
  if (!any_condjump_p (BB_END (exit_bb)))
    return;

  ein = EDGE_SUCC (exit_bb, 0);
  if (ein == e)
    ein = EDGE_SUCC (exit_bb, 1);

  desc->out_edge = e;
  desc->in_edge = ein;

  /* Test whether the condition is suitable.  */
  if (!(condition = get_condition (BB_END (ein->src), &at, false, false)))
    return;

  if (ein->flags & EDGE_FALLTHRU)
    {
      condition = reversed_condition (condition);
      if (!condition)
	return;
    }

  /* Check that we are able to determine number of iterations and fill
     in information about it.  */
  iv_number_of_iterations (loop, at, condition, desc);
}

/* Finds a simple exit of LOOP and stores its description into DESC.  */

void
find_simple_exit (struct loop *loop, struct niter_desc *desc)
{
  unsigned i;
  basic_block *body;
  edge e;
  struct niter_desc act;
  bool any = false;
  edge_iterator ei;

  desc->simple_p = false;
  body = get_loop_body (loop);

  for (i = 0; i < loop->num_nodes; i++)
    {
      FOR_EACH_EDGE (e, ei, body[i]->succs)
	{
	  if (flow_bb_inside_loop_p (loop, e->dest))
	    continue;
	  
	  check_simple_exit (loop, e, &act);
	  if (!act.simple_p)
	    continue;

	  /* Prefer constant iterations; the less the better.  */
	  if (!any)
	    any = true;
	  else if (!act.const_iter
		   || (desc->const_iter && act.niter >= desc->niter))
	    continue;
	  *desc = act;
	}
    }

  if (dump_file)
    {
      if (desc->simple_p)
	{
	  fprintf (dump_file, "Loop %d is simple:\n", loop->num);
	  fprintf (dump_file, "  simple exit %d -> %d\n",
		   desc->out_edge->src->index,
		   desc->out_edge->dest->index);
	  if (desc->assumptions)
	    {
	      fprintf (dump_file, "  assumptions: ");
	      print_rtl (dump_file, desc->assumptions);
	      fprintf (dump_file, "\n");
	    }
	  if (desc->noloop_assumptions)
	    {
	      fprintf (dump_file, "  does not roll if: ");
	      print_rtl (dump_file, desc->noloop_assumptions);
	      fprintf (dump_file, "\n");
	    }
	  if (desc->infinite)
	    {
	      fprintf (dump_file, "  infinite if: ");
	      print_rtl (dump_file, desc->infinite);
	      fprintf (dump_file, "\n");
	    }

	  fprintf (dump_file, "  number of iterations: ");
	  print_rtl (dump_file, desc->niter_expr);
      	  fprintf (dump_file, "\n");

	  fprintf (dump_file, "  upper bound: ");
	  fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, desc->niter_max);
      	  fprintf (dump_file, "\n");
	}
      else
	fprintf (dump_file, "Loop %d is not simple.\n", loop->num);
    }

  free (body);
}

/* Creates a simple loop description of LOOP if it was not computed
   already.  */

struct niter_desc *
get_simple_loop_desc (struct loop *loop)
{
  struct niter_desc *desc = simple_loop_desc (loop);

  if (desc)
    return desc;

  desc = xmalloc (sizeof (struct niter_desc));
  iv_analysis_loop_init (loop);
  find_simple_exit (loop, desc);
  loop->aux = desc;

  return desc;
}

/* Releases simple loop description for LOOP.  */

void
free_simple_loop_desc (struct loop *loop)
{
  struct niter_desc *desc = simple_loop_desc (loop);

  if (!desc)
    return;

  free (desc);
  loop->aux = NULL;
}
ready verified that SIZE and ALIGN are large enough. GNAT_ENTITY is used to name the resulting record and to issue a warning. IS_COMPONENT_TYPE is true if this is being done for the component type of an array. IS_USER_TYPE is true if the original type needs to be completed. DEFINITION is true if this type is being defined. SET_RM_SIZE is true if the RM size of the resulting type is to be set to SIZE too. */ tree maybe_pad_type (tree type, tree size, unsigned int align, Entity_Id gnat_entity, bool is_component_type, bool is_user_type, bool definition, bool set_rm_size) { tree orig_size = TYPE_SIZE (type); unsigned int orig_align = TYPE_ALIGN (type); tree record, field; /* If TYPE is a padded type, see if it agrees with any size and alignment we were given. If so, return the original type. Otherwise, strip off the padding, since we will either be returning the inner type or repadding it. If no size or alignment is specified, use that of the original padded type. */ if (TYPE_IS_PADDING_P (type)) { if ((!size || operand_equal_p (round_up (size, orig_align), orig_size, 0)) && (align == 0 || align == orig_align)) return type; if (!size) size = orig_size; if (align == 0) align = orig_align; type = TREE_TYPE (TYPE_FIELDS (type)); orig_size = TYPE_SIZE (type); orig_align = TYPE_ALIGN (type); } /* If the size is either not being changed or is being made smaller (which is not done here and is only valid for bitfields anyway), show the size isn't changing. Likewise, clear the alignment if it isn't being changed. Then return if we aren't doing anything. */ if (size && (operand_equal_p (size, orig_size, 0) || (TREE_CODE (orig_size) == INTEGER_CST && tree_int_cst_lt (size, orig_size)))) size = NULL_TREE; if (align == orig_align) align = 0; if (align == 0 && !size) return type; /* If requested, complete the original type and give it a name. */ if (is_user_type) create_type_decl (get_entity_name (gnat_entity), type, !Comes_From_Source (gnat_entity), !(TYPE_NAME (type) && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL && DECL_IGNORED_P (TYPE_NAME (type))), gnat_entity); /* We used to modify the record in place in some cases, but that could generate incorrect debugging information. So make a new record type and name. */ record = make_node (RECORD_TYPE); TYPE_PADDING_P (record) = 1; if (Present (gnat_entity)) TYPE_NAME (record) = create_concat_name (gnat_entity, "PAD"); TYPE_ALIGN (record) = align ? align : orig_align; TYPE_SIZE (record) = size ? size : orig_size; TYPE_SIZE_UNIT (record) = convert (sizetype, size_binop (CEIL_DIV_EXPR, TYPE_SIZE (record), bitsize_unit_node)); /* If we are changing the alignment and the input type is a record with BLKmode and a small constant size, try to make a form that has an integral mode. This might allow the padding record to also have an integral mode, which will be much more efficient. There is no point in doing so if a size is specified unless it is also a small constant size and it is incorrect to do so if we cannot guarantee that the mode will be naturally aligned since the field must always be addressable. ??? This might not always be a win when done for a stand-alone object: since the nominal and the effective type of the object will now have different modes, a VIEW_CONVERT_EXPR will be required for converting between them and it might be hard to overcome afterwards, including at the RTL level when the stand-alone object is accessed as a whole. */ if (align != 0 && RECORD_OR_UNION_TYPE_P (type) && TYPE_MODE (type) == BLKmode && !TYPE_BY_REFERENCE_P (type) && TREE_CODE (orig_size) == INTEGER_CST && !TREE_OVERFLOW (orig_size) && compare_tree_int (orig_size, MAX_FIXED_MODE_SIZE) <= 0 && (!size || (TREE_CODE (size) == INTEGER_CST && compare_tree_int (size, MAX_FIXED_MODE_SIZE) <= 0))) { tree packable_type = make_packable_type (type, true); if (TYPE_MODE (packable_type) != BLKmode && align >= TYPE_ALIGN (packable_type)) type = packable_type; } /* Now create the field with the original size. */ field = create_field_decl (get_identifier ("F"), type, record, orig_size, bitsize_zero_node, 0, 1); DECL_INTERNAL_P (field) = 1; /* Do not emit debug info until after the auxiliary record is built. */ finish_record_type (record, field, 1, false); /* Set the RM size if requested. */ if (set_rm_size) { tree canonical_pad_type; SET_TYPE_ADA_SIZE (record, size ? size : orig_size); /* If the padded type is complete and has constant size, we canonicalize it by means of the hash table. This is consistent with the language semantics and ensures that gigi and the middle-end have a common view of these padded types. */ if (TREE_CONSTANT (TYPE_SIZE (record)) && (canonical_pad_type = lookup_and_insert_pad_type (record))) { record = canonical_pad_type; goto built; } } /* Unless debugging information isn't being written for the input type, write a record that shows what we are a subtype of and also make a variable that indicates our size, if still variable. */ if (TREE_CODE (orig_size) != INTEGER_CST && TYPE_NAME (record) && TYPE_NAME (type) && !(TREE_CODE (TYPE_NAME (type)) == TYPE_DECL && DECL_IGNORED_P (TYPE_NAME (type)))) { tree name = TYPE_IDENTIFIER (record); tree size_unit = TYPE_SIZE_UNIT (record); /* A variable that holds the size is required even with no encoding since it will be referenced by debugging information attributes. At global level, we need a single variable across all translation units. */ if (size && TREE_CODE (size) != INTEGER_CST && (definition || global_bindings_p ())) { size_unit = create_var_decl (concat_name (name, "XVZ"), NULL_TREE, sizetype, size_unit, true, global_bindings_p (), !definition && global_bindings_p (), false, true, true, NULL, gnat_entity); TYPE_SIZE_UNIT (record) = size_unit; } tree marker = make_node (RECORD_TYPE); tree orig_name = TYPE_IDENTIFIER (type); TYPE_NAME (marker) = concat_name (name, "XVS"); finish_record_type (marker, create_field_decl (orig_name, build_reference_type (type), marker, NULL_TREE, NULL_TREE, 0, 0), 0, true); TYPE_SIZE_UNIT (marker) = size_unit; add_parallel_type (record, marker); } rest_of_record_type_compilation (record); built: /* If the size was widened explicitly, maybe give a warning. Take the original size as the maximum size of the input if there was an unconstrained record involved and round it up to the specified alignment, if one was specified. But don't do it if we are just annotating types and the type is tagged, since tagged types aren't fully laid out in this mode. */ if (!size || TREE_CODE (size) == COND_EXPR || TREE_CODE (size) == MAX_EXPR || No (gnat_entity) || (type_annotate_only && Is_Tagged_Type (Etype (gnat_entity)))) return record; if (CONTAINS_PLACEHOLDER_P (orig_size)) orig_size = max_size (orig_size, true); if (align && AGGREGATE_TYPE_P (type)) orig_size = round_up (orig_size, align); if (!operand_equal_p (size, orig_size, 0) && !(TREE_CODE (size) == INTEGER_CST && TREE_CODE (orig_size) == INTEGER_CST && (TREE_OVERFLOW (size) || TREE_OVERFLOW (orig_size) || tree_int_cst_lt (size, orig_size)))) { Node_Id gnat_error_node = Empty; /* For a packed array, post the message on the original array type. */ if (Is_Packed_Array_Impl_Type (gnat_entity)) gnat_entity = Original_Array_Type (gnat_entity); if ((Ekind (gnat_entity) == E_Component || Ekind (gnat_entity) == E_Discriminant) && Present (Component_Clause (gnat_entity))) gnat_error_node = Last_Bit (Component_Clause (gnat_entity)); else if (Present (Size_Clause (gnat_entity))) gnat_error_node = Expression (Size_Clause (gnat_entity)); /* Generate message only for entities that come from source, since if we have an entity created by expansion, the message will be generated for some other corresponding source entity. */ if (Comes_From_Source (gnat_entity)) { if (Present (gnat_error_node)) post_error_ne_tree ("{^ }bits of & unused?", gnat_error_node, gnat_entity, size_diffop (size, orig_size)); else if (is_component_type) post_error_ne_tree ("component of& padded{ by ^ bits}?", gnat_entity, gnat_entity, size_diffop (size, orig_size)); } } return record; } /* Return a copy of the padded TYPE but with reverse storage order. */ tree set_reverse_storage_order_on_pad_type (tree type) { tree field, canonical_pad_type; #ifdef ENABLE_CHECKING /* If the inner type is not scalar then the function does nothing. */ tree inner_type = TREE_TYPE (TYPE_FIELDS (type)); gcc_assert (!AGGREGATE_TYPE_P (inner_type) && !VECTOR_TYPE_P (inner_type)); #endif /* This is required for the canonicalization. */ gcc_assert (TREE_CONSTANT (TYPE_SIZE (type))); field = copy_node (TYPE_FIELDS (type)); type = copy_type (type); DECL_CONTEXT (field) = type; TYPE_FIELDS (type) = field; TYPE_REVERSE_STORAGE_ORDER (type) = 1; canonical_pad_type = lookup_and_insert_pad_type (type); return canonical_pad_type ? canonical_pad_type : type; } /* Relate the alias sets of GNU_NEW_TYPE and GNU_OLD_TYPE according to OP. If this is a multi-dimensional array type, do this recursively. OP may be - ALIAS_SET_COPY: the new set is made a copy of the old one. - ALIAS_SET_SUPERSET: the new set is made a superset of the old one. - ALIAS_SET_SUBSET: the new set is made a subset of the old one. */ void relate_alias_sets (tree gnu_new_type, tree gnu_old_type, enum alias_set_op op) { /* Remove any padding from GNU_OLD_TYPE. It doesn't matter in the case of a one-dimensional array, since the padding has the same alias set as the field type, but if it's a multi-dimensional array, we need to see the inner types. */ while (TREE_CODE (gnu_old_type) == RECORD_TYPE && (TYPE_JUSTIFIED_MODULAR_P (gnu_old_type) || TYPE_PADDING_P (gnu_old_type))) gnu_old_type = TREE_TYPE (TYPE_FIELDS (gnu_old_type)); /* Unconstrained array types are deemed incomplete and would thus be given alias set 0. Retrieve the underlying array type. */ if (TREE_CODE (gnu_old_type) == UNCONSTRAINED_ARRAY_TYPE) gnu_old_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_old_type)))); if (TREE_CODE (gnu_new_type) == UNCONSTRAINED_ARRAY_TYPE) gnu_new_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_new_type)))); if (TREE_CODE (gnu_new_type) == ARRAY_TYPE && TREE_CODE (TREE_TYPE (gnu_new_type)) == ARRAY_TYPE && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_new_type))) relate_alias_sets (TREE_TYPE (gnu_new_type), TREE_TYPE (gnu_old_type), op); switch (op) { case ALIAS_SET_COPY: /* The alias set shouldn't be copied between array types with different aliasing settings because this can break the aliasing relationship between the array type and its element type. */ if (flag_checking || flag_strict_aliasing) gcc_assert (!(TREE_CODE (gnu_new_type) == ARRAY_TYPE && TREE_CODE (gnu_old_type) == ARRAY_TYPE && TYPE_NONALIASED_COMPONENT (gnu_new_type) != TYPE_NONALIASED_COMPONENT (gnu_old_type))); TYPE_ALIAS_SET (gnu_new_type) = get_alias_set (gnu_old_type); break; case ALIAS_SET_SUBSET: case ALIAS_SET_SUPERSET: { alias_set_type old_set = get_alias_set (gnu_old_type); alias_set_type new_set = get_alias_set (gnu_new_type); /* Do nothing if the alias sets conflict. This ensures that we never call record_alias_subset several times for the same pair or at all for alias set 0. */ if (!alias_sets_conflict_p (old_set, new_set)) { if (op == ALIAS_SET_SUBSET) record_alias_subset (old_set, new_set); else record_alias_subset (new_set, old_set); } } break; default: gcc_unreachable (); } record_component_aliases (gnu_new_type); } /* Record TYPE as a builtin type for Ada. NAME is the name of the type. ARTIFICIAL_P is true if the type was generated by the compiler. */ void record_builtin_type (const char *name, tree type, bool artificial_p) { tree type_decl = build_decl (input_location, TYPE_DECL, get_identifier (name), type); DECL_ARTIFICIAL (type_decl) = artificial_p; TYPE_ARTIFICIAL (type) = artificial_p; gnat_pushdecl (type_decl, Empty); if (debug_hooks->type_decl) debug_hooks->type_decl (type_decl, false); } /* Given a record type RECORD_TYPE and a list of FIELD_DECL nodes FIELD_LIST, finish constructing the record type as a fat pointer type. */ void finish_fat_pointer_type (tree record_type, tree field_list) { /* Make sure we can put it into a register. */ if (STRICT_ALIGNMENT) TYPE_ALIGN (record_type) = MIN (BIGGEST_ALIGNMENT, 2 * POINTER_SIZE); /* Show what it really is. */ TYPE_FAT_POINTER_P (record_type) = 1; /* Do not emit debug info for it since the types of its fields may still be incomplete at this point. */ finish_record_type (record_type, field_list, 0, false); /* Force type_contains_placeholder_p to return true on it. Although the PLACEHOLDER_EXPRs are referenced only indirectly, this isn't a pointer type but the representation of the unconstrained array. */ TYPE_CONTAINS_PLACEHOLDER_INTERNAL (record_type) = 2; } /* Given a record type RECORD_TYPE and a list of FIELD_DECL nodes FIELD_LIST, finish constructing the record or union type. If REP_LEVEL is zero, this record has no representation clause and so will be entirely laid out here. If REP_LEVEL is one, this record has a representation clause and has been laid out already; only set the sizes and alignment. If REP_LEVEL is two, this record is derived from a parent record and thus inherits its layout; only make a pass on the fields to finalize them. DEBUG_INFO_P is true if we need to write debug information about this type. */ void finish_record_type (tree record_type, tree field_list, int rep_level, bool debug_info_p) { enum tree_code code = TREE_CODE (record_type); tree name = TYPE_IDENTIFIER (record_type); tree ada_size = bitsize_zero_node; tree size = bitsize_zero_node; bool had_size = TYPE_SIZE (record_type) != 0; bool had_size_unit = TYPE_SIZE_UNIT (record_type) != 0; bool had_align = TYPE_ALIGN (record_type) != 0; tree field; TYPE_FIELDS (record_type) = field_list; /* Always attach the TYPE_STUB_DECL for a record type. It is required to generate debug info and have a parallel type. */ TYPE_STUB_DECL (record_type) = create_type_stub_decl (name, record_type); /* Globally initialize the record first. If this is a rep'ed record, that just means some initializations; otherwise, layout the record. */ if (rep_level > 0) { TYPE_ALIGN (record_type) = MAX (BITS_PER_UNIT, TYPE_ALIGN (record_type)); if (!had_size_unit) TYPE_SIZE_UNIT (record_type) = size_zero_node; if (!had_size) TYPE_SIZE (record_type) = bitsize_zero_node; /* For all-repped records with a size specified, lay the QUAL_UNION_TYPE out just like a UNION_TYPE, since the size will be fixed. */ else if (code == QUAL_UNION_TYPE) code = UNION_TYPE; } else { /* Ensure there isn't a size already set. There can be in an error case where there is a rep clause but all fields have errors and no longer have a position. */ TYPE_SIZE (record_type) = 0; /* Ensure we use the traditional GCC layout for bitfields when we need to pack the record type or have a representation clause. The other possible layout (Microsoft C compiler), if available, would prevent efficient packing in almost all cases. */ #ifdef TARGET_MS_BITFIELD_LAYOUT if (TARGET_MS_BITFIELD_LAYOUT && TYPE_PACKED (record_type)) decl_attributes (&record_type, tree_cons (get_identifier ("gcc_struct"), NULL_TREE, NULL_TREE), ATTR_FLAG_TYPE_IN_PLACE); #endif layout_type (record_type); } /* At this point, the position and size of each field is known. It was either set before entry by a rep clause, or by laying out the type above. We now run a pass over the fields (in reverse order for QUAL_UNION_TYPEs) to compute the Ada size; the GCC size and alignment (for rep'ed records that are not padding types); and the mode (for rep'ed records). We also clear the DECL_BIT_FIELD indication for the cases we know have not been handled yet, and adjust DECL_NONADDRESSABLE_P accordingly. */ if (code == QUAL_UNION_TYPE) field_list = nreverse (field_list); for (field = field_list; field; field = DECL_CHAIN (field)) { tree type = TREE_TYPE (field); tree pos = bit_position (field); tree this_size = DECL_SIZE (field); tree this_ada_size; if (RECORD_OR_UNION_TYPE_P (type) && !TYPE_FAT_POINTER_P (type) && !TYPE_CONTAINS_TEMPLATE_P (type) && TYPE_ADA_SIZE (type)) this_ada_size = TYPE_ADA_SIZE (type); else this_ada_size = this_size; /* Clear DECL_BIT_FIELD for the cases layout_decl does not handle. */ if (DECL_BIT_FIELD (field) && operand_equal_p (this_size, TYPE_SIZE (type), 0)) { unsigned int align = TYPE_ALIGN (type); /* In the general case, type alignment is required. */ if (value_factor_p (pos, align)) { /* The enclosing record type must be sufficiently aligned. Otherwise, if no alignment was specified for it and it has been laid out already, bump its alignment to the desired one if this is compatible with its size. */ if (TYPE_ALIGN (record_type) >= align) { DECL_ALIGN (field) = MAX (DECL_ALIGN (field), align); DECL_BIT_FIELD (field) = 0; } else if (!had_align && rep_level == 0 && value_factor_p (TYPE_SIZE (record_type), align)) { TYPE_ALIGN (record_type) = align; DECL_ALIGN (field) = MAX (DECL_ALIGN (field), align); DECL_BIT_FIELD (field) = 0; } } /* In the non-strict alignment case, only byte alignment is. */ if (!STRICT_ALIGNMENT && DECL_BIT_FIELD (field) && value_factor_p (pos, BITS_PER_UNIT)) DECL_BIT_FIELD (field) = 0; } /* If we still have DECL_BIT_FIELD set at this point, we know that the field is technically not addressable. Except that it can actually be addressed if it is BLKmode and happens to be properly aligned. */ if (DECL_BIT_FIELD (field) && !(DECL_MODE (field) == BLKmode && value_factor_p (pos, BITS_PER_UNIT))) DECL_NONADDRESSABLE_P (field) = 1; /* A type must be as aligned as its most aligned field that is not a bit-field. But this is already enforced by layout_type. */ if (rep_level > 0 && !DECL_BIT_FIELD (field)) TYPE_ALIGN (record_type) = MAX (TYPE_ALIGN (record_type), DECL_ALIGN (field)); switch (code) { case UNION_TYPE: ada_size = size_binop (MAX_EXPR, ada_size, this_ada_size); size = size_binop (MAX_EXPR, size, this_size); break; case QUAL_UNION_TYPE: ada_size = fold_build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field), this_ada_size, ada_size); size = fold_build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field), this_size, size); break; case RECORD_TYPE: /* Since we know here that all fields are sorted in order of increasing bit position, the size of the record is one higher than the ending bit of the last field processed unless we have a rep clause, since in that case we might have a field outside a QUAL_UNION_TYPE that has a higher ending position. So use a MAX in that case. Also, if this field is a QUAL_UNION_TYPE, we need to take into account the previous size in the case of empty variants. */ ada_size = merge_sizes (ada_size, pos, this_ada_size, TREE_CODE (type) == QUAL_UNION_TYPE, rep_level > 0); size = merge_sizes (size, pos, this_size, TREE_CODE (type) == QUAL_UNION_TYPE, rep_level > 0); break; default: gcc_unreachable (); } } if (code == QUAL_UNION_TYPE) nreverse (field_list); if (rep_level < 2) { /* If this is a padding record, we never want to make the size smaller than what was specified in it, if any. */ if (TYPE_IS_PADDING_P (record_type) && TYPE_SIZE (record_type)) size = TYPE_SIZE (record_type); /* Now set any of the values we've just computed that apply. */ if (!TYPE_FAT_POINTER_P (record_type) && !TYPE_CONTAINS_TEMPLATE_P (record_type)) SET_TYPE_ADA_SIZE (record_type, ada_size); if (rep_level > 0) { tree size_unit = had_size_unit ? TYPE_SIZE_UNIT (record_type) : convert (sizetype, size_binop (CEIL_DIV_EXPR, size, bitsize_unit_node)); unsigned int align = TYPE_ALIGN (record_type); TYPE_SIZE (record_type) = variable_size (round_up (size, align)); TYPE_SIZE_UNIT (record_type) = variable_size (round_up (size_unit, align / BITS_PER_UNIT)); compute_record_mode (record_type); } } if (debug_info_p) rest_of_record_type_compilation (record_type); } /* Append PARALLEL_TYPE on the chain of parallel types of TYPE. If PARRALEL_TYPE has no context and its computation is not deferred yet, also propagate TYPE's context to PARALLEL_TYPE's or defer its propagation to the moment TYPE will get a context. */ void add_parallel_type (tree type, tree parallel_type) { tree decl = TYPE_STUB_DECL (type); while (DECL_PARALLEL_TYPE (decl)) decl = TYPE_STUB_DECL (DECL_PARALLEL_TYPE (decl)); SET_DECL_PARALLEL_TYPE (decl, parallel_type); /* If PARALLEL_TYPE already has a context, we are done. */ if (TYPE_CONTEXT (parallel_type) != NULL_TREE) return; /* Otherwise, try to get one from TYPE's context. */ if (TYPE_CONTEXT (type) != NULL_TREE) /* TYPE already has a context, so simply propagate it to PARALLEL_TYPE. */ gnat_set_type_context (parallel_type, TYPE_CONTEXT (type)); /* ... otherwise TYPE has not context yet. We know it will thanks to gnat_pushdecl, and then its context will be propagated to PARALLEL_TYPE. So we have nothing to do in this case. */ } /* Return true if TYPE has a parallel type. */ static bool has_parallel_type (tree type) { tree decl = TYPE_STUB_DECL (type); return DECL_PARALLEL_TYPE (decl) != NULL_TREE; } /* Wrap up compilation of RECORD_TYPE, i.e. output all the debug information associated with it. It need not be invoked directly in most cases since finish_record_type takes care of doing so, but this can be necessary if a parallel type is to be attached to the record type. */ void rest_of_record_type_compilation (tree record_type) { bool var_size = false; tree field; /* If this is a padded type, the bulk of the debug info has already been generated for the field's type. */ if (TYPE_IS_PADDING_P (record_type)) return; /* If the type already has a parallel type (XVS type), then we're done. */ if (has_parallel_type (record_type)) return; for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field)) { /* We need to make an XVE/XVU record if any field has variable size, whether or not the record does. For example, if we have a union, it may be that all fields, rounded up to the alignment, have the same size, in which case we'll use that size. But the debug output routines (except Dwarf2) won't be able to output the fields, so we need to make the special record. */ if (TREE_CODE (DECL_SIZE (field)) != INTEGER_CST /* If a field has a non-constant qualifier, the record will have variable size too. */ || (TREE_CODE (record_type) == QUAL_UNION_TYPE && TREE_CODE (DECL_QUALIFIER (field)) != INTEGER_CST)) { var_size = true; break; } } /* If this record type is of variable size, make a parallel record type that will tell the debugger how the former is laid out (see exp_dbug.ads). */ if (var_size) { tree new_record_type = make_node (TREE_CODE (record_type) == QUAL_UNION_TYPE ? UNION_TYPE : TREE_CODE (record_type)); tree orig_name = TYPE_IDENTIFIER (record_type), new_name; tree last_pos = bitsize_zero_node; tree old_field, prev_old_field = NULL_TREE; new_name = concat_name (orig_name, TREE_CODE (record_type) == QUAL_UNION_TYPE ? "XVU" : "XVE"); TYPE_NAME (new_record_type) = new_name; TYPE_ALIGN (new_record_type) = BIGGEST_ALIGNMENT; TYPE_STUB_DECL (new_record_type) = create_type_stub_decl (new_name, new_record_type); DECL_IGNORED_P (TYPE_STUB_DECL (new_record_type)) = DECL_IGNORED_P (TYPE_STUB_DECL (record_type)); TYPE_SIZE (new_record_type) = size_int (TYPE_ALIGN (record_type)); TYPE_SIZE_UNIT (new_record_type) = size_int (TYPE_ALIGN (record_type) / BITS_PER_UNIT); /* Now scan all the fields, replacing each field with a new field corresponding to the new encoding. */ for (old_field = TYPE_FIELDS (record_type); old_field; old_field = DECL_CHAIN (old_field)) { tree field_type = TREE_TYPE (old_field); tree field_name = DECL_NAME (old_field); tree curpos = bit_position (old_field); tree pos, new_field; bool var = false; unsigned int align = 0; /* We're going to do some pattern matching below so remove as many conversions as possible. */ curpos = remove_conversions (curpos, true); /* See how the position was modified from the last position. There are two basic cases we support: a value was added to the last position or the last position was rounded to a boundary and they something was added. Check for the first case first. If not, see if there is any evidence of rounding. If so, round the last position and retry. If this is a union, the position can be taken as zero. */ if (TREE_CODE (new_record_type) == UNION_TYPE) pos = bitsize_zero_node; else pos = compute_related_constant (curpos, last_pos); if (!pos && TREE_CODE (curpos) == MULT_EXPR && tree_fits_uhwi_p (TREE_OPERAND (curpos, 1))) { tree offset = TREE_OPERAND (curpos, 0); align = tree_to_uhwi (TREE_OPERAND (curpos, 1)); align = scale_by_factor_of (offset, align); last_pos = round_up (last_pos, align); pos = compute_related_constant (curpos, last_pos); } else if (!pos && TREE_CODE (curpos) == PLUS_EXPR && tree_fits_uhwi_p (TREE_OPERAND (curpos, 1)) && TREE_CODE (TREE_OPERAND (curpos, 0)) == MULT_EXPR && tree_fits_uhwi_p (TREE_OPERAND (TREE_OPERAND (curpos, 0), 1))) { tree offset = TREE_OPERAND (TREE_OPERAND (curpos, 0), 0); unsigned HOST_WIDE_INT addend = tree_to_uhwi (TREE_OPERAND (curpos, 1)); align = tree_to_uhwi (TREE_OPERAND (TREE_OPERAND (curpos, 0), 1)); align = scale_by_factor_of (offset, align); align = MIN (align, addend & -addend); last_pos = round_up (last_pos, align); pos = compute_related_constant (curpos, last_pos); } else if (potential_alignment_gap (prev_old_field, old_field, pos)) { align = TYPE_ALIGN (field_type); last_pos = round_up (last_pos, align); pos = compute_related_constant (curpos, last_pos); } /* If we can't compute a position, set it to zero. ??? We really should abort here, but it's too much work to get this correct for all cases. */ if (!pos) pos = bitsize_zero_node; /* See if this type is variable-sized and make a pointer type and indicate the indirection if so. Beware that the debug back-end may adjust the position computed above according to the alignment of the field type, i.e. the pointer type in this case, if we don't preventively counter that. */ if (TREE_CODE (DECL_SIZE (old_field)) != INTEGER_CST) { field_type = build_pointer_type (field_type); if (align != 0 && TYPE_ALIGN (field_type) > align) { field_type = copy_node (field_type); TYPE_ALIGN (field_type) = align; } var = true; } /* Make a new field name, if necessary. */ if (var || align != 0) { char suffix[16]; if (align != 0) sprintf (suffix, "XV%c%u", var ? 'L' : 'A', align / BITS_PER_UNIT); else strcpy (suffix, "XVL"); field_name = concat_name (field_name, suffix); } new_field = create_field_decl (field_name, field_type, new_record_type, DECL_SIZE (old_field), pos, 0, 0); DECL_CHAIN (new_field) = TYPE_FIELDS (new_record_type); TYPE_FIELDS (new_record_type) = new_field; /* If old_field is a QUAL_UNION_TYPE, take its size as being zero. The only time it's not the last field of the record is when there are other components at fixed positions after it (meaning there was a rep clause for every field) and we want to be able to encode them. */ last_pos = size_binop (PLUS_EXPR, bit_position (old_field), (TREE_CODE (TREE_TYPE (old_field)) == QUAL_UNION_TYPE) ? bitsize_zero_node : DECL_SIZE (old_field)); prev_old_field = old_field; } TYPE_FIELDS (new_record_type) = nreverse (TYPE_FIELDS (new_record_type)); add_parallel_type (record_type, new_record_type); } } /* Utility function of above to merge LAST_SIZE, the previous size of a record with FIRST_BIT and SIZE that describe a field. SPECIAL is true if this represents a QUAL_UNION_TYPE in which case we must look for COND_EXPRs and replace a value of zero with the old size. If HAS_REP is true, we take the MAX of the end position of this field with LAST_SIZE. In all other cases, we use FIRST_BIT plus SIZE. Return an expression for the size. */ static tree merge_sizes (tree last_size, tree first_bit, tree size, bool special, bool has_rep) { tree type = TREE_TYPE (last_size); tree new_size; if (!special || TREE_CODE (size) != COND_EXPR) { new_size = size_binop (PLUS_EXPR, first_bit, size); if (has_rep) new_size = size_binop (MAX_EXPR, last_size, new_size); } else new_size = fold_build3 (COND_EXPR, type, TREE_OPERAND (size, 0), integer_zerop (TREE_OPERAND (size, 1)) ? last_size : merge_sizes (last_size, first_bit, TREE_OPERAND (size, 1), 1, has_rep), integer_zerop (TREE_OPERAND (size, 2)) ? last_size : merge_sizes (last_size, first_bit, TREE_OPERAND (size, 2), 1, has_rep)); /* We don't need any NON_VALUE_EXPRs and they can confuse us (especially when fed through substitute_in_expr) into thinking that a constant size is not constant. */ while (TREE_CODE (new_size) == NON_LVALUE_EXPR) new_size = TREE_OPERAND (new_size, 0); return new_size; } /* Utility function of above to see if OP0 and OP1, both of SIZETYPE, are related by the addition of a constant. Return that constant if so. */ static tree compute_related_constant (tree op0, tree op1) { tree op0_var, op1_var; tree op0_con = split_plus (op0, &op0_var); tree op1_con = split_plus (op1, &op1_var); tree result = size_binop (MINUS_EXPR, op0_con, op1_con); if (operand_equal_p (op0_var, op1_var, 0)) return result; else if (operand_equal_p (op0, size_binop (PLUS_EXPR, op1_var, result), 0)) return result; else return 0; } /* Utility function of above to split a tree OP which may be a sum, into a constant part, which is returned, and a variable part, which is stored in *PVAR. *PVAR may be bitsize_zero_node. All operations must be of bitsizetype. */ static tree split_plus (tree in, tree *pvar) { /* Strip conversions in order to ease the tree traversal and maximize the potential for constant or plus/minus discovery. We need to be careful to always return and set *pvar to bitsizetype trees, but it's worth the effort. */ in = remove_conversions (in, false); *pvar = convert (bitsizetype, in); if (TREE_CODE (in) == INTEGER_CST) { *pvar = bitsize_zero_node; return convert (bitsizetype, in); } else if (TREE_CODE (in) == PLUS_EXPR || TREE_CODE (in) == MINUS_EXPR) { tree lhs_var, rhs_var; tree lhs_con = split_plus (TREE_OPERAND (in, 0), &lhs_var); tree rhs_con = split_plus (TREE_OPERAND (in, 1), &rhs_var); if (lhs_var == TREE_OPERAND (in, 0) && rhs_var == TREE_OPERAND (in, 1)) return bitsize_zero_node; *pvar = size_binop (TREE_CODE (in), lhs_var, rhs_var); return size_binop (TREE_CODE (in), lhs_con, rhs_con); } else return bitsize_zero_node; } /* Return a FUNCTION_TYPE node. RETURN_TYPE is the type returned by the subprogram. If it is VOID_TYPE, then we are dealing with a procedure, otherwise we are dealing with a function. PARAM_DECL_LIST is a list of PARM_DECL nodes that are the subprogram parameters. CICO_LIST is the copy-in/copy-out list to be stored into the TYPE_CICO_LIST field. RETURN_UNCONSTRAINED_P is true if the function returns an unconstrained object. RETURN_BY_DIRECT_REF_P is true if the function returns by direct reference. RETURN_BY_INVISI_REF_P is true if the function returns by invisible reference. */ tree create_subprog_type (tree return_type, tree param_decl_list, tree cico_list, bool return_unconstrained_p, bool return_by_direct_ref_p, bool return_by_invisi_ref_p) { /* A list of the data type nodes of the subprogram formal parameters. This list is generated by traversing the input list of PARM_DECL nodes. */ vec<tree, va_gc> *param_type_list = NULL; tree t, type; for (t = param_decl_list; t; t = DECL_CHAIN (t)) vec_safe_push (param_type_list, TREE_TYPE (t)); type = build_function_type_vec (return_type, param_type_list); /* TYPE may have been shared since GCC hashes types. If it has a different CICO_LIST, make a copy. Likewise for the various flags. */ if (!fntype_same_flags_p (type, cico_list, return_unconstrained_p, return_by_direct_ref_p, return_by_invisi_ref_p)) { type = copy_type (type); TYPE_CI_CO_LIST (type) = cico_list; TYPE_RETURN_UNCONSTRAINED_P (type) = return_unconstrained_p; TYPE_RETURN_BY_DIRECT_REF_P (type) = return_by_direct_ref_p; TREE_ADDRESSABLE (type) = return_by_invisi_ref_p; } return type; } /* Return a copy of TYPE but safe to modify in any way. */ tree copy_type (tree type) { tree new_type = copy_node (type); /* Unshare the language-specific data. */ if (TYPE_LANG_SPECIFIC (type)) { TYPE_LANG_SPECIFIC (new_type) = NULL; SET_TYPE_LANG_SPECIFIC (new_type, GET_TYPE_LANG_SPECIFIC (type)); } /* And the contents of the language-specific slot if needed. */ if ((INTEGRAL_TYPE_P (type) || TREE_CODE (type) == REAL_TYPE) && TYPE_RM_VALUES (type)) { TYPE_RM_VALUES (new_type) = NULL_TREE; SET_TYPE_RM_SIZE (new_type, TYPE_RM_SIZE (type)); SET_TYPE_RM_MIN_VALUE (new_type, TYPE_RM_MIN_VALUE (type)); SET_TYPE_RM_MAX_VALUE (new_type, TYPE_RM_MAX_VALUE (type)); } /* copy_node clears this field instead of copying it, because it is aliased with TREE_CHAIN. */ TYPE_STUB_DECL (new_type) = TYPE_STUB_DECL (type); TYPE_POINTER_TO (new_type) = 0; TYPE_REFERENCE_TO (new_type) = 0; TYPE_MAIN_VARIANT (new_type) = new_type; TYPE_NEXT_VARIANT (new_type) = 0; TYPE_CANONICAL (new_type) = new_type; return new_type; } /* Return a subtype of sizetype with range MIN to MAX and whose TYPE_INDEX_TYPE is INDEX. GNAT_NODE is used for the position of the associated TYPE_DECL. */ tree create_index_type (tree min, tree max, tree index, Node_Id gnat_node) { /* First build a type for the desired range. */ tree type = build_nonshared_range_type (sizetype, min, max); /* Then set the index type. */ SET_TYPE_INDEX_TYPE (type, index); create_type_decl (NULL_TREE, type, true, false, gnat_node); return type; } /* Return a subtype of TYPE with range MIN to MAX. If TYPE is NULL, sizetype is used. */ tree create_range_type (tree type, tree min, tree max) { tree range_type; if (type == NULL_TREE) type = sizetype; /* First build a type with the base range. */ range_type = build_nonshared_range_type (type, TYPE_MIN_VALUE (type), TYPE_MAX_VALUE (type)); /* Then set the actual range. */ SET_TYPE_RM_MIN_VALUE (range_type, min); SET_TYPE_RM_MAX_VALUE (range_type, max); return range_type; } /* Return a TYPE_DECL node suitable for the TYPE_STUB_DECL field of TYPE. NAME gives the name of the type to be used in the declaration. */ tree create_type_stub_decl (tree name, tree type) { tree type_decl = build_decl (input_location, TYPE_DECL, name, type); DECL_ARTIFICIAL (type_decl) = 1; TYPE_ARTIFICIAL (type) = 1; return type_decl; } /* Return a TYPE_DECL node for TYPE. NAME gives the name of the type to be used in the declaration. ARTIFICIAL_P is true if the declaration was generated by the compiler. DEBUG_INFO_P is true if we need to write debug information about this type. GNAT_NODE is used for the position of the decl. */ tree create_type_decl (tree name, tree type, bool artificial_p, bool debug_info_p, Node_Id gnat_node) { enum tree_code code = TREE_CODE (type); bool is_named = TYPE_NAME (type) && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL; tree type_decl; /* Only the builtin TYPE_STUB_DECL should be used for dummy types. */ gcc_assert (!TYPE_IS_DUMMY_P (type)); /* If the type hasn't been named yet, we're naming it; preserve an existing TYPE_STUB_DECL that has been attached to it for some purpose. */ if (!is_named && TYPE_STUB_DECL (type)) { type_decl = TYPE_STUB_DECL (type); DECL_NAME (type_decl) = name; } else type_decl = build_decl (input_location, TYPE_DECL, name, type); DECL_ARTIFICIAL (type_decl) = artificial_p; TYPE_ARTIFICIAL (type) = artificial_p; /* Add this decl to the current binding level. */ gnat_pushdecl (type_decl, gnat_node); /* If we're naming the type, equate the TYPE_STUB_DECL to the name. This causes the name to be also viewed as a "tag" by the debug back-end, with the advantage that no DW_TAG_typedef is emitted for artificial "tagged" types in DWARF. Note that if "type" is used as a DECL_ORIGINAL_TYPE, it may be referenced from multiple contexts, and "type_decl" references a copy of it: in such a case, do not mess TYPE_STUB_DECL: we do not want to re-use the TYPE_DECL with the mechanism above. */ if (!is_named && type != DECL_ORIGINAL_TYPE (type_decl)) TYPE_STUB_DECL (type) = type_decl; /* Do not generate debug info for UNCONSTRAINED_ARRAY_TYPE that the back-end doesn't support, and for others if we don't need to. */ if (code == UNCONSTRAINED_ARRAY_TYPE || !debug_info_p) DECL_IGNORED_P (type_decl) = 1; return type_decl; } /* Return a VAR_DECL or CONST_DECL node. NAME gives the name of the variable. ASM_NAME is its assembler name (if provided). TYPE is its data type (a GCC ..._TYPE node). INIT is the GCC tree for an optional initial expression; NULL_TREE if none. CONST_FLAG is true if this variable is constant, in which case we might return a CONST_DECL node unless CONST_DECL_ALLOWED_P is false. PUBLIC_FLAG is true if this is for a reference to a public entity or for a definition to be made visible outside of the current compilation unit, for instance variable definitions in a package specification. EXTERN_FLAG is true when processing an external variable declaration (as opposed to a definition: no storage is to be allocated for the variable). STATIC_FLAG is only relevant when not at top level. In that case it indicates whether to always allocate storage to the variable. ARTIFICIAL_P is true if the variable was generated by the compiler. DEBUG_INFO_P is true if we need to write debug information for it. GNAT_NODE is used for the position of the decl. */ tree create_var_decl (tree name, tree asm_name, tree type, tree init, bool const_flag, bool public_flag, bool extern_flag, bool static_flag, bool artificial_p, bool debug_info_p, struct attrib *attr_list, Node_Id gnat_node, bool const_decl_allowed_p) { /* Whether the object has static storage duration, either explicitly or by virtue of being declared at the global level. */ const bool static_storage = static_flag || global_bindings_p (); /* Whether the initializer is constant: for an external object or an object with static storage duration, we check that the initializer is a valid constant expression for initializing a static variable; otherwise, we only check that it is constant. */ const bool init_const = (init && gnat_types_compatible_p (type, TREE_TYPE (init)) && (extern_flag || static_storage ? initializer_constant_valid_p (init, TREE_TYPE (init)) != NULL_TREE : TREE_CONSTANT (init))); /* Whether we will make TREE_CONSTANT the DECL we produce here, in which case the initializer may be used in lieu of the DECL node (as done in Identifier_to_gnu). This is useful to prevent the need of elaboration code when an identifier for which such a DECL is made is in turn used as an initializer. We used to rely on CONST_DECL vs VAR_DECL for this, but extra constraints apply to this choice (see below) and they are not relevant to the distinction we wish to make. */ const bool constant_p = const_flag && init_const; /* The actual DECL node. CONST_DECL was initially intended for enumerals and may be used for scalars in general but not for aggregates. */ tree var_decl = build_decl (input_location, (constant_p && const_decl_allowed_p && !AGGREGATE_TYPE_P (type)) ? CONST_DECL : VAR_DECL, name, type); /* If this is external, throw away any initializations (they will be done elsewhere) unless this is a constant for which we would like to remain able to get the initializer. If we are defining a global here, leave a constant initialization and save any variable elaborations for the elaboration routine. If we are just annotating types, throw away the initialization if it isn't a constant. */ if ((extern_flag && !constant_p) || (type_annotate_only && init && !TREE_CONSTANT (init))) init = NULL_TREE; /* At the global level, a non-constant initializer generates elaboration statements. Check that such statements are allowed, that is to say, not violating a No_Elaboration_Code restriction. */ if (init && !init_const && global_bindings_p ()) Check_Elaboration_Code_Allowed (gnat_node); /* Attach the initializer, if any. */ DECL_INITIAL (var_decl) = init; /* Directly set some flags. */ DECL_ARTIFICIAL (var_decl) = artificial_p; DECL_EXTERNAL (var_decl) = extern_flag; TREE_CONSTANT (var_decl) = constant_p; TREE_READONLY (var_decl) = const_flag; /* We need to allocate static storage for an object with static storage duration if it isn't external. */ TREE_STATIC (var_decl) = !extern_flag && static_storage; /* The object is public if it is external or if it is declared public and has static storage duration. */ TREE_PUBLIC (var_decl) = extern_flag || (public_flag && static_storage); /* Ada doesn't feature Fortran-like COMMON variables so we shouldn't try to fiddle with DECL_COMMON. However, on platforms that don't support global BSS sections, uninitialized global variables would go in DATA instead, thus increasing the size of the executable. */ if (!flag_no_common && TREE_CODE (var_decl) == VAR_DECL && TREE_PUBLIC (var_decl) && !have_global_bss_p ()) DECL_COMMON (var_decl) = 1; /* Do not emit debug info for a CONST_DECL if optimization isn't enabled, since we will create an associated variable. Likewise for an external constant whose initializer is not absolute, because this would mean a global relocation in a read-only section which runs afoul of the PE-COFF run-time relocation mechanism. */ if (!debug_info_p || (TREE_CODE (var_decl) == CONST_DECL && !optimize) || (extern_flag && constant_p && init && initializer_constant_valid_p (init, TREE_TYPE (init)) != null_pointer_node)) DECL_IGNORED_P (var_decl) = 1; if (TYPE_VOLATILE (type)) TREE_SIDE_EFFECTS (var_decl) = TREE_THIS_VOLATILE (var_decl) = 1; if (TREE_SIDE_EFFECTS (var_decl)) TREE_ADDRESSABLE (var_decl) = 1; /* ??? Some attributes cannot be applied to CONST_DECLs. */ if (TREE_CODE (var_decl) == VAR_DECL) process_attributes (&var_decl, &attr_list, true, gnat_node); /* Add this decl to the current binding level. */ gnat_pushdecl (var_decl, gnat_node); if (TREE_CODE (var_decl) == VAR_DECL && asm_name) { /* Let the target mangle the name if this isn't a verbatim asm. */ if (*IDENTIFIER_POINTER (asm_name) != '*') asm_name = targetm.mangle_decl_assembler_name (var_decl, asm_name); SET_DECL_ASSEMBLER_NAME (var_decl, asm_name); } return var_decl; } /* Return true if TYPE, an aggregate type, contains (or is) an array. */ static bool aggregate_type_contains_array_p (tree type) { switch (TREE_CODE (type)) { case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: { tree field; for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field)) if (AGGREGATE_TYPE_P (TREE_TYPE (field)) && aggregate_type_contains_array_p (TREE_TYPE (field))) return true; return false; } case ARRAY_TYPE: return true; default: gcc_unreachable (); } } /* Return a FIELD_DECL node. NAME is the field's name, TYPE is its type and RECORD_TYPE is the type of the enclosing record. If SIZE is nonzero, it is the specified size of the field. If POS is nonzero, it is the bit position. PACKED is 1 if the enclosing record is packed, -1 if it has Component_Alignment of Storage_Unit. If ADDRESSABLE is nonzero, it means we are allowed to take the address of the field; if it is negative, we should not make a bitfield, which is used by make_aligning_type. */ tree create_field_decl (tree name, tree type, tree record_type, tree size, tree pos, int packed, int addressable) { tree field_decl = build_decl (input_location, FIELD_DECL, name, type); DECL_CONTEXT (field_decl) = record_type; TREE_READONLY (field_decl) = TYPE_READONLY (type); /* If FIELD_TYPE is BLKmode, we must ensure this is aligned to at least a byte boundary since GCC cannot handle less-aligned BLKmode bitfields. Likewise for an aggregate without specified position that contains an array, because in this case slices of variable length of this array must be handled by GCC and variable-sized objects need to be aligned to at least a byte boundary. */ if (packed && (TYPE_MODE (type) == BLKmode || (!pos && AGGREGATE_TYPE_P (type) && aggregate_type_contains_array_p (type)))) DECL_ALIGN (field_decl) = BITS_PER_UNIT; /* If a size is specified, use it. Otherwise, if the record type is packed compute a size to use, which may differ from the object's natural size. We always set a size in this case to trigger the checks for bitfield creation below, which is typically required when no position has been specified. */ if (size) size = convert (bitsizetype, size); else if (packed == 1) { size = rm_size (type); if (TYPE_MODE (type) == BLKmode) size = round_up (size, BITS_PER_UNIT); } /* If we may, according to ADDRESSABLE, make a bitfield if a size is specified for two reasons: first if the size differs from the natural size. Second, if the alignment is insufficient. There are a number of ways the latter can be true. We never make a bitfield if the type of the field has a nonconstant size, because no such entity requiring bitfield operations should reach here. We do *preventively* make a bitfield when there might be the need for it but we don't have all the necessary information to decide, as is the case of a field with no specified position in a packed record. We also don't look at STRICT_ALIGNMENT here, and rely on later processing in layout_decl or finish_record_type to clear the bit_field indication if it is in fact not needed. */ if (addressable >= 0 && size && TREE_CODE (size) == INTEGER_CST && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST && (!tree_int_cst_equal (size, TYPE_SIZE (type)) || (pos && !value_factor_p (pos, TYPE_ALIGN (type))) || packed || (TYPE_ALIGN (record_type) != 0 && TYPE_ALIGN (record_type) < TYPE_ALIGN (type)))) { DECL_BIT_FIELD (field_decl) = 1; DECL_SIZE (field_decl) = size; if (!packed && !pos) { if (TYPE_ALIGN (record_type) != 0 && TYPE_ALIGN (record_type) < TYPE_ALIGN (type)) DECL_ALIGN (field_decl) = TYPE_ALIGN (record_type); else DECL_ALIGN (field_decl) = TYPE_ALIGN (type); } } DECL_PACKED (field_decl) = pos ? DECL_BIT_FIELD (field_decl) : packed; /* Bump the alignment if need be, either for bitfield/packing purposes or to satisfy the type requirements if no such consideration applies. When we get the alignment from the type, indicate if this is from an explicit user request, which prevents stor-layout from lowering it later on. */ { unsigned int bit_align = (DECL_BIT_FIELD (field_decl) ? 1 : packed && TYPE_MODE (type) != BLKmode ? BITS_PER_UNIT : 0); if (bit_align > DECL_ALIGN (field_decl)) DECL_ALIGN (field_decl) = bit_align; else if (!bit_align && TYPE_ALIGN (type) > DECL_ALIGN (field_decl)) { DECL_ALIGN (field_decl) = TYPE_ALIGN (type); DECL_USER_ALIGN (field_decl) = TYPE_USER_ALIGN (type); } } if (pos) { /* We need to pass in the alignment the DECL is known to have. This is the lowest-order bit set in POS, but no more than the alignment of the record, if one is specified. Note that an alignment of 0 is taken as infinite. */ unsigned int known_align; if (tree_fits_uhwi_p (pos)) known_align = tree_to_uhwi (pos) & - tree_to_uhwi (pos); else known_align = BITS_PER_UNIT; if (TYPE_ALIGN (record_type) && (known_align == 0 || known_align > TYPE_ALIGN (record_type))) known_align = TYPE_ALIGN (record_type); layout_decl (field_decl, known_align); SET_DECL_OFFSET_ALIGN (field_decl, tree_fits_uhwi_p (pos) ? BIGGEST_ALIGNMENT : BITS_PER_UNIT); pos_from_bit (&DECL_FIELD_OFFSET (field_decl), &DECL_FIELD_BIT_OFFSET (field_decl), DECL_OFFSET_ALIGN (field_decl), pos); } /* In addition to what our caller says, claim the field is addressable if we know that its type is not suitable. The field may also be "technically" nonaddressable, meaning that even if we attempt to take the field's address we will actually get the address of a copy. This is the case for true bitfields, but the DECL_BIT_FIELD value we have at this point is not accurate enough, so we don't account for this here and let finish_record_type decide. */ if (!addressable && !type_for_nonaliased_component_p (type)) addressable = 1; DECL_NONADDRESSABLE_P (field_decl) = !addressable; return field_decl; } /* Return a PARM_DECL node. NAME is the name of the parameter and TYPE is its type. READONLY is true if the parameter is readonly (either an In parameter or an address of a pass-by-ref parameter). */ tree create_param_decl (tree name, tree type, bool readonly) { tree param_decl = build_decl (input_location, PARM_DECL, name, type); /* Honor TARGET_PROMOTE_PROTOTYPES like the C compiler, as not doing so can lead to various ABI violations. */ if (targetm.calls.promote_prototypes (NULL_TREE) && INTEGRAL_TYPE_P (type) && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node)) { /* We have to be careful about biased types here. Make a subtype of integer_type_node with the proper biasing. */ if (TREE_CODE (type) == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (type)) { tree subtype = make_unsigned_type (TYPE_PRECISION (integer_type_node)); TREE_TYPE (subtype) = integer_type_node; TYPE_BIASED_REPRESENTATION_P (subtype) = 1; SET_TYPE_RM_MIN_VALUE (subtype, TYPE_MIN_VALUE (type)); SET_TYPE_RM_MAX_VALUE (subtype, TYPE_MAX_VALUE (type)); type = subtype; } else type = integer_type_node; } DECL_ARG_TYPE (param_decl) = type; TREE_READONLY (param_decl) = readonly; return param_decl; } /* Process the attributes in ATTR_LIST for NODE, which is either a DECL or a TYPE. If IN_PLACE is true, the tree pointed to by NODE should not be changed. GNAT_NODE is used for the position of error messages. */ void process_attributes (tree *node, struct attrib **attr_list, bool in_place, Node_Id gnat_node) { struct attrib *attr; for (attr = *attr_list; attr; attr = attr->next) switch (attr->type) { case ATTR_MACHINE_ATTRIBUTE: Sloc_to_locus (Sloc (gnat_node), &input_location); decl_attributes (node, tree_cons (attr->name, attr->args, NULL_TREE), in_place ? ATTR_FLAG_TYPE_IN_PLACE : 0); break; case ATTR_LINK_ALIAS: if (!DECL_EXTERNAL (*node)) { TREE_STATIC (*node) = 1; assemble_alias (*node, attr->name); } break; case ATTR_WEAK_EXTERNAL: if (SUPPORTS_WEAK) declare_weak (*node); else post_error ("?weak declarations not supported on this target", attr->error_point); break; case ATTR_LINK_SECTION: if (targetm_common.have_named_sections) { set_decl_section_name (*node, IDENTIFIER_POINTER (attr->name)); DECL_COMMON (*node) = 0; } else post_error ("?section attributes are not supported for this target", attr->error_point); break; case ATTR_LINK_CONSTRUCTOR: DECL_STATIC_CONSTRUCTOR (*node) = 1; TREE_USED (*node) = 1; break; case ATTR_LINK_DESTRUCTOR: DECL_STATIC_DESTRUCTOR (*node) = 1; TREE_USED (*node) = 1; break; case ATTR_THREAD_LOCAL_STORAGE: set_decl_tls_model (*node, decl_default_tls_model (*node)); DECL_COMMON (*node) = 0; break; } *attr_list = NULL; } /* Return true if VALUE is a known to be a multiple of FACTOR, which must be a power of 2. */ bool value_factor_p (tree value, HOST_WIDE_INT factor) { if (tree_fits_uhwi_p (value)) return tree_to_uhwi (value) % factor == 0; if (TREE_CODE (value) == MULT_EXPR) return (value_factor_p (TREE_OPERAND (value, 0), factor) || value_factor_p (TREE_OPERAND (value, 1), factor)); return false; } /* Return whether GNAT_NODE is a defining identifier for a renaming that comes from the parameter association for the instantiation of a generic. We do not want to emit source location for them: the code generated for their initialization is likely to disturb debugging. */ bool renaming_from_generic_instantiation_p (Node_Id gnat_node) { if (Nkind (gnat_node) != N_Defining_Identifier || !IN (Ekind (gnat_node), Object_Kind) || Comes_From_Source (gnat_node) || !Present (Renamed_Object (gnat_node))) return false; /* Get the object declaration of the renamed object, if any and if the renamed object is a mere identifier. */ gnat_node = Renamed_Object (gnat_node); if (Nkind (gnat_node) != N_Identifier) return false; gnat_node = Entity (gnat_node); if (!Present (Parent (gnat_node))) return false; gnat_node = Parent (gnat_node); return (Present (gnat_node) && Nkind (gnat_node) == N_Object_Declaration && Present (Corresponding_Generic_Association (gnat_node))); } /* Defer the initialization of DECL's DECL_CONTEXT attribute, scheduling to feed it with the elaboration of GNAT_SCOPE. */ static struct deferred_decl_context_node * add_deferred_decl_context (tree decl, Entity_Id gnat_scope, int force_global) { struct deferred_decl_context_node *new_node; new_node = (struct deferred_decl_context_node * ) xmalloc (sizeof (*new_node)); new_node->decl = decl; new_node->gnat_scope = gnat_scope; new_node->force_global = force_global; new_node->types.create (1); new_node->next = deferred_decl_context_queue; deferred_decl_context_queue = new_node; return new_node; } /* Defer the initialization of TYPE's TYPE_CONTEXT attribute, scheduling to feed it with the DECL_CONTEXT computed as part of N as soon as it is computed. */ static void add_deferred_type_context (struct deferred_decl_context_node *n, tree type) { n->types.safe_push (type); } /* Get the GENERIC node corresponding to GNAT_SCOPE, if available. Return NULL_TREE if it is not available. */ static tree compute_deferred_decl_context (Entity_Id gnat_scope) { tree context; if (present_gnu_tree (gnat_scope)) context = get_gnu_tree (gnat_scope); else return NULL_TREE; if (TREE_CODE (context) == TYPE_DECL) { const tree context_type = TREE_TYPE (context); /* Skip dummy types: only the final ones can appear in the context chain. */ if (TYPE_DUMMY_P (context_type)) return NULL_TREE; /* ..._TYPE nodes are more useful than TYPE_DECL nodes in the context chain. */ else context = context_type; } return context; } /* Try to process all deferred nodes in the queue. Keep in the queue the ones that cannot be processed yet, remove the other ones. If FORCE is true, force the processing for all nodes, use the global context when nodes don't have a GNU translation. */ void process_deferred_decl_context (bool force) { struct deferred_decl_context_node **it = &deferred_decl_context_queue; struct deferred_decl_context_node *node; while (*it != NULL) { bool processed = false; tree context = NULL_TREE; Entity_Id gnat_scope; node = *it; /* If FORCE, get the innermost elaborated scope. Otherwise, just try to get the first scope. */ gnat_scope = node->gnat_scope; while (Present (gnat_scope)) { context = compute_deferred_decl_context (gnat_scope); if (!force || context != NULL_TREE) break; gnat_scope = get_debug_scope (gnat_scope, NULL); } /* Imported declarations must not be in a local context (i.e. not inside a function). */ if (context != NULL_TREE && node->force_global > 0) { tree ctx = context; while (ctx != NULL_TREE) { gcc_assert (TREE_CODE (ctx) != FUNCTION_DECL); ctx = (DECL_P (ctx)) ? DECL_CONTEXT (ctx) : TYPE_CONTEXT (ctx); } } /* If FORCE, we want to get rid of all nodes in the queue: in case there was no elaborated scope, use the global context. */ if (force && context == NULL_TREE) context = get_global_context (); if (context != NULL_TREE) { tree t; int i; DECL_CONTEXT (node->decl) = context; /* Propagate it to the TYPE_CONTEXT attributes of the requested ..._TYPE nodes. */ FOR_EACH_VEC_ELT (node->types, i, t) { gnat_set_type_context (t, context); } processed = true; } /* If this node has been successfuly processed, remove it from the queue. Then move to the next node. */ if (processed) { *it = node->next; node->types.release (); free (node); } else it = &node->next; } } /* Return VALUE scaled by the biggest power-of-2 factor of EXPR. */ static unsigned int scale_by_factor_of (tree expr, unsigned int value) { unsigned HOST_WIDE_INT addend = 0; unsigned HOST_WIDE_INT factor = 1; /* Peel conversions around EXPR and try to extract bodies from function calls: it is possible to get the scale factor from size functions. */ expr = remove_conversions (expr, true); if (TREE_CODE (expr) == CALL_EXPR) expr = maybe_inline_call_in_expr (expr); /* Sometimes we get PLUS_EXPR (BIT_AND_EXPR (..., X), Y), where Y is a multiple of the scale factor we are looking for. */ if (TREE_CODE (expr) == PLUS_EXPR && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST && tree_fits_uhwi_p (TREE_OPERAND (expr, 1))) { addend = TREE_INT_CST_LOW (TREE_OPERAND (expr, 1)); expr = TREE_OPERAND (expr, 0); } /* An expression which is a bitwise AND with a mask has a power-of-2 factor corresponding to the number of trailing zeros of the mask. */ if (TREE_CODE (expr) == BIT_AND_EXPR && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST) { unsigned HOST_WIDE_INT mask = TREE_INT_CST_LOW (TREE_OPERAND (expr, 1)); unsigned int i = 0; while ((mask & 1) == 0 && i < HOST_BITS_PER_WIDE_INT) { mask >>= 1; factor *= 2; i++; } } /* If the addend is not a multiple of the factor we found, give up. In theory we could find a smaller common factor but it's useless for our needs. This situation arises when dealing with a field F1 with no alignment requirement but that is following a field F2 with such requirements. As long as we have F2's offset, we don't need alignment information to compute F1's. */ if (addend % factor != 0) factor = 1; return factor * value; } /* Given two consecutive field decls PREV_FIELD and CURR_FIELD, return true unless we can prove these 2 fields are laid out in such a way that no gap exist between the end of PREV_FIELD and the beginning of CURR_FIELD. OFFSET is the distance in bits between the end of PREV_FIELD and the starting position of CURR_FIELD. It is ignored if null. */ static bool potential_alignment_gap (tree prev_field, tree curr_field, tree offset) { /* If this is the first field of the record, there cannot be any gap */ if (!prev_field) return false; /* If the previous field is a union type, then return false: The only time when such a field is not the last field of the record is when there are other components at fixed positions after it (meaning there was a rep clause for every field), in which case we don't want the alignment constraint to override them. */ if (TREE_CODE (TREE_TYPE (prev_field)) == QUAL_UNION_TYPE) return false; /* If the distance between the end of prev_field and the beginning of curr_field is constant, then there is a gap if the value of this constant is not null. */ if (offset && tree_fits_uhwi_p (offset)) return !integer_zerop (offset); /* If the size and position of the previous field are constant, then check the sum of this size and position. There will be a gap iff it is not multiple of the current field alignment. */ if (tree_fits_uhwi_p (DECL_SIZE (prev_field)) && tree_fits_uhwi_p (bit_position (prev_field))) return ((tree_to_uhwi (bit_position (prev_field)) + tree_to_uhwi (DECL_SIZE (prev_field))) % DECL_ALIGN (curr_field) != 0); /* If both the position and size of the previous field are multiples of the current field alignment, there cannot be any gap. */ if (value_factor_p (bit_position (prev_field), DECL_ALIGN (curr_field)) && value_factor_p (DECL_SIZE (prev_field), DECL_ALIGN (curr_field))) return false; /* Fallback, return that there may be a potential gap */ return true; } /* Return a LABEL_DECL with NAME. GNAT_NODE is used for the position of the decl. */ tree create_label_decl (tree name, Node_Id gnat_node) { tree label_decl = build_decl (input_location, LABEL_DECL, name, void_type_node); DECL_MODE (label_decl) = VOIDmode; /* Add this decl to the current binding level. */ gnat_pushdecl (label_decl, gnat_node); return label_decl; } /* Return a FUNCTION_DECL node. NAME is the name of the subprogram, ASM_NAME its assembler name, TYPE its type (a FUNCTION_TYPE node), PARAM_DECL_LIST the list of its parameters (a list of PARM_DECL nodes chained through the DECL_CHAIN field). INLINE_STATUS, PUBLIC_FLAG, EXTERN_FLAG and ATTR_LIST are used to set the appropriate fields in the FUNCTION_DECL. ARTIFICIAL_P is true if the subprogram was generated by the compiler. DEBUG_INFO_P is true if we need to write debug information for it. GNAT_NODE is used for the position of the decl. */ tree create_subprog_decl (tree name, tree asm_name, tree type, tree param_decl_list, enum inline_status_t inline_status, bool public_flag, bool extern_flag, bool artificial_p, bool debug_info_p, struct attrib *attr_list, Node_Id gnat_node) { tree subprog_decl = build_decl (input_location, FUNCTION_DECL, name, type); tree result_decl = build_decl (input_location, RESULT_DECL, NULL_TREE, TREE_TYPE (type)); DECL_ARGUMENTS (subprog_decl) = param_decl_list; DECL_ARTIFICIAL (subprog_decl) = artificial_p; DECL_EXTERNAL (subprog_decl) = extern_flag; switch (inline_status) { case is_suppressed: DECL_UNINLINABLE (subprog_decl) = 1; break; case is_disabled: break; case is_required: if (Back_End_Inlining) decl_attributes (&subprog_decl, tree_cons (get_identifier ("always_inline"), NULL_TREE, NULL_TREE), ATTR_FLAG_TYPE_IN_PLACE); /* ... fall through ... */ case is_enabled: DECL_DECLARED_INLINE_P (subprog_decl) = 1; DECL_NO_INLINE_WARNING_P (subprog_decl) = artificial_p; break; default: gcc_unreachable (); } if (!debug_info_p) DECL_IGNORED_P (subprog_decl) = 1; TREE_PUBLIC (subprog_decl) = public_flag; TREE_READONLY (subprog_decl) = TYPE_READONLY (type); TREE_THIS_VOLATILE (subprog_decl) = TYPE_VOLATILE (type); TREE_SIDE_EFFECTS (subprog_decl) = TYPE_VOLATILE (type); DECL_ARTIFICIAL (result_decl) = 1; DECL_IGNORED_P (result_decl) = 1; DECL_BY_REFERENCE (result_decl) = TREE_ADDRESSABLE (type); DECL_RESULT (subprog_decl) = result_decl; process_attributes (&subprog_decl, &attr_list, true, gnat_node); /* Add this decl to the current binding level. */ gnat_pushdecl (subprog_decl, gnat_node); if (asm_name) { /* Let the target mangle the name if this isn't a verbatim asm. */ if (*IDENTIFIER_POINTER (asm_name) != '*') asm_name = targetm.mangle_decl_assembler_name (subprog_decl, asm_name); SET_DECL_ASSEMBLER_NAME (subprog_decl, asm_name); /* The expand_main_function circuitry expects "main_identifier_node" to designate the DECL_NAME of the 'main' entry point, in turn expected to be declared as the "main" function literally by default. Ada program entry points are typically declared with a different name within the binder generated file, exported as 'main' to satisfy the system expectations. Force main_identifier_node in this case. */ if (asm_name == main_identifier_node) DECL_NAME (subprog_decl) = main_identifier_node; } /* Output the assembler code and/or RTL for the declaration. */ rest_of_decl_compilation (subprog_decl, global_bindings_p (), 0); return subprog_decl; } /* Set up the framework for generating code for SUBPROG_DECL, a subprogram body. This routine needs to be invoked before processing the declarations appearing in the subprogram. */ void begin_subprog_body (tree subprog_decl) { tree param_decl; announce_function (subprog_decl); /* This function is being defined. */ TREE_STATIC (subprog_decl) = 1; /* The failure of this assertion will likely come from a wrong context for the subprogram body, e.g. another procedure for a procedure declared at library level. */ gcc_assert (current_function_decl == decl_function_context (subprog_decl)); current_function_decl = subprog_decl; /* Enter a new binding level and show that all the parameters belong to this function. */ gnat_pushlevel (); for (param_decl = DECL_ARGUMENTS (subprog_decl); param_decl; param_decl = DECL_CHAIN (param_decl)) DECL_CONTEXT (param_decl) = subprog_decl; make_decl_rtl (subprog_decl); } /* Finish translating the current subprogram and set its BODY. */ void end_subprog_body (tree body) { tree fndecl = current_function_decl; /* Attach the BLOCK for this level to the function and pop the level. */ BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl; DECL_INITIAL (fndecl) = current_binding_level->block; gnat_poplevel (); /* Mark the RESULT_DECL as being in this subprogram. */ DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl; /* The body should be a BIND_EXPR whose BLOCK is the top-level one. */ if (TREE_CODE (body) == BIND_EXPR) { BLOCK_SUPERCONTEXT (BIND_EXPR_BLOCK (body)) = fndecl; DECL_INITIAL (fndecl) = BIND_EXPR_BLOCK (body); } DECL_SAVED_TREE (fndecl) = body; current_function_decl = decl_function_context (fndecl); } /* Wrap up compilation of SUBPROG_DECL, a subprogram body. */ void rest_of_subprog_body_compilation (tree subprog_decl) { /* We cannot track the location of errors past this point. */ error_gnat_node = Empty; /* If we're only annotating types, don't actually compile this function. */ if (type_annotate_only) return; /* Dump functions before gimplification. */ dump_function (TDI_original, subprog_decl); if (!decl_function_context (subprog_decl)) cgraph_node::finalize_function (subprog_decl, false); else /* Register this function with cgraph just far enough to get it added to our parent's nested function list. */ (void) cgraph_node::get_create (subprog_decl); } tree gnat_builtin_function (tree decl) { gnat_pushdecl (decl, Empty); return decl; } /* Return an integer type with the number of bits of precision given by PRECISION. UNSIGNEDP is nonzero if the type is unsigned; otherwise it is a signed type. */ tree gnat_type_for_size (unsigned precision, int unsignedp) { tree t; char type_name[20]; if (precision <= 2 * MAX_BITS_PER_WORD && signed_and_unsigned_types[precision][unsignedp]) return signed_and_unsigned_types[precision][unsignedp]; if (unsignedp) t = make_unsigned_type (precision); else t = make_signed_type (precision); if (precision <= 2 * MAX_BITS_PER_WORD) signed_and_unsigned_types[precision][unsignedp] = t; if (!TYPE_NAME (t)) { sprintf (type_name, "%sSIGNED_%u", unsignedp ? "UN" : "", precision); TYPE_NAME (t) = get_identifier (type_name); } return t; } /* Likewise for floating-point types. */ static tree float_type_for_precision (int precision, machine_mode mode) { tree t; char type_name[20]; if (float_types[(int) mode]) return float_types[(int) mode]; float_types[(int) mode] = t = make_node (REAL_TYPE); TYPE_PRECISION (t) = precision; layout_type (t); gcc_assert (TYPE_MODE (t) == mode); if (!TYPE_NAME (t)) { sprintf (type_name, "FLOAT_%d", precision); TYPE_NAME (t) = get_identifier (type_name); } return t; } /* Return a data type that has machine mode MODE. UNSIGNEDP selects an unsigned type; otherwise a signed type is returned. */ tree gnat_type_for_mode (machine_mode mode, int unsignedp) { if (mode == BLKmode) return NULL_TREE; if (mode == VOIDmode) return void_type_node; if (COMPLEX_MODE_P (mode)) return NULL_TREE; if (SCALAR_FLOAT_MODE_P (mode)) return float_type_for_precision (GET_MODE_PRECISION (mode), mode); if (SCALAR_INT_MODE_P (mode)) return gnat_type_for_size (GET_MODE_BITSIZE (mode), unsignedp); if (VECTOR_MODE_P (mode)) { machine_mode inner_mode = GET_MODE_INNER (mode); tree inner_type = gnat_type_for_mode (inner_mode, unsignedp); if (inner_type) return build_vector_type_for_mode (inner_type, mode); } return NULL_TREE; } /* Return the unsigned version of a TYPE_NODE, a scalar type. */ tree gnat_unsigned_type (tree type_node) { tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 1); if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node)) { type = copy_node (type); TREE_TYPE (type) = type_node; } else if (TREE_TYPE (type_node) && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE && TYPE_MODULAR_P (TREE_TYPE (type_node))) { type = copy_node (type); TREE_TYPE (type) = TREE_TYPE (type_node); } return type; } /* Return the signed version of a TYPE_NODE, a scalar type. */ tree gnat_signed_type (tree type_node) { tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 0); if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node)) { type = copy_node (type); TREE_TYPE (type) = type_node; } else if (TREE_TYPE (type_node) && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE && TYPE_MODULAR_P (TREE_TYPE (type_node))) { type = copy_node (type); TREE_TYPE (type) = TREE_TYPE (type_node); } return type; } /* Return 1 if the types T1 and T2 are compatible, i.e. if they can be transparently converted to each other. */ int gnat_types_compatible_p (tree t1, tree t2) { enum tree_code code; /* This is the default criterion. */ if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2)) return 1; /* We only check structural equivalence here. */ if ((code = TREE_CODE (t1)) != TREE_CODE (t2)) return 0; /* Vector types are also compatible if they have the same number of subparts and the same form of (scalar) element type. */ if (code == VECTOR_TYPE && TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2) && TREE_CODE (TREE_TYPE (t1)) == TREE_CODE (TREE_TYPE (t2)) && TYPE_PRECISION (TREE_TYPE (t1)) == TYPE_PRECISION (TREE_TYPE (t2))) return 1; /* Array types are also compatible if they are constrained and have the same domain(s), the same component type and the same scalar storage order. */ if (code == ARRAY_TYPE && (TYPE_DOMAIN (t1) == TYPE_DOMAIN (t2) || (TYPE_DOMAIN (t1) && TYPE_DOMAIN (t2) && tree_int_cst_equal (TYPE_MIN_VALUE (TYPE_DOMAIN (t1)), TYPE_MIN_VALUE (TYPE_DOMAIN (t2))) && tree_int_cst_equal (TYPE_MAX_VALUE (TYPE_DOMAIN (t1)), TYPE_MAX_VALUE (TYPE_DOMAIN (t2))))) && (TREE_TYPE (t1) == TREE_TYPE (t2) || (TREE_CODE (TREE_TYPE (t1)) == ARRAY_TYPE && gnat_types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))) && TYPE_REVERSE_STORAGE_ORDER (t1) == TYPE_REVERSE_STORAGE_ORDER (t2)) return 1; return 0; } /* Return true if EXPR is a useless type conversion. */ bool gnat_useless_type_conversion (tree expr) { if (CONVERT_EXPR_P (expr) || TREE_CODE (expr) == VIEW_CONVERT_EXPR || TREE_CODE (expr) == NON_LVALUE_EXPR) return gnat_types_compatible_p (TREE_TYPE (expr), TREE_TYPE (TREE_OPERAND (expr, 0))); return false; } /* Return true if T, a FUNCTION_TYPE, has the specified list of flags. */ bool fntype_same_flags_p (const_tree t, tree cico_list, bool return_unconstrained_p, bool return_by_direct_ref_p, bool return_by_invisi_ref_p) { return TYPE_CI_CO_LIST (t) == cico_list && TYPE_RETURN_UNCONSTRAINED_P (t) == return_unconstrained_p && TYPE_RETURN_BY_DIRECT_REF_P (t) == return_by_direct_ref_p && TREE_ADDRESSABLE (t) == return_by_invisi_ref_p; } /* EXP is an expression for the size of an object. If this size contains discriminant references, replace them with the maximum (if MAX_P) or minimum (if !MAX_P) possible value of the discriminant. */ tree max_size (tree exp, bool max_p) { enum tree_code code = TREE_CODE (exp); tree type = TREE_TYPE (exp); switch (TREE_CODE_CLASS (code)) { case tcc_declaration: case tcc_constant: return exp; case tcc_vl_exp: if (code == CALL_EXPR) { tree t, *argarray; int n, i; t = maybe_inline_call_in_expr (exp); if (t) return max_size (t, max_p); n = call_expr_nargs (exp); gcc_assert (n > 0); argarray = XALLOCAVEC (tree, n); for (i = 0; i < n; i++) argarray[i] = max_size (CALL_EXPR_ARG (exp, i), max_p); return build_call_array (type, CALL_EXPR_FN (exp), n, argarray); } break; case tcc_reference: /* If this contains a PLACEHOLDER_EXPR, it is the thing we want to modify. Otherwise, we treat it like a variable. */ if (CONTAINS_PLACEHOLDER_P (exp)) { tree val_type = TREE_TYPE (TREE_OPERAND (exp, 1)); tree val = (max_p ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type)); return max_size (convert (get_base_type (val_type), val), true); } return exp; case tcc_comparison: return max_p ? size_one_node : size_zero_node; case tcc_unary: if (code == NON_LVALUE_EXPR) return max_size (TREE_OPERAND (exp, 0), max_p); return fold_build1 (code, type, max_size (TREE_OPERAND (exp, 0), code == NEGATE_EXPR ? !max_p : max_p)); case tcc_binary: { tree lhs = max_size (TREE_OPERAND (exp, 0), max_p); tree rhs = max_size (TREE_OPERAND (exp, 1), code == MINUS_EXPR ? !max_p : max_p); /* Special-case wanting the maximum value of a MIN_EXPR. In that case, if one side overflows, return the other. */ if (max_p && code == MIN_EXPR) { if (TREE_CODE (rhs) == INTEGER_CST && TREE_OVERFLOW (rhs)) return lhs; if (TREE_CODE (lhs) == INTEGER_CST && TREE_OVERFLOW (lhs)) return rhs; } /* Likewise, handle a MINUS_EXPR or PLUS_EXPR with the LHS overflowing and the RHS a variable. */ if ((code == MINUS_EXPR || code == PLUS_EXPR) && TREE_CODE (lhs) == INTEGER_CST && TREE_OVERFLOW (lhs) && TREE_CODE (rhs) != INTEGER_CST) return lhs; /* If we are going to subtract a "negative" value in an unsigned type, do the operation as an addition of the negated value, in order to avoid creating a spurious overflow below. */ if (code == MINUS_EXPR && TYPE_UNSIGNED (type) && TREE_CODE (rhs) == INTEGER_CST && !TREE_OVERFLOW (rhs) && tree_int_cst_sign_bit (rhs) != 0) { rhs = fold_build1 (NEGATE_EXPR, type, rhs); code = PLUS_EXPR; } /* We need to detect overflows so we call size_binop here. */ return size_binop (code, lhs, rhs); } case tcc_expression: switch (TREE_CODE_LENGTH (code)) { case 1: if (code == SAVE_EXPR) return exp; return fold_build1 (code, type, max_size (TREE_OPERAND (exp, 0), max_p)); case 2: if (code == COMPOUND_EXPR) return max_size (TREE_OPERAND (exp, 1), max_p); return fold_build2 (code, type, max_size (TREE_OPERAND (exp, 0), max_p), max_size (TREE_OPERAND (exp, 1), max_p)); case 3: if (code == COND_EXPR) return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type, max_size (TREE_OPERAND (exp, 1), max_p), max_size (TREE_OPERAND (exp, 2), max_p)); default: break; } /* Other tree classes cannot happen. */ default: break; } gcc_unreachable (); } /* Build a template of type TEMPLATE_TYPE from the array bounds of ARRAY_TYPE. EXPR is an expression that we can use to locate any PLACEHOLDER_EXPRs. Return a constructor for the template. */ tree build_template (tree template_type, tree array_type, tree expr) { vec<constructor_elt, va_gc> *template_elts = NULL; tree bound_list = NULL_TREE; tree field; while (TREE_CODE (array_type) == RECORD_TYPE && (TYPE_PADDING_P (array_type) || TYPE_JUSTIFIED_MODULAR_P (array_type))) array_type = TREE_TYPE (TYPE_FIELDS (array_type)); if (TREE_CODE (array_type) == ARRAY_TYPE || (TREE_CODE (array_type) == INTEGER_TYPE && TYPE_HAS_ACTUAL_BOUNDS_P (array_type))) bound_list = TYPE_ACTUAL_BOUNDS (array_type); /* First make the list for a CONSTRUCTOR for the template. Go down the field list of the template instead of the type chain because this array might be an Ada array of arrays and we can't tell where the nested arrays stop being the underlying object. */ for (field = TYPE_FIELDS (template_type); field; (bound_list ? (bound_list = TREE_CHAIN (bound_list)) : (array_type = TREE_TYPE (array_type))), field = DECL_CHAIN (DECL_CHAIN (field))) { tree bounds, min, max; /* If we have a bound list, get the bounds from there. Likewise for an ARRAY_TYPE. Otherwise, if expr is a PARM_DECL with DECL_BY_COMPONENT_PTR_P, use the bounds of the field in the template. This will give us a maximum range. */ if (bound_list) bounds = TREE_VALUE (bound_list); else if (TREE_CODE (array_type) == ARRAY_TYPE) bounds = TYPE_INDEX_TYPE (TYPE_DOMAIN (array_type)); else if (expr && TREE_CODE (expr) == PARM_DECL && DECL_BY_COMPONENT_PTR_P (expr)) bounds = TREE_TYPE (field); else gcc_unreachable (); min = convert (TREE_TYPE (field), TYPE_MIN_VALUE (bounds)); max = convert (TREE_TYPE (DECL_CHAIN (field)), TYPE_MAX_VALUE (bounds)); /* If either MIN or MAX involve a PLACEHOLDER_EXPR, we must substitute it from OBJECT. */ min = SUBSTITUTE_PLACEHOLDER_IN_EXPR (min, expr); max = SUBSTITUTE_PLACEHOLDER_IN_EXPR (max, expr); CONSTRUCTOR_APPEND_ELT (template_elts, field, min); CONSTRUCTOR_APPEND_ELT (template_elts, DECL_CHAIN (field), max); } return gnat_build_constructor (template_type, template_elts); } /* Return true if TYPE is suitable for the element type of a vector. */ static bool type_for_vector_element_p (tree type) { machine_mode mode; if (!INTEGRAL_TYPE_P (type) && !SCALAR_FLOAT_TYPE_P (type) && !FIXED_POINT_TYPE_P (type)) return false; mode = TYPE_MODE (type); if (GET_MODE_CLASS (mode) != MODE_INT && !SCALAR_FLOAT_MODE_P (mode) && !ALL_SCALAR_FIXED_POINT_MODE_P (mode)) return false; return true; } /* Return a vector type given the SIZE and the INNER_TYPE, or NULL_TREE if this is not possible. If ATTRIBUTE is non-zero, we are processing the attribute declaration and want to issue error messages on failure. */ static tree build_vector_type_for_size (tree inner_type, tree size, tree attribute) { unsigned HOST_WIDE_INT size_int, inner_size_int; int nunits; /* Silently punt on variable sizes. We can't make vector types for them, need to ignore them on front-end generated subtypes of unconstrained base types, and this attribute is for binding implementors, not end users, so we should never get there from legitimate explicit uses. */ if (!tree_fits_uhwi_p (size)) return NULL_TREE; size_int = tree_to_uhwi (size); if (!type_for_vector_element_p (inner_type)) { if (attribute) error ("invalid element type for attribute %qs", IDENTIFIER_POINTER (attribute)); return NULL_TREE; } inner_size_int = tree_to_uhwi (TYPE_SIZE_UNIT (inner_type)); if (size_int % inner_size_int) { if (attribute) error ("vector size not an integral multiple of component size"); return NULL_TREE; } if (size_int == 0) { if (attribute) error ("zero vector size"); return NULL_TREE; } nunits = size_int / inner_size_int; if (nunits & (nunits - 1)) { if (attribute) error ("number of components of vector not a power of two"); return NULL_TREE; } return build_vector_type (inner_type, nunits); } /* Return a vector type whose representative array type is ARRAY_TYPE, or NULL_TREE if this is not possible. If ATTRIBUTE is non-zero, we are processing the attribute and want to issue error messages on failure. */ static tree build_vector_type_for_array (tree array_type, tree attribute) { tree vector_type = build_vector_type_for_size (TREE_TYPE (array_type), TYPE_SIZE_UNIT (array_type), attribute); if (!vector_type) return NULL_TREE; TYPE_REPRESENTATIVE_ARRAY (vector_type) = array_type; return vector_type; } /* Build a type to be used to represent an aliased object whose nominal type is an unconstrained array. This consists of a RECORD_TYPE containing a field of TEMPLATE_TYPE and a field of OBJECT_TYPE, which is an ARRAY_TYPE. If ARRAY_TYPE is that of an unconstrained array, this is used to represent an arbitrary unconstrained object. Use NAME as the name of the record. DEBUG_INFO_P is true if we need to write debug information for the type. */ tree build_unc_object_type (tree template_type, tree object_type, tree name, bool debug_info_p) { tree decl; tree type = make_node (RECORD_TYPE); tree template_field = create_field_decl (get_identifier ("BOUNDS"), template_type, type, NULL_TREE, NULL_TREE, 0, 1); tree array_field = create_field_decl (get_identifier ("ARRAY"), object_type, type, NULL_TREE, NULL_TREE, 0, 1); TYPE_NAME (type) = name; TYPE_CONTAINS_TEMPLATE_P (type) = 1; DECL_CHAIN (template_field) = array_field; finish_record_type (type, template_field, 0, true); /* Declare it now since it will never be declared otherwise. This is necessary to ensure that its subtrees are properly marked. */ decl = create_type_decl (name, type, true, debug_info_p, Empty); /* template_type will not be used elsewhere than here, so to keep the debug info clean and in order to avoid scoping issues, make decl its context. */ gnat_set_type_context (template_type, decl); return type; } /* Same, taking a thin or fat pointer type instead of a template type. */ tree build_unc_object_type_from_ptr (tree thin_fat_ptr_type, tree object_type, tree name, bool debug_info_p) { tree template_type; gcc_assert (TYPE_IS_FAT_OR_THIN_POINTER_P (thin_fat_ptr_type)); template_type = (TYPE_IS_FAT_POINTER_P (thin_fat_ptr_type) ? TREE_TYPE (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (thin_fat_ptr_type)))) : TREE_TYPE (TYPE_FIELDS (TREE_TYPE (thin_fat_ptr_type)))); return build_unc_object_type (template_type, object_type, name, debug_info_p); } /* Update anything previously pointing to OLD_TYPE to point to NEW_TYPE. In the normal case this is just two adjustments, but we have more to do if NEW_TYPE is an UNCONSTRAINED_ARRAY_TYPE. */ void update_pointer_to (tree old_type, tree new_type) { tree ptr = TYPE_POINTER_TO (old_type); tree ref = TYPE_REFERENCE_TO (old_type); tree t; /* If this is the main variant, process all the other variants first. */ if (TYPE_MAIN_VARIANT (old_type) == old_type) for (t = TYPE_NEXT_VARIANT (old_type); t; t = TYPE_NEXT_VARIANT (t)) update_pointer_to (t, new_type); /* If no pointers and no references, we are done. */ if (!ptr && !ref) return; /* Merge the old type qualifiers in the new type. Each old variant has qualifiers for specific reasons, and the new designated type as well. Each set of qualifiers represents useful information grabbed at some point, and merging the two simply unifies these inputs into the final type description. Consider for instance a volatile type frozen after an access to constant type designating it; after the designated type's freeze, we get here with a volatile NEW_TYPE and a dummy OLD_TYPE with a readonly variant, created when the access type was processed. We will make a volatile and readonly designated type, because that's what it really is. We might also get here for a non-dummy OLD_TYPE variant with different qualifiers than those of NEW_TYPE, for instance in some cases of pointers to private record type elaboration (see the comments around the call to this routine in gnat_to_gnu_entity <E_Access_Type>). We have to merge the qualifiers in those cases too, to avoid accidentally discarding the initial set, and will often end up with OLD_TYPE == NEW_TYPE then. */ new_type = build_qualified_type (new_type, TYPE_QUALS (old_type) | TYPE_QUALS (new_type)); /* If old type and new type are identical, there is nothing to do. */ if (old_type == new_type) return; /* Otherwise, first handle the simple case. */ if (TREE_CODE (new_type) != UNCONSTRAINED_ARRAY_TYPE) { tree new_ptr, new_ref; /* If pointer or reference already points to new type, nothing to do. This can happen as update_pointer_to can be invoked multiple times on the same couple of types because of the type variants. */ if ((ptr && TREE_TYPE (ptr) == new_type) || (ref && TREE_TYPE (ref) == new_type)) return; /* Chain PTR and its variants at the end. */ new_ptr = TYPE_POINTER_TO (new_type); if (new_ptr) { while (TYPE_NEXT_PTR_TO (new_ptr)) new_ptr = TYPE_NEXT_PTR_TO (new_ptr); TYPE_NEXT_PTR_TO (new_ptr) = ptr; } else TYPE_POINTER_TO (new_type) = ptr; /* Now adjust them. */ for (; ptr; ptr = TYPE_NEXT_PTR_TO (ptr)) for (t = TYPE_MAIN_VARIANT (ptr); t; t = TYPE_NEXT_VARIANT (t)) { TREE_TYPE (t) = new_type; if (TYPE_NULL_BOUNDS (t)) TREE_TYPE (TREE_OPERAND (TYPE_NULL_BOUNDS (t), 0)) = new_type; } /* Chain REF and its variants at the end. */ new_ref = TYPE_REFERENCE_TO (new_type); if (new_ref) { while (TYPE_NEXT_REF_TO (new_ref)) new_ref = TYPE_NEXT_REF_TO (new_ref); TYPE_NEXT_REF_TO (new_ref) = ref; } else TYPE_REFERENCE_TO (new_type) = ref; /* Now adjust them. */ for (; ref; ref = TYPE_NEXT_REF_TO (ref)) for (t = TYPE_MAIN_VARIANT (ref); t; t = TYPE_NEXT_VARIANT (t)) TREE_TYPE (t) = new_type; TYPE_POINTER_TO (old_type) = NULL_TREE; TYPE_REFERENCE_TO (old_type) = NULL_TREE; } /* Now deal with the unconstrained array case. In this case the pointer is actually a record where both fields are pointers to dummy nodes. Turn them into pointers to the correct types using update_pointer_to. Likewise for the pointer to the object record (thin pointer). */ else { tree new_ptr = TYPE_POINTER_TO (new_type); gcc_assert (TYPE_IS_FAT_POINTER_P (ptr)); /* If PTR already points to NEW_TYPE, nothing to do. This can happen since update_pointer_to can be invoked multiple times on the same couple of types because of the type variants. */ if (TYPE_UNCONSTRAINED_ARRAY (ptr) == new_type) return; update_pointer_to (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))), TREE_TYPE (TREE_TYPE (TYPE_FIELDS (new_ptr)))); update_pointer_to (TREE_TYPE (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (ptr)))), TREE_TYPE (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (new_ptr))))); update_pointer_to (TYPE_OBJECT_RECORD_TYPE (old_type), TYPE_OBJECT_RECORD_TYPE (new_type)); TYPE_POINTER_TO (old_type) = NULL_TREE; } } /* Convert EXPR, a pointer to a constrained array, into a pointer to an unconstrained one. This involves making or finding a template. */ static tree convert_to_fat_pointer (tree type, tree expr) { tree template_type = TREE_TYPE (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (type)))); tree p_array_type = TREE_TYPE (TYPE_FIELDS (type)); tree etype = TREE_TYPE (expr); tree template_addr; vec<constructor_elt, va_gc> *v; vec_alloc (v, 2); /* If EXPR is null, make a fat pointer that contains a null pointer to the array (compare_fat_pointers ensures that this is the full discriminant) and a valid pointer to the bounds. This latter property is necessary since the compiler can hoist the load of the bounds done through it. */ if (integer_zerop (expr)) { tree ptr_template_type = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (type))); tree null_bounds, t; if (TYPE_NULL_BOUNDS (ptr_template_type)) null_bounds = TYPE_NULL_BOUNDS (ptr_template_type); else { /* The template type can still be dummy at this point so we build an empty constructor. The middle-end will fill it in with zeros. */ t = build_constructor (template_type, NULL); TREE_CONSTANT (t) = TREE_STATIC (t) = 1; null_bounds = build_unary_op (ADDR_EXPR, NULL_TREE, t); SET_TYPE_NULL_BOUNDS (ptr_template_type, null_bounds); } CONSTRUCTOR_APPEND_ELT (v, TYPE_FIELDS (type), fold_convert (p_array_type, null_pointer_node)); CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (TYPE_FIELDS (type)), null_bounds); t = build_constructor (type, v); /* Do not set TREE_CONSTANT so as to force T to static memory. */ TREE_CONSTANT (t) = 0; TREE_STATIC (t) = 1; return t; } /* If EXPR is a thin pointer, make template and data from the record. */ if (TYPE_IS_THIN_POINTER_P (etype)) { tree field = TYPE_FIELDS (TREE_TYPE (etype)); expr = gnat_protect_expr (expr); /* If we have a TYPE_UNCONSTRAINED_ARRAY attached to the RECORD_TYPE, the thin pointer value has been shifted so we shift it back to get the template address. */ if (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (etype))) { template_addr = build_binary_op (POINTER_PLUS_EXPR, etype, expr, fold_build1 (NEGATE_EXPR, sizetype, byte_position (DECL_CHAIN (field)))); template_addr = fold_convert (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (type))), template_addr); } /* Otherwise we explicitly take the address of the fields. */ else { expr = build_unary_op (INDIRECT_REF, NULL_TREE, expr); template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, build_component_ref (expr, NULL_TREE, field, false)); expr = build_unary_op (ADDR_EXPR, NULL_TREE, build_component_ref (expr, NULL_TREE, DECL_CHAIN (field), false)); } } /* Otherwise, build the constructor for the template. */ else template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, build_template (template_type, TREE_TYPE (etype), expr)); /* The final result is a constructor for the fat pointer. If EXPR is an argument of a foreign convention subprogram, the type it points to is directly the component type. In this case, the expression type may not match the corresponding FIELD_DECL type at this point, so we call "convert" here to fix that up if necessary. This type consistency is required, for instance because it ensures that possible later folding of COMPONENT_REFs against this constructor always yields something of the same type as the initial reference. Note that the call to "build_template" above is still fine because it will only refer to the provided TEMPLATE_TYPE in this case. */ CONSTRUCTOR_APPEND_ELT (v, TYPE_FIELDS (type), convert (p_array_type, expr)); CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (TYPE_FIELDS (type)), template_addr); return gnat_build_constructor (type, v); } /* Create an expression whose value is that of EXPR, converted to type TYPE. The TREE_TYPE of the value is always TYPE. This function implements all reasonable conversions; callers should filter out those that are not permitted by the language being compiled. */ tree convert (tree type, tree expr) { tree etype = TREE_TYPE (expr); enum tree_code ecode = TREE_CODE (etype); enum tree_code code = TREE_CODE (type); /* If the expression is already of the right type, we are done. */ if (etype == type) return expr; /* If both input and output have padding and are of variable size, do this as an unchecked conversion. Likewise if one is a mere variant of the other, so we avoid a pointless unpad/repad sequence. */ else if (code == RECORD_TYPE && ecode == RECORD_TYPE && TYPE_PADDING_P (type) && TYPE_PADDING_P (etype) && (!TREE_CONSTANT (TYPE_SIZE (type)) || !TREE_CONSTANT (TYPE_SIZE (etype)) || TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype) || TYPE_NAME (TREE_TYPE (TYPE_FIELDS (type))) == TYPE_NAME (TREE_TYPE (TYPE_FIELDS (etype))))) ; /* If the output type has padding, convert to the inner type and make a constructor to build the record, unless a variable size is involved. */ else if (code == RECORD_TYPE && TYPE_PADDING_P (type)) { vec<constructor_elt, va_gc> *v; /* If we previously converted from another type and our type is of variable size, remove the conversion to avoid the need for variable-sized temporaries. Likewise for a conversion between original and packable version. */ if (TREE_CODE (expr) == VIEW_CONVERT_EXPR && (!TREE_CONSTANT (TYPE_SIZE (type)) || (ecode == RECORD_TYPE && TYPE_NAME (etype) == TYPE_NAME (TREE_TYPE (TREE_OPERAND (expr, 0)))))) expr = TREE_OPERAND (expr, 0); /* If we are just removing the padding from expr, convert the original object if we have variable size in order to avoid the need for some variable-sized temporaries. Likewise if the padding is a variant of the other, so we avoid a pointless unpad/repad sequence. */ if (TREE_CODE (expr) == COMPONENT_REF && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (expr, 0))) && (!TREE_CONSTANT (TYPE_SIZE (type)) || TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (expr, 0))) || (ecode == RECORD_TYPE && TYPE_NAME (etype) == TYPE_NAME (TREE_TYPE (TYPE_FIELDS (type)))))) return convert (type, TREE_OPERAND (expr, 0)); /* If the inner type is of self-referential size and the expression type is a record, do this as an unchecked conversion. But first pad the expression if possible to have the same size on both sides. */ if (ecode == RECORD_TYPE && CONTAINS_PLACEHOLDER_P (DECL_SIZE (TYPE_FIELDS (type)))) { if (TREE_CODE (TYPE_SIZE (etype)) == INTEGER_CST) expr = convert (maybe_pad_type (etype, TYPE_SIZE (type), 0, Empty, false, false, false, true), expr); return unchecked_convert (type, expr, false); } /* If we are converting between array types with variable size, do the final conversion as an unchecked conversion, again to avoid the need for some variable-sized temporaries. If valid, this conversion is very likely purely technical and without real effects. */ if (ecode == ARRAY_TYPE && TREE_CODE (TREE_TYPE (TYPE_FIELDS (type))) == ARRAY_TYPE && !TREE_CONSTANT (TYPE_SIZE (etype)) && !TREE_CONSTANT (TYPE_SIZE (type))) return unchecked_convert (type, convert (TREE_TYPE (TYPE_FIELDS (type)), expr), false); vec_alloc (v, 1); CONSTRUCTOR_APPEND_ELT (v, TYPE_FIELDS (type), convert (TREE_TYPE (TYPE_FIELDS (type)), expr)); return gnat_build_constructor (type, v); } /* If the input type has padding, remove it and convert to the output type. The conditions ordering is arranged to ensure that the output type is not a padding type here, as it is not clear whether the conversion would always be correct if this was to happen. */ else if (ecode == RECORD_TYPE && TYPE_PADDING_P (etype)) { tree unpadded; /* If we have just converted to this padded type, just get the inner expression. */ if (TREE_CODE (expr) == CONSTRUCTOR) unpadded = CONSTRUCTOR_ELT (expr, 0)->value; /* Otherwise, build an explicit component reference. */ else unpadded = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (etype), false); return convert (type, unpadded); } /* If the input is a biased type, adjust first. */ if (ecode == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (etype)) return convert (type, fold_build2 (PLUS_EXPR, TREE_TYPE (etype), fold_convert (TREE_TYPE (etype), expr), fold_convert (TREE_TYPE (etype), TYPE_MIN_VALUE (etype)))); /* If the input is a justified modular type, we need to extract the actual object before converting it to any other type with the exceptions of an unconstrained array or of a mere type variant. It is useful to avoid the extraction and conversion in the type variant case because it could end up replacing a VAR_DECL expr by a constructor and we might be about the take the address of the result. */ if (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype) && code != UNCONSTRAINED_ARRAY_TYPE && TYPE_MAIN_VARIANT (type) != TYPE_MAIN_VARIANT (etype)) return convert (type, build_component_ref (expr, NULL_TREE, TYPE_FIELDS (etype), false)); /* If converting to a type that contains a template, convert to the data type and then build the template. */ if (code == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (type)) { tree obj_type = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (type))); vec<constructor_elt, va_gc> *v; vec_alloc (v, 2); /* If the source already has a template, get a reference to the associated array only, as we are going to rebuild a template for the target type anyway. */ expr = maybe_unconstrained_array (expr); CONSTRUCTOR_APPEND_ELT (v, TYPE_FIELDS (type), build_template (TREE_TYPE (TYPE_FIELDS (type)), obj_type, NULL_TREE)); if (expr) CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (TYPE_FIELDS (type)), convert (obj_type, expr)); return gnat_build_constructor (type, v); } /* There are some cases of expressions that we process specially. */ switch (TREE_CODE (expr)) { case ERROR_MARK: return expr; case NULL_EXPR: /* Just set its type here. For TRANSFORM_EXPR, we will do the actual conversion in gnat_expand_expr. NULL_EXPR does not represent and actual value, so no conversion is needed. */ expr = copy_node (expr); TREE_TYPE (expr) = type; return expr; case STRING_CST: /* If we are converting a STRING_CST to another constrained array type, just make a new one in the proper type. */ if (code == ecode && AGGREGATE_TYPE_P (etype) && !(TREE_CODE (TYPE_SIZE (etype)) == INTEGER_CST && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)) { expr = copy_node (expr); TREE_TYPE (expr) = type; return expr; } break; case VECTOR_CST: /* If we are converting a VECTOR_CST to a mere type variant, just make a new one in the proper type. */ if (code == ecode && gnat_types_compatible_p (type, etype)) { expr = copy_node (expr); TREE_TYPE (expr) = type; return expr; } case CONSTRUCTOR: /* If we are converting a CONSTRUCTOR to a mere type variant, or to another padding type around the same type, just make a new one in the proper type. */ if (code == ecode && (gnat_types_compatible_p (type, etype) || (code == RECORD_TYPE && TYPE_PADDING_P (type) && TYPE_PADDING_P (etype) && TREE_TYPE (TYPE_FIELDS (type)) == TREE_TYPE (TYPE_FIELDS (etype))))) { expr = copy_node (expr); TREE_TYPE (expr) = type; CONSTRUCTOR_ELTS (expr) = vec_safe_copy (CONSTRUCTOR_ELTS (expr)); return expr; } /* Likewise for a conversion between original and packable version, or conversion between types of the same size and with the same list of fields, but we have to work harder to preserve type consistency. */ if (code == ecode && code == RECORD_TYPE && (TYPE_NAME (type) == TYPE_NAME (etype) || tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (etype)))) { vec<constructor_elt, va_gc> *e = CONSTRUCTOR_ELTS (expr); unsigned HOST_WIDE_INT len = vec_safe_length (e); vec<constructor_elt, va_gc> *v; vec_alloc (v, len); tree efield = TYPE_FIELDS (etype), field = TYPE_FIELDS (type); unsigned HOST_WIDE_INT idx; tree index, value; /* Whether we need to clear TREE_CONSTANT et al. on the output constructor when we convert in place. */ bool clear_constant = false; FOR_EACH_CONSTRUCTOR_ELT(e, idx, index, value) { /* Skip the missing fields in the CONSTRUCTOR. */ while (efield && field && !SAME_FIELD_P (efield, index)) { efield = DECL_CHAIN (efield); field = DECL_CHAIN (field); } /* The field must be the same. */ if (!(efield && field && SAME_FIELD_P (efield, field))) break; constructor_elt elt = {field, convert (TREE_TYPE (field), value)}; v->quick_push (elt); /* If packing has made this field a bitfield and the input value couldn't be emitted statically any more, we need to clear TREE_CONSTANT on our output. */ if (!clear_constant && TREE_CONSTANT (expr) && !CONSTRUCTOR_BITFIELD_P (efield) && CONSTRUCTOR_BITFIELD_P (field) && !initializer_constant_valid_for_bitfield_p (value)) clear_constant = true; efield = DECL_CHAIN (efield); field = DECL_CHAIN (field); } /* If we have been able to match and convert all the input fields to their output type, convert in place now. We'll fallback to a view conversion downstream otherwise. */ if (idx == len) { expr = copy_node (expr); TREE_TYPE (expr) = type; CONSTRUCTOR_ELTS (expr) = v; if (clear_constant) TREE_CONSTANT (expr) = TREE_STATIC (expr) = 0; return expr; } } /* Likewise for a conversion between array type and vector type with a compatible representative array. */ else if (code == VECTOR_TYPE && ecode == ARRAY_TYPE && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type), etype)) { vec<constructor_elt, va_gc> *e = CONSTRUCTOR_ELTS (expr); unsigned HOST_WIDE_INT len = vec_safe_length (e); vec<constructor_elt, va_gc> *v; unsigned HOST_WIDE_INT ix; tree value; /* Build a VECTOR_CST from a *constant* array constructor. */ if (TREE_CONSTANT (expr)) { bool constant_p = true; /* Iterate through elements and check if all constructor elements are *_CSTs. */ FOR_EACH_CONSTRUCTOR_VALUE (e, ix, value) if (!CONSTANT_CLASS_P (value)) { constant_p = false; break; } if (constant_p) return build_vector_from_ctor (type, CONSTRUCTOR_ELTS (expr)); } /* Otherwise, build a regular vector constructor. */ vec_alloc (v, len); FOR_EACH_CONSTRUCTOR_VALUE (e, ix, value) { constructor_elt elt = {NULL_TREE, value}; v->quick_push (elt); } expr = copy_node (expr); TREE_TYPE (expr) = type; CONSTRUCTOR_ELTS (expr) = v; return expr; } break; case UNCONSTRAINED_ARRAY_REF: /* First retrieve the underlying array. */ expr = maybe_unconstrained_array (expr); etype = TREE_TYPE (expr); ecode = TREE_CODE (etype); break; case VIEW_CONVERT_EXPR: { /* GCC 4.x is very sensitive to type consistency overall, and view conversions thus are very frequent. Even though just "convert"ing the inner operand to the output type is fine in most cases, it might expose unexpected input/output type mismatches in special circumstances so we avoid such recursive calls when we can. */ tree op0 = TREE_OPERAND (expr, 0); /* If we are converting back to the original type, we can just lift the input conversion. This is a common occurrence with switches back-and-forth amongst type variants. */ if (type == TREE_TYPE (op0)) return op0; /* Otherwise, if we're converting between two aggregate or vector types, we might be allowed to substitute the VIEW_CONVERT_EXPR target type in place or to just convert the inner expression. */ if ((AGGREGATE_TYPE_P (type) && AGGREGATE_TYPE_P (etype)) || (VECTOR_TYPE_P (type) && VECTOR_TYPE_P (etype))) { /* If we are converting between mere variants, we can just substitute the VIEW_CONVERT_EXPR in place. */ if (gnat_types_compatible_p (type, etype)) return build1 (VIEW_CONVERT_EXPR, type, op0); /* Otherwise, we may just bypass the input view conversion unless one of the types is a fat pointer, which is handled by specialized code below which relies on exact type matching. */ else if (!TYPE_IS_FAT_POINTER_P (type) && !TYPE_IS_FAT_POINTER_P (etype)) return convert (type, op0); } break; } default: break; } /* Check for converting to a pointer to an unconstrained array. */ if (TYPE_IS_FAT_POINTER_P (type) && !TYPE_IS_FAT_POINTER_P (etype)) return convert_to_fat_pointer (type, expr); /* If we are converting between two aggregate or vector types that are mere variants, just make a VIEW_CONVERT_EXPR. Likewise when we are converting to a vector type from its representative array type. */ else if ((code == ecode && (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)) && gnat_types_compatible_p (type, etype)) || (code == VECTOR_TYPE && ecode == ARRAY_TYPE && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type), etype))) return build1 (VIEW_CONVERT_EXPR, type, expr); /* If we are converting between tagged types, try to upcast properly. */ else if (ecode == RECORD_TYPE && code == RECORD_TYPE && TYPE_ALIGN_OK (etype) && TYPE_ALIGN_OK (type)) { tree child_etype = etype; do { tree field = TYPE_FIELDS (child_etype); if (DECL_NAME (field) == parent_name_id && TREE_TYPE (field) == type) return build_component_ref (expr, NULL_TREE, field, false); child_etype = TREE_TYPE (field); } while (TREE_CODE (child_etype) == RECORD_TYPE); } /* If we are converting from a smaller form of record type back to it, just make a VIEW_CONVERT_EXPR. But first pad the expression to have the same size on both sides. */ else if (ecode == RECORD_TYPE && code == RECORD_TYPE && smaller_form_type_p (etype, type)) { expr = convert (maybe_pad_type (etype, TYPE_SIZE (type), 0, Empty, false, false, false, true), expr); return build1 (VIEW_CONVERT_EXPR, type, expr); } /* In all other cases of related types, make a NOP_EXPR. */ else if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype)) return fold_convert (type, expr); switch (code) { case VOID_TYPE: return fold_build1 (CONVERT_EXPR, type, expr); case INTEGER_TYPE: if (TYPE_HAS_ACTUAL_BOUNDS_P (type) && (ecode == ARRAY_TYPE || ecode == UNCONSTRAINED_ARRAY_TYPE || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype)))) return unchecked_convert (type, expr, false); else if (TYPE_BIASED_REPRESENTATION_P (type)) return fold_convert (type, fold_build2 (MINUS_EXPR, TREE_TYPE (type), convert (TREE_TYPE (type), expr), convert (TREE_TYPE (type), TYPE_MIN_VALUE (type)))); /* ... fall through ... */ case ENUMERAL_TYPE: case BOOLEAN_TYPE: /* If we are converting an additive expression to an integer type with lower precision, be wary of the optimization that can be applied by convert_to_integer. There are 2 problematic cases: - if the first operand was originally of a biased type, because we could be recursively called to convert it to an intermediate type and thus rematerialize the additive operator endlessly, - if the expression contains a placeholder, because an intermediate conversion that changes the sign could be inserted and thus introduce an artificial overflow at compile time when the placeholder is substituted. */ if (code == INTEGER_TYPE && ecode == INTEGER_TYPE && TYPE_PRECISION (type) < TYPE_PRECISION (etype) && (TREE_CODE (expr) == PLUS_EXPR || TREE_CODE (expr) == MINUS_EXPR)) { tree op0 = get_unwidened (TREE_OPERAND (expr, 0), type); if ((TREE_CODE (TREE_TYPE (op0)) == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (TREE_TYPE (op0))) || CONTAINS_PLACEHOLDER_P (expr)) return build1 (NOP_EXPR, type, expr); } return fold (convert_to_integer (type, expr)); case POINTER_TYPE: case REFERENCE_TYPE: /* If converting between two thin pointers, adjust if needed to account for differing offsets from the base pointer, depending on whether there is a TYPE_UNCONSTRAINED_ARRAY attached to the record type. */ if (TYPE_IS_THIN_POINTER_P (etype) && TYPE_IS_THIN_POINTER_P (type)) { tree etype_pos = TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (etype)) != NULL_TREE ? byte_position (DECL_CHAIN (TYPE_FIELDS (TREE_TYPE (etype)))) : size_zero_node; tree type_pos = TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type)) != NULL_TREE ? byte_position (DECL_CHAIN (TYPE_FIELDS (TREE_TYPE (type)))) : size_zero_node; tree byte_diff = size_diffop (type_pos, etype_pos); expr = build1 (NOP_EXPR, type, expr); if (integer_zerop (byte_diff)) return expr; return build_binary_op (POINTER_PLUS_EXPR, type, expr, fold_convert (sizetype, byte_diff)); } /* If converting fat pointer to normal or thin pointer, get the pointer to the array and then convert it. */ if (TYPE_IS_FAT_POINTER_P (etype)) expr = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (etype), false); return fold (convert_to_pointer (type, expr)); case REAL_TYPE: return fold (convert_to_real (type, expr)); case RECORD_TYPE: if (TYPE_JUSTIFIED_MODULAR_P (type) && !AGGREGATE_TYPE_P (etype)) { vec<constructor_elt, va_gc> *v; vec_alloc (v, 1); CONSTRUCTOR_APPEND_ELT (v, TYPE_FIELDS (type), convert (TREE_TYPE (TYPE_FIELDS (type)), expr)); return gnat_build_constructor (type, v); } /* ... fall through ... */ case ARRAY_TYPE: /* In these cases, assume the front-end has validated the conversion. If the conversion is valid, it will be a bit-wise conversion, so it can be viewed as an unchecked conversion. */ return unchecked_convert (type, expr, false); case UNION_TYPE: /* This is a either a conversion between a tagged type and some subtype, which we have to mark as a UNION_TYPE because of overlapping fields or a conversion of an Unchecked_Union. */ return unchecked_convert (type, expr, false); case UNCONSTRAINED_ARRAY_TYPE: /* If the input is a VECTOR_TYPE, convert to the representative array type first. */ if (ecode == VECTOR_TYPE) { expr = convert (TYPE_REPRESENTATIVE_ARRAY (etype), expr); etype = TREE_TYPE (expr); ecode = TREE_CODE (etype); } /* If EXPR is a constrained array, take its address, convert it to a fat pointer, and then dereference it. Likewise if EXPR is a record containing both a template and a constrained array. Note that a record representing a justified modular type always represents a packed constrained array. */ if (ecode == ARRAY_TYPE || (ecode == INTEGER_TYPE && TYPE_HAS_ACTUAL_BOUNDS_P (etype)) || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype)) || (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype))) return build_unary_op (INDIRECT_REF, NULL_TREE, convert_to_fat_pointer (TREE_TYPE (type), build_unary_op (ADDR_EXPR, NULL_TREE, expr))); /* Do something very similar for converting one unconstrained array to another. */ else if (ecode == UNCONSTRAINED_ARRAY_TYPE) return build_unary_op (INDIRECT_REF, NULL_TREE, convert (TREE_TYPE (type), build_unary_op (ADDR_EXPR, NULL_TREE, expr))); else gcc_unreachable (); case COMPLEX_TYPE: return fold (convert_to_complex (type, expr)); default: gcc_unreachable (); } } /* Create an expression whose value is that of EXPR converted to the common index type, which is sizetype. EXPR is supposed to be in the base type of the GNAT index type. Calling it is equivalent to doing convert (sizetype, expr) but we try to distribute the type conversion with the knowledge that EXPR cannot overflow in its type. This is a best-effort approach and we fall back to the above expression as soon as difficulties are encountered. This is necessary to overcome issues that arise when the GNAT base index type and the GCC common index type (sizetype) don't have the same size, which is quite frequent on 64-bit architectures. In this case, and if the GNAT base index type is signed but the iteration type of the loop has been forced to unsigned, the loop scalar evolution engine cannot compute a simple evolution for the general induction variables associated with the array indices, because it will preserve the wrap-around semantics in the unsigned type of their "inner" part. As a result, many loop optimizations are blocked. The solution is to use a special (basic) induction variable that is at least as large as sizetype, and to express the aforementioned general induction variables in terms of this induction variable, eliminating the problematic intermediate truncation to the GNAT base index type. This is possible as long as the original expression doesn't overflow and if the middle-end hasn't introduced artificial overflows in the course of the various simplification it can make to the expression. */ tree convert_to_index_type (tree expr) { enum tree_code code = TREE_CODE (expr); tree type = TREE_TYPE (expr); /* If the type is unsigned, overflow is allowed so we cannot be sure that EXPR doesn't overflow. Keep it simple if optimization is disabled. */ if (TYPE_UNSIGNED (type) || !optimize) return convert (sizetype, expr); switch (code) { case VAR_DECL: /* The main effect of the function: replace a loop parameter with its associated special induction variable. */ if (DECL_LOOP_PARM_P (expr) && DECL_INDUCTION_VAR (expr)) expr = DECL_INDUCTION_VAR (expr); break; CASE_CONVERT: { tree otype = TREE_TYPE (TREE_OPERAND (expr, 0)); /* Bail out as soon as we suspect some sort of type frobbing. */ if (TYPE_PRECISION (type) != TYPE_PRECISION (otype) || TYPE_UNSIGNED (type) != TYPE_UNSIGNED (otype)) break; } /* ... fall through ... */ case NON_LVALUE_EXPR: return fold_build1 (code, sizetype, convert_to_index_type (TREE_OPERAND (expr, 0))); case PLUS_EXPR: case MINUS_EXPR: case MULT_EXPR: return fold_build2 (code, sizetype, convert_to_index_type (TREE_OPERAND (expr, 0)), convert_to_index_type (TREE_OPERAND (expr, 1))); case COMPOUND_EXPR: return fold_build2 (code, sizetype, TREE_OPERAND (expr, 0), convert_to_index_type (TREE_OPERAND (expr, 1))); case COND_EXPR: return fold_build3 (code, sizetype, TREE_OPERAND (expr, 0), convert_to_index_type (TREE_OPERAND (expr, 1)), convert_to_index_type (TREE_OPERAND (expr, 2))); default: break; } return convert (sizetype, expr); } /* Remove all conversions that are done in EXP. This includes converting from a padded type or to a justified modular type. If TRUE_ADDRESS is true, always return the address of the containing object even if the address is not bit-aligned. */ tree remove_conversions (tree exp, bool true_address) { switch (TREE_CODE (exp)) { case CONSTRUCTOR: if (true_address && TREE_CODE (TREE_TYPE (exp)) == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (exp))) return remove_conversions (CONSTRUCTOR_ELT (exp, 0)->value, true); break; case COMPONENT_REF: if (TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (exp, 0)))) return remove_conversions (TREE_OPERAND (exp, 0), true_address); break; CASE_CONVERT: case VIEW_CONVERT_EXPR: case NON_LVALUE_EXPR: return remove_conversions (TREE_OPERAND (exp, 0), true_address); default: break; } return exp; } /* If EXP's type is an UNCONSTRAINED_ARRAY_TYPE, return an expression that refers to the underlying array. If it has TYPE_CONTAINS_TEMPLATE_P, likewise return an expression pointing to the underlying array. */ tree maybe_unconstrained_array (tree exp) { enum tree_code code = TREE_CODE (exp); tree type = TREE_TYPE (exp); switch (TREE_CODE (type)) { case UNCONSTRAINED_ARRAY_TYPE: if (code == UNCONSTRAINED_ARRAY_REF) { const bool read_only = TREE_READONLY (exp); const bool no_trap = TREE_THIS_NOTRAP (exp); exp = TREE_OPERAND (exp, 0); type = TREE_TYPE (exp); if (TREE_CODE (exp) == COND_EXPR) { tree op1 = build_unary_op (INDIRECT_REF, NULL_TREE, build_component_ref (TREE_OPERAND (exp, 1), NULL_TREE, TYPE_FIELDS (type), false)); tree op2 = build_unary_op (INDIRECT_REF, NULL_TREE, build_component_ref (TREE_OPERAND (exp, 2), NULL_TREE, TYPE_FIELDS (type), false)); exp = build3 (COND_EXPR, TREE_TYPE (TREE_TYPE (TYPE_FIELDS (type))), TREE_OPERAND (exp, 0), op1, op2); } else { exp = build_unary_op (INDIRECT_REF, NULL_TREE, build_component_ref (exp, NULL_TREE, TYPE_FIELDS (type), false)); TREE_READONLY (exp) = read_only; TREE_THIS_NOTRAP (exp) = no_trap; } } else if (code == NULL_EXPR) exp = build1 (NULL_EXPR, TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (type)))), TREE_OPERAND (exp, 0)); break; case RECORD_TYPE: /* If this is a padded type and it contains a template, convert to the unpadded type first. */ if (TYPE_PADDING_P (type) && TREE_CODE (TREE_TYPE (TYPE_FIELDS (type))) == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (TYPE_FIELDS (type)))) { exp = convert (TREE_TYPE (TYPE_FIELDS (type)), exp); type = TREE_TYPE (exp); } if (TYPE_CONTAINS_TEMPLATE_P (type)) { exp = build_simple_component_ref (exp, NULL_TREE, DECL_CHAIN (TYPE_FIELDS (type)), false); /* If the array type is padded, convert to the unpadded type. */ if (exp && TYPE_IS_PADDING_P (TREE_TYPE (exp))) exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp); } break; default: break; } return exp; } /* Return true if EXPR is an expression that can be folded as an operand of a VIEW_CONVERT_EXPR. See ada-tree.h for a complete rationale. */ static bool can_fold_for_view_convert_p (tree expr) { tree t1, t2; /* The folder will fold NOP_EXPRs between integral types with the same precision (in the middle-end's sense). We cannot allow it if the types don't have the same precision in the Ada sense as well. */ if (TREE_CODE (expr) != NOP_EXPR) return true; t1 = TREE_TYPE (expr); t2 = TREE_TYPE (TREE_OPERAND (expr, 0)); /* Defer to the folder for non-integral conversions. */ if (!(INTEGRAL_TYPE_P (t1) && INTEGRAL_TYPE_P (t2))) return true; /* Only fold conversions that preserve both precisions. */ if (TYPE_PRECISION (t1) == TYPE_PRECISION (t2) && operand_equal_p (rm_size (t1), rm_size (t2), 0)) return true; return false; } /* Return an expression that does an unchecked conversion of EXPR to TYPE. If NOTRUNC_P is true, truncation operations should be suppressed. Special care is required with (source or target) integral types whose precision is not equal to their size, to make sure we fetch or assign the value bits whose location might depend on the endianness, e.g. Rmsize : constant := 8; subtype Int is Integer range 0 .. 2 ** Rmsize - 1; type Bit_Array is array (1 .. Rmsize) of Boolean; pragma Pack (Bit_Array); function To_Bit_Array is new Unchecked_Conversion (Int, Bit_Array); Value : Int := 2#1000_0001#; Vbits : Bit_Array := To_Bit_Array (Value); we expect the 8 bits at Vbits'Address to always contain Value, while their original location depends on the endianness, at Value'Address on a little-endian architecture but not on a big-endian one. */ tree unchecked_convert (tree type, tree expr, bool notrunc_p) { tree etype = TREE_TYPE (expr); enum tree_code ecode = TREE_CODE (etype); enum tree_code code = TREE_CODE (type); tree tem; int c; /* If the expression is already of the right type, we are done. */ if (etype == type) return expr; /* If both types are integral just do a normal conversion. Likewise for a conversion to an unconstrained array. */ if (((INTEGRAL_TYPE_P (type) || (POINTER_TYPE_P (type) && !TYPE_IS_THIN_POINTER_P (type)) || (code == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (type))) && (INTEGRAL_TYPE_P (etype) || (POINTER_TYPE_P (etype) && !TYPE_IS_THIN_POINTER_P (etype)) || (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)))) || code == UNCONSTRAINED_ARRAY_TYPE) { if (ecode == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (etype)) { tree ntype = copy_type (etype); TYPE_BIASED_REPRESENTATION_P (ntype) = 0; TYPE_MAIN_VARIANT (ntype) = ntype; expr = build1 (NOP_EXPR, ntype, expr); } if (code == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (type)) { tree rtype = copy_type (type); TYPE_BIASED_REPRESENTATION_P (rtype) = 0; TYPE_MAIN_VARIANT (rtype) = rtype; expr = convert (rtype, expr); expr = build1 (NOP_EXPR, type, expr); } else expr = convert (type, expr); } /* If we are converting to an integral type whose precision is not equal to its size, first unchecked convert to a record type that contains a field of the given precision. Then extract the result from the field. There is a subtlety if the source type is an aggregate type with reverse storage order because its representation is not contiguous in the native storage order, i.e. a direct unchecked conversion to an integral type with N bits of precision cannot read the first N bits of the aggregate type. To overcome it, we do an unchecked conversion to an integral type with reverse storage order and return the resulting value. This also ensures that the result of the unchecked conversion doesn't depend on the endianness of the target machine, but only on the storage order of the aggregate type. Finally, for the sake of consistency, we do the unchecked conversion to an integral type with reverse storage order as soon as the source type is an aggregate type with reverse storage order, even if there are no considerations of precision or size involved. */ else if (INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type) && (0 != compare_tree_int (TYPE_RM_SIZE (type), GET_MODE_BITSIZE (TYPE_MODE (type))) || (AGGREGATE_TYPE_P (etype) && TYPE_REVERSE_STORAGE_ORDER (etype)))) { tree rec_type = make_node (RECORD_TYPE); unsigned HOST_WIDE_INT prec = TREE_INT_CST_LOW (TYPE_RM_SIZE (type)); tree field_type, field; if (AGGREGATE_TYPE_P (etype)) TYPE_REVERSE_STORAGE_ORDER (rec_type) = TYPE_REVERSE_STORAGE_ORDER (etype); if (TYPE_UNSIGNED (type)) field_type = make_unsigned_type (prec); else field_type = make_signed_type (prec); SET_TYPE_RM_SIZE (field_type, TYPE_RM_SIZE (type)); field = create_field_decl (get_identifier ("OBJ"), field_type, rec_type, NULL_TREE, bitsize_zero_node, 1, 0); finish_record_type (rec_type, field, 1, false); expr = unchecked_convert (rec_type, expr, notrunc_p); expr = build_component_ref (expr, NULL_TREE, field, false); expr = fold_build1 (NOP_EXPR, type, expr); } /* Similarly if we are converting from an integral type whose precision is not equal to its size, first copy into a field of the given precision and unchecked convert the record type. The same considerations as above apply if the target type is an aggregate type with reverse storage order and we also proceed similarly. */ else if (INTEGRAL_TYPE_P (etype) && TYPE_RM_SIZE (etype) && (0 != compare_tree_int (TYPE_RM_SIZE (etype), GET_MODE_BITSIZE (TYPE_MODE (etype))) || (AGGREGATE_TYPE_P (type) && TYPE_REVERSE_STORAGE_ORDER (type)))) { tree rec_type = make_node (RECORD_TYPE); unsigned HOST_WIDE_INT prec = TREE_INT_CST_LOW (TYPE_RM_SIZE (etype)); vec<constructor_elt, va_gc> *v; vec_alloc (v, 1); tree field_type, field; if (AGGREGATE_TYPE_P (type)) TYPE_REVERSE_STORAGE_ORDER (rec_type) = TYPE_REVERSE_STORAGE_ORDER (type); if (TYPE_UNSIGNED (etype)) field_type = make_unsigned_type (prec); else field_type = make_signed_type (prec); SET_TYPE_RM_SIZE (field_type, TYPE_RM_SIZE (etype)); field = create_field_decl (get_identifier ("OBJ"), field_type, rec_type, NULL_TREE, bitsize_zero_node, 1, 0); finish_record_type (rec_type, field, 1, false); expr = fold_build1 (NOP_EXPR, field_type, expr); CONSTRUCTOR_APPEND_ELT (v, field, expr); expr = gnat_build_constructor (rec_type, v); expr = unchecked_convert (type, expr, notrunc_p); } /* If we are converting from a scalar type to a type with a different size, we need to pad to have the same size on both sides. ??? We cannot do it unconditionally because unchecked conversions are used liberally by the front-end to implement polymorphism, e.g. in: S191s : constant ada__tags__addr_ptr := ada__tags__addr_ptr!(S190s); return p___size__4 (p__object!(S191s.all)); so we skip all expressions that are references. */ else if (!REFERENCE_CLASS_P (expr) && !AGGREGATE_TYPE_P (etype) && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST && (c = tree_int_cst_compare (TYPE_SIZE (etype), TYPE_SIZE (type)))) { if (c < 0) { expr = convert (maybe_pad_type (etype, TYPE_SIZE (type), 0, Empty, false, false, false, true), expr); expr = unchecked_convert (type, expr, notrunc_p); } else { tree rec_type = maybe_pad_type (type, TYPE_SIZE (etype), 0, Empty, false, false, false, true); expr = unchecked_convert (rec_type, expr, notrunc_p); expr = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (rec_type), false); } } /* We have a special case when we are converting between two unconstrained array types. In that case, take the address, convert the fat pointer types, and dereference. */ else if (ecode == code && code == UNCONSTRAINED_ARRAY_TYPE) expr = build_unary_op (INDIRECT_REF, NULL_TREE, build1 (VIEW_CONVERT_EXPR, TREE_TYPE (type), build_unary_op (ADDR_EXPR, NULL_TREE, expr))); /* Another special case is when we are converting to a vector type from its representative array type; this a regular conversion. */ else if (code == VECTOR_TYPE && ecode == ARRAY_TYPE && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type), etype)) expr = convert (type, expr); /* And, if the array type is not the representative, we try to build an intermediate vector type of which the array type is the representative and to do the unchecked conversion between the vector types, in order to enable further simplifications in the middle-end. */ else if (code == VECTOR_TYPE && ecode == ARRAY_TYPE && (tem = build_vector_type_for_array (etype, NULL_TREE))) { expr = convert (tem, expr); return unchecked_convert (type, expr, notrunc_p); } /* If we are converting a CONSTRUCTOR to a more aligned RECORD_TYPE, bump the alignment of the CONSTRUCTOR to speed up the copy operation. */ else if (TREE_CODE (expr) == CONSTRUCTOR && code == RECORD_TYPE && TYPE_ALIGN (etype) < TYPE_ALIGN (type)) { expr = convert (maybe_pad_type (etype, NULL_TREE, TYPE_ALIGN (type), Empty, false, false, false, true), expr); return unchecked_convert (type, expr, notrunc_p); } /* Otherwise, just build a VIEW_CONVERT_EXPR of the expression. */ else { expr = maybe_unconstrained_array (expr); etype = TREE_TYPE (expr); ecode = TREE_CODE (etype); if (can_fold_for_view_convert_p (expr)) expr = fold_build1 (VIEW_CONVERT_EXPR, type, expr); else expr = build1 (VIEW_CONVERT_EXPR, type, expr); } /* If the result is an integral type whose precision is not equal to its size, sign- or zero-extend the result. We need not do this if the input is an integral type of the same precision and signedness or if the output is a biased type or if both the input and output are unsigned. */ if (!notrunc_p && INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type) && !(code == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (type)) && 0 != compare_tree_int (TYPE_RM_SIZE (type), GET_MODE_BITSIZE (TYPE_MODE (type))) && !(INTEGRAL_TYPE_P (etype) && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (etype) && operand_equal_p (TYPE_RM_SIZE (type), (TYPE_RM_SIZE (etype) != 0 ? TYPE_RM_SIZE (etype) : TYPE_SIZE (etype)), 0)) && !(TYPE_UNSIGNED (type) && TYPE_UNSIGNED (etype))) { tree base_type = gnat_type_for_mode (TYPE_MODE (type), TYPE_UNSIGNED (type)); tree shift_expr = convert (base_type, size_binop (MINUS_EXPR, bitsize_int (GET_MODE_BITSIZE (TYPE_MODE (type))), TYPE_RM_SIZE (type))); expr = convert (type, build_binary_op (RSHIFT_EXPR, base_type, build_binary_op (LSHIFT_EXPR, base_type, convert (base_type, expr), shift_expr), shift_expr)); } /* An unchecked conversion should never raise Constraint_Error. The code below assumes that GCC's conversion routines overflow the same way that the underlying hardware does. This is probably true. In the rare case when it is false, we can rely on the fact that such conversions are erroneous anyway. */ if (TREE_CODE (expr) == INTEGER_CST) TREE_OVERFLOW (expr) = 0; /* If the sizes of the types differ and this is an VIEW_CONVERT_EXPR, show no longer constant. */ if (TREE_CODE (expr) == VIEW_CONVERT_EXPR && !operand_equal_p (TYPE_SIZE_UNIT (type), TYPE_SIZE_UNIT (etype), OEP_ONLY_CONST)) TREE_CONSTANT (expr) = 0; return expr; } /* Return the appropriate GCC tree code for the specified GNAT_TYPE, the latter being a record type as predicated by Is_Record_Type. */ enum tree_code tree_code_for_record_type (Entity_Id gnat_type) { Node_Id component_list, component; /* Return UNION_TYPE if it's an Unchecked_Union whose non-discriminant fields are all in the variant part. Otherwise, return RECORD_TYPE. */ if (!Is_Unchecked_Union (gnat_type)) return RECORD_TYPE; gnat_type = Implementation_Base_Type (gnat_type); component_list = Component_List (Type_Definition (Declaration_Node (gnat_type))); for (component = First_Non_Pragma (Component_Items (component_list)); Present (component); component = Next_Non_Pragma (component)) if (Ekind (Defining_Entity (component)) == E_Component) return RECORD_TYPE; return UNION_TYPE; } /* Return true if GNAT_TYPE is a "double" floating-point type, i.e. whose size is equal to 64 bits, or an array of such a type. Set ALIGN_CLAUSE according to the presence of an alignment clause on the type or, if it is an array, on the component type. */ bool is_double_float_or_array (Entity_Id gnat_type, bool *align_clause) { gnat_type = Underlying_Type (gnat_type); *align_clause = Present (Alignment_Clause (gnat_type)); if (Is_Array_Type (gnat_type)) { gnat_type = Underlying_Type (Component_Type (gnat_type)); if (Present (Alignment_Clause (gnat_type))) *align_clause = true; } if (!Is_Floating_Point_Type (gnat_type)) return false; if (UI_To_Int (Esize (gnat_type)) != 64) return false; return true; } /* Return true if GNAT_TYPE is a "double" or larger scalar type, i.e. whose size is greater or equal to 64 bits, or an array of such a type. Set ALIGN_CLAUSE according to the presence of an alignment clause on the type or, if it is an array, on the component type. */ bool is_double_scalar_or_array (Entity_Id gnat_type, bool *align_clause) { gnat_type = Underlying_Type (gnat_type); *align_clause = Present (Alignment_Clause (gnat_type)); if (Is_Array_Type (gnat_type)) { gnat_type = Underlying_Type (Component_Type (gnat_type)); if (Present (Alignment_Clause (gnat_type))) *align_clause = true; } if (!Is_Scalar_Type (gnat_type)) return false; if (UI_To_Int (Esize (gnat_type)) < 64) return false; return true; } /* Return true if GNU_TYPE is suitable as the type of a non-aliased component of an aggregate type. */ bool type_for_nonaliased_component_p (tree gnu_type) { /* If the type is passed by reference, we may have pointers to the component so it cannot be made non-aliased. */ if (must_pass_by_ref (gnu_type) || default_pass_by_ref (gnu_type)) return false; /* We used to say that any component of aggregate type is aliased because the front-end may take 'Reference of it. The front-end has been enhanced in the meantime so as to use a renaming instead in most cases, but the back-end can probably take the address of such a component too so we go for the conservative stance. For instance, we might need the address of any array type, even if normally passed by copy, to construct a fat pointer if the component is used as an actual for an unconstrained formal. Likewise for record types: even if a specific record subtype is passed by copy, the parent type might be passed by ref (e.g. if it's of variable size) and we might take the address of a child component to pass to a parent formal. We have no way to check for such conditions here. */ if (AGGREGATE_TYPE_P (gnu_type)) return false; return true; } /* Return true if TYPE is a smaller form of ORIG_TYPE. */ bool smaller_form_type_p (tree type, tree orig_type) { tree size, osize; /* We're not interested in variants here. */ if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig_type)) return false; /* Like a variant, a packable version keeps the original TYPE_NAME. */ if (TYPE_NAME (type) != TYPE_NAME (orig_type)) return false; size = TYPE_SIZE (type); osize = TYPE_SIZE (orig_type); if (!(TREE_CODE (size) == INTEGER_CST && TREE_CODE (osize) == INTEGER_CST)) return false; return tree_int_cst_lt (size, osize) != 0; } /* Perform final processing on global declarations. */ static GTY (()) tree dummy_global; void gnat_write_global_declarations (void) { unsigned int i; tree iter; /* If we have declared types as used at the global level, insert them in the global hash table. We use a dummy variable for this purpose, but we need to build it unconditionally to avoid -fcompare-debug issues. */ if (first_global_object_name) { struct varpool_node *node; char *label; ASM_FORMAT_PRIVATE_NAME (label, first_global_object_name, 0); dummy_global = build_decl (BUILTINS_LOCATION, VAR_DECL, get_identifier (label), void_type_node); DECL_HARD_REGISTER (dummy_global) = 1; TREE_STATIC (dummy_global) = 1; node = varpool_node::get_create (dummy_global); node->definition = 1; node->force_output = 1; if (types_used_by_cur_var_decl) while (!types_used_by_cur_var_decl->is_empty ()) { tree t = types_used_by_cur_var_decl->pop (); types_used_by_var_decl_insert (t, dummy_global); } } /* Output debug information for all global type declarations first. This ensures that global types whose compilation hasn't been finalized yet, for example pointers to Taft amendment types, have their compilation finalized in the right context. */ FOR_EACH_VEC_SAFE_ELT (global_decls, i, iter) if (TREE_CODE (iter) == TYPE_DECL && !DECL_IGNORED_P (iter)) debug_hooks->type_decl (iter, false); /* Then output the global variables. We need to do that after the debug information for global types is emitted so that they are finalized. */ FOR_EACH_VEC_SAFE_ELT (global_decls, i, iter) if (TREE_CODE (iter) == VAR_DECL) rest_of_decl_compilation (iter, true, 0); } /* ************************************************************************ * * GCC builtins support * * ************************************************************************ */ /* The general scheme is fairly simple: For each builtin function/type to be declared, gnat_install_builtins calls internal facilities which eventually get to gnat_pushdecl, which in turn tracks the so declared builtin function decls in the 'builtin_decls' global datastructure. When an Intrinsic subprogram declaration is processed, we search this global datastructure to retrieve the associated BUILT_IN DECL node. */ /* Search the chain of currently available builtin declarations for a node corresponding to function NAME (an IDENTIFIER_NODE). Return the first node found, if any, or NULL_TREE otherwise. */ tree builtin_decl_for (tree name) { unsigned i; tree decl; FOR_EACH_VEC_SAFE_ELT (builtin_decls, i, decl) if (DECL_NAME (decl) == name) return decl; return NULL_TREE; } /* The code below eventually exposes gnat_install_builtins, which declares the builtin types and functions we might need, either internally or as user accessible facilities. ??? This is a first implementation shot, still in rough shape. It is heavily inspired from the "C" family implementation, with chunks copied verbatim from there. Two obvious improvement candidates are: o Use a more efficient name/decl mapping scheme o Devise a middle-end infrastructure to avoid having to copy pieces between front-ends. */ /* ----------------------------------------------------------------------- * * BUILTIN ELEMENTARY TYPES * * ----------------------------------------------------------------------- */ /* Standard data types to be used in builtin argument declarations. */ enum c_tree_index { CTI_SIGNED_SIZE_TYPE, /* For format checking only. */ CTI_STRING_TYPE, CTI_CONST_STRING_TYPE, CTI_MAX }; static tree c_global_trees[CTI_MAX]; #define signed_size_type_node c_global_trees[CTI_SIGNED_SIZE_TYPE] #define string_type_node c_global_trees[CTI_STRING_TYPE] #define const_string_type_node c_global_trees[CTI_CONST_STRING_TYPE] /* ??? In addition some attribute handlers, we currently don't support a (small) number of builtin-types, which in turns inhibits support for a number of builtin functions. */ #define wint_type_node void_type_node #define intmax_type_node void_type_node #define uintmax_type_node void_type_node /* Build the void_list_node (void_type_node having been created). */ static tree build_void_list_node (void) { tree t = build_tree_list (NULL_TREE, void_type_node); return t; } /* Used to help initialize the builtin-types.def table. When a type of the correct size doesn't exist, use error_mark_node instead of NULL. The later results in segfaults even when a decl using the type doesn't get invoked. */ static tree builtin_type_for_size (int size, bool unsignedp) { tree type = gnat_type_for_size (size, unsignedp); return type ? type : error_mark_node; } /* Build/push the elementary type decls that builtin functions/types will need. */ static void install_builtin_elementary_types (void) { signed_size_type_node = gnat_signed_type (size_type_node); pid_type_node = integer_type_node; void_list_node = build_void_list_node (); string_type_node = build_pointer_type (char_type_node); const_string_type_node = build_pointer_type (build_qualified_type (char_type_node, TYPE_QUAL_CONST)); } /* ----------------------------------------------------------------------- * * BUILTIN FUNCTION TYPES * * ----------------------------------------------------------------------- */ /* Now, builtin function types per se. */ enum c_builtin_type { #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME, #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME, #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME, #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME, #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME, #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME, #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME, #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6) NAME, #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7) NAME, #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7, ARG8) NAME, #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7, ARG8, ARG9) NAME, #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7, ARG8, ARG9, ARG10) NAME, #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME, #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME, #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME, #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME, #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME, #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME, #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \ NAME, #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6) NAME, #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7) NAME, #define DEF_POINTER_TYPE(NAME, TYPE) NAME, #include "builtin-types.def" #undef DEF_PRIMITIVE_TYPE #undef DEF_FUNCTION_TYPE_0 #undef DEF_FUNCTION_TYPE_1 #undef DEF_FUNCTION_TYPE_2 #undef DEF_FUNCTION_TYPE_3 #undef DEF_FUNCTION_TYPE_4 #undef DEF_FUNCTION_TYPE_5 #undef DEF_FUNCTION_TYPE_6 #undef DEF_FUNCTION_TYPE_7 #undef DEF_FUNCTION_TYPE_8 #undef DEF_FUNCTION_TYPE_9 #undef DEF_FUNCTION_TYPE_10 #undef DEF_FUNCTION_TYPE_11 #undef DEF_FUNCTION_TYPE_VAR_0 #undef DEF_FUNCTION_TYPE_VAR_1 #undef DEF_FUNCTION_TYPE_VAR_2 #undef DEF_FUNCTION_TYPE_VAR_3 #undef DEF_FUNCTION_TYPE_VAR_4 #undef DEF_FUNCTION_TYPE_VAR_5 #undef DEF_FUNCTION_TYPE_VAR_6 #undef DEF_FUNCTION_TYPE_VAR_7 #undef DEF_POINTER_TYPE BT_LAST }; typedef enum c_builtin_type builtin_type; /* A temporary array used in communication with def_fn_type. */ static GTY(()) tree builtin_types[(int) BT_LAST + 1]; /* A helper function for install_builtin_types. Build function type for DEF with return type RET and N arguments. If VAR is true, then the function should be variadic after those N arguments. Takes special care not to ICE if any of the types involved are error_mark_node, which indicates that said type is not in fact available (see builtin_type_for_size). In which case the function type as a whole should be error_mark_node. */ static void def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...) { tree t; tree *args = XALLOCAVEC (tree, n); va_list list; int i; va_start (list, n); for (i = 0; i < n; ++i) { builtin_type a = (builtin_type) va_arg (list, int); t = builtin_types[a]; if (t == error_mark_node) goto egress; args[i] = t; } t = builtin_types[ret]; if (t == error_mark_node) goto egress; if (var) t = build_varargs_function_type_array (t, n, args); else t = build_function_type_array (t, n, args); egress: builtin_types[def] = t; va_end (list); } /* Build the builtin function types and install them in the builtin_types array for later use in builtin function decls. */ static void install_builtin_function_types (void) { tree va_list_ref_type_node; tree va_list_arg_type_node; if (TREE_CODE (va_list_type_node) == ARRAY_TYPE) { va_list_arg_type_node = va_list_ref_type_node = build_pointer_type (TREE_TYPE (va_list_type_node)); } else { va_list_arg_type_node = va_list_type_node; va_list_ref_type_node = build_reference_type (va_list_type_node); } #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \ builtin_types[ENUM] = VALUE; #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \ def_fn_type (ENUM, RETURN, 0, 0); #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \ def_fn_type (ENUM, RETURN, 0, 1, ARG1); #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \ def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2); #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \ def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3); #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \ def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4); #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \ def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5); #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6) \ def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6); #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7) \ def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7); #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7, ARG8) \ def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \ ARG7, ARG8); #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7, ARG8, ARG9) \ def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \ ARG7, ARG8, ARG9); #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5,\ ARG6, ARG7, ARG8, ARG9, ARG10) \ def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \ ARG7, ARG8, ARG9, ARG10); #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5,\ ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) \ def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \ ARG7, ARG8, ARG9, ARG10, ARG11); #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \ def_fn_type (ENUM, RETURN, 1, 0); #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \ def_fn_type (ENUM, RETURN, 1, 1, ARG1); #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \ def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2); #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \ def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3); #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \ def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4); #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \ def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5); #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6) \ def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6); #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \ ARG6, ARG7) \ def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7); #define DEF_POINTER_TYPE(ENUM, TYPE) \ builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]); #include "builtin-types.def" #undef DEF_PRIMITIVE_TYPE #undef DEF_FUNCTION_TYPE_0 #undef DEF_FUNCTION_TYPE_1 #undef DEF_FUNCTION_TYPE_2 #undef DEF_FUNCTION_TYPE_3 #undef DEF_FUNCTION_TYPE_4 #undef DEF_FUNCTION_TYPE_5 #undef DEF_FUNCTION_TYPE_6 #undef DEF_FUNCTION_TYPE_7 #undef DEF_FUNCTION_TYPE_8 #undef DEF_FUNCTION_TYPE_9 #undef DEF_FUNCTION_TYPE_10 #undef DEF_FUNCTION_TYPE_11 #undef DEF_FUNCTION_TYPE_VAR_0 #undef DEF_FUNCTION_TYPE_VAR_1 #undef DEF_FUNCTION_TYPE_VAR_2 #undef DEF_FUNCTION_TYPE_VAR_3 #undef DEF_FUNCTION_TYPE_VAR_4 #undef DEF_FUNCTION_TYPE_VAR_5 #undef DEF_FUNCTION_TYPE_VAR_6 #undef DEF_FUNCTION_TYPE_VAR_7 #undef DEF_POINTER_TYPE builtin_types[(int) BT_LAST] = NULL_TREE; } /* ----------------------------------------------------------------------- * * BUILTIN ATTRIBUTES * * ----------------------------------------------------------------------- */ enum built_in_attribute { #define DEF_ATTR_NULL_TREE(ENUM) ENUM, #define DEF_ATTR_INT(ENUM, VALUE) ENUM, #define DEF_ATTR_STRING(ENUM, VALUE) ENUM, #define DEF_ATTR_IDENT(ENUM, STRING) ENUM, #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM, #include "builtin-attrs.def" #undef DEF_ATTR_NULL_TREE #undef DEF_ATTR_INT #undef DEF_ATTR_STRING #undef DEF_ATTR_IDENT #undef DEF_ATTR_TREE_LIST ATTR_LAST }; static GTY(()) tree built_in_attributes[(int) ATTR_LAST]; static void install_builtin_attributes (void) { /* Fill in the built_in_attributes array. */ #define DEF_ATTR_NULL_TREE(ENUM) \ built_in_attributes[(int) ENUM] = NULL_TREE; #define DEF_ATTR_INT(ENUM, VALUE) \ built_in_attributes[(int) ENUM] = build_int_cst (NULL_TREE, VALUE); #define DEF_ATTR_STRING(ENUM, VALUE) \ built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE); #define DEF_ATTR_IDENT(ENUM, STRING) \ built_in_attributes[(int) ENUM] = get_identifier (STRING); #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \ built_in_attributes[(int) ENUM] \ = tree_cons (built_in_attributes[(int) PURPOSE], \ built_in_attributes[(int) VALUE], \ built_in_attributes[(int) CHAIN]); #include "builtin-attrs.def" #undef DEF_ATTR_NULL_TREE #undef DEF_ATTR_INT #undef DEF_ATTR_STRING #undef DEF_ATTR_IDENT #undef DEF_ATTR_TREE_LIST } /* Handle a "const" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_const_attribute (tree *node, tree ARG_UNUSED (name), tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *no_add_attrs) { if (TREE_CODE (*node) == FUNCTION_DECL) TREE_READONLY (*node) = 1; else *no_add_attrs = true; return NULL_TREE; } /* Handle a "nothrow" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_nothrow_attribute (tree *node, tree ARG_UNUSED (name), tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *no_add_attrs) { if (TREE_CODE (*node) == FUNCTION_DECL) TREE_NOTHROW (*node) = 1; else *no_add_attrs = true; return NULL_TREE; } /* Handle a "pure" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_pure_attribute (tree *node, tree name, tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *no_add_attrs) { if (TREE_CODE (*node) == FUNCTION_DECL) DECL_PURE_P (*node) = 1; /* TODO: support types. */ else { warning (OPT_Wattributes, "%qs attribute ignored", IDENTIFIER_POINTER (name)); *no_add_attrs = true; } return NULL_TREE; } /* Handle a "no vops" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_novops_attribute (tree *node, tree ARG_UNUSED (name), tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *ARG_UNUSED (no_add_attrs)) { gcc_assert (TREE_CODE (*node) == FUNCTION_DECL); DECL_IS_NOVOPS (*node) = 1; return NULL_TREE; } /* Helper for nonnull attribute handling; fetch the operand number from the attribute argument list. */ static bool get_nonnull_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp) { /* Verify the arg number is a constant. */ if (!tree_fits_uhwi_p (arg_num_expr)) return false; *valp = TREE_INT_CST_LOW (arg_num_expr); return true; } /* Handle the "nonnull" attribute. */ static tree handle_nonnull_attribute (tree *node, tree ARG_UNUSED (name), tree args, int ARG_UNUSED (flags), bool *no_add_attrs) { tree type = *node; unsigned HOST_WIDE_INT attr_arg_num; /* If no arguments are specified, all pointer arguments should be non-null. Verify a full prototype is given so that the arguments will have the correct types when we actually check them later. */ if (!args) { if (!prototype_p (type)) { error ("nonnull attribute without arguments on a non-prototype"); *no_add_attrs = true; } return NULL_TREE; } /* Argument list specified. Verify that each argument number references a pointer argument. */ for (attr_arg_num = 1; args; args = TREE_CHAIN (args)) { unsigned HOST_WIDE_INT arg_num = 0, ck_num; if (!get_nonnull_operand (TREE_VALUE (args), &arg_num)) { error ("nonnull argument has invalid operand number (argument %lu)", (unsigned long) attr_arg_num); *no_add_attrs = true; return NULL_TREE; } if (prototype_p (type)) { function_args_iterator iter; tree argument; function_args_iter_init (&iter, type); for (ck_num = 1; ; ck_num++, function_args_iter_next (&iter)) { argument = function_args_iter_cond (&iter); if (!argument || ck_num == arg_num) break; } if (!argument || TREE_CODE (argument) == VOID_TYPE) { error ("nonnull argument with out-of-range operand number " "(argument %lu, operand %lu)", (unsigned long) attr_arg_num, (unsigned long) arg_num); *no_add_attrs = true; return NULL_TREE; } if (TREE_CODE (argument) != POINTER_TYPE) { error ("nonnull argument references non-pointer operand " "(argument %lu, operand %lu)", (unsigned long) attr_arg_num, (unsigned long) arg_num); *no_add_attrs = true; return NULL_TREE; } } } return NULL_TREE; } /* Handle a "sentinel" attribute. */ static tree handle_sentinel_attribute (tree *node, tree name, tree args, int ARG_UNUSED (flags), bool *no_add_attrs) { if (!prototype_p (*node)) { warning (OPT_Wattributes, "%qs attribute requires prototypes with named arguments", IDENTIFIER_POINTER (name)); *no_add_attrs = true; } else { if (!stdarg_p (*node)) { warning (OPT_Wattributes, "%qs attribute only applies to variadic functions", IDENTIFIER_POINTER (name)); *no_add_attrs = true; } } if (args) { tree position = TREE_VALUE (args); if (TREE_CODE (position) != INTEGER_CST) { warning (0, "requested position is not an integer constant"); *no_add_attrs = true; } else { if (tree_int_cst_lt (position, integer_zero_node)) { warning (0, "requested position is less than zero"); *no_add_attrs = true; } } } return NULL_TREE; } /* Handle a "noreturn" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_noreturn_attribute (tree *node, tree name, tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *no_add_attrs) { tree type = TREE_TYPE (*node); /* See FIXME comment in c_common_attribute_table. */ if (TREE_CODE (*node) == FUNCTION_DECL) TREE_THIS_VOLATILE (*node) = 1; else if (TREE_CODE (type) == POINTER_TYPE && TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE) TREE_TYPE (*node) = build_pointer_type (build_type_variant (TREE_TYPE (type), TYPE_READONLY (TREE_TYPE (type)), 1)); else { warning (OPT_Wattributes, "%qs attribute ignored", IDENTIFIER_POINTER (name)); *no_add_attrs = true; } return NULL_TREE; } /* Handle a "leaf" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_leaf_attribute (tree *node, tree name, tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *no_add_attrs) { if (TREE_CODE (*node) != FUNCTION_DECL) { warning (OPT_Wattributes, "%qE attribute ignored", name); *no_add_attrs = true; } if (!TREE_PUBLIC (*node)) { warning (OPT_Wattributes, "%qE attribute has no effect", name); *no_add_attrs = true; } return NULL_TREE; } /* Handle a "always_inline" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_always_inline_attribute (tree *node, tree name, tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *no_add_attrs) { if (TREE_CODE (*node) == FUNCTION_DECL) { /* Set the attribute and mark it for disregarding inline limits. */ DECL_DISREGARD_INLINE_LIMITS (*node) = 1; } else { warning (OPT_Wattributes, "%qE attribute ignored", name); *no_add_attrs = true; } return NULL_TREE; } /* Handle a "malloc" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_malloc_attribute (tree *node, tree name, tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *no_add_attrs) { if (TREE_CODE (*node) == FUNCTION_DECL && POINTER_TYPE_P (TREE_TYPE (TREE_TYPE (*node)))) DECL_IS_MALLOC (*node) = 1; else { warning (OPT_Wattributes, "%qs attribute ignored", IDENTIFIER_POINTER (name)); *no_add_attrs = true; } return NULL_TREE; } /* Fake handler for attributes we don't properly support. */ tree fake_attribute_handler (tree * ARG_UNUSED (node), tree ARG_UNUSED (name), tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool * ARG_UNUSED (no_add_attrs)) { return NULL_TREE; } /* Handle a "type_generic" attribute. */ static tree handle_type_generic_attribute (tree *node, tree ARG_UNUSED (name), tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool * ARG_UNUSED (no_add_attrs)) { /* Ensure we have a function type. */ gcc_assert (TREE_CODE (*node) == FUNCTION_TYPE); /* Ensure we have a variadic function. */ gcc_assert (!prototype_p (*node) || stdarg_p (*node)); return NULL_TREE; } /* Handle a "vector_size" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_vector_size_attribute (tree *node, tree name, tree args, int ARG_UNUSED (flags), bool *no_add_attrs) { tree type = *node; tree vector_type; *no_add_attrs = true; /* We need to provide for vector pointers, vector arrays, and functions returning vectors. For example: __attribute__((vector_size(16))) short *foo; In this case, the mode is SI, but the type being modified is HI, so we need to look further. */ while (POINTER_TYPE_P (type) || TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == ARRAY_TYPE) type = TREE_TYPE (type); vector_type = build_vector_type_for_size (type, TREE_VALUE (args), name); if (!vector_type) return NULL_TREE; /* Build back pointers if needed. */ *node = reconstruct_complex_type (*node, vector_type); return NULL_TREE; } /* Handle a "vector_type" attribute; arguments as in struct attribute_spec.handler. */ static tree handle_vector_type_attribute (tree *node, tree name, tree ARG_UNUSED (args), int ARG_UNUSED (flags), bool *no_add_attrs) { tree type = *node; tree vector_type; *no_add_attrs = true; if (TREE_CODE (type) != ARRAY_TYPE) { error ("attribute %qs applies to array types only", IDENTIFIER_POINTER (name)); return NULL_TREE; } vector_type = build_vector_type_for_array (type, name); if (!vector_type) return NULL_TREE; TYPE_REPRESENTATIVE_ARRAY (vector_type) = type; *node = vector_type; return NULL_TREE; } /* ----------------------------------------------------------------------- * * BUILTIN FUNCTIONS * * ----------------------------------------------------------------------- */ /* Worker for DEF_BUILTIN. Possibly define a builtin function with one or two names. Does not declare a non-__builtin_ function if flag_no_builtin, or if nonansi_p and flag_no_nonansi_builtin. */ static void def_builtin_1 (enum built_in_function fncode, const char *name, enum built_in_class fnclass, tree fntype, tree libtype, bool both_p, bool fallback_p, bool nonansi_p ATTRIBUTE_UNUSED, tree fnattrs, bool implicit_p) { tree decl; const char *libname; /* Preserve an already installed decl. It most likely was setup in advance (e.g. as part of the internal builtins) for specific reasons. */ if (builtin_decl_explicit (fncode) != NULL_TREE) return; gcc_assert ((!both_p && !fallback_p) || !strncmp (name, "__builtin_", strlen ("__builtin_"))); libname = name + strlen ("__builtin_"); decl = add_builtin_function (name, fntype, fncode, fnclass, (fallback_p ? libname : NULL), fnattrs); if (both_p) /* ??? This is normally further controlled by command-line options like -fno-builtin, but we don't have them for Ada. */ add_builtin_function (libname, libtype, fncode, fnclass, NULL, fnattrs); set_builtin_decl (fncode, decl, implicit_p); } static int flag_isoc94 = 0; static int flag_isoc99 = 0; static int flag_isoc11 = 0; /* Install what the common builtins.def offers. */ static void install_builtin_functions (void) { #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \ NONANSI_P, ATTRS, IMPLICIT, COND) \ if (NAME && COND) \ def_builtin_1 (ENUM, NAME, CLASS, \ builtin_types[(int) TYPE], \ builtin_types[(int) LIBTYPE], \ BOTH_P, FALLBACK_P, NONANSI_P, \ built_in_attributes[(int) ATTRS], IMPLICIT); #include "builtins.def" } /* ----------------------------------------------------------------------- * * BUILTIN FUNCTIONS * * ----------------------------------------------------------------------- */ /* Install the builtin functions we might need. */ void gnat_install_builtins (void) { install_builtin_elementary_types (); install_builtin_function_types (); install_builtin_attributes (); /* Install builtins used by generic middle-end pieces first. Some of these know about internal specificities and control attributes accordingly, for instance __builtin_alloca vs no-throw and -fstack-check. We will ignore the generic definition from builtins.def. */ build_common_builtin_nodes (); /* Now, install the target specific builtins, such as the AltiVec family on ppc, and the common set as exposed by builtins.def. */ targetm.init_builtins (); install_builtin_functions (); } #include "gt-ada-utils.h" #include "gtype-ada.h"