summaryrefslogtreecommitdiff
path: root/compiler/ncal.pas
blob: d1c4c37cbe021c7c653e61c867105937b73438ec (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
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
{
    This file implements the node for sub procedure calling.

    Copyright (c) 1998-2002 by Florian Klaempfl

    This program 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 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

 ****************************************************************************
}
unit ncal;

{$i fpcdefs.inc}

{ $define DEBUGINLINE}

interface

    uses
       cutils,cclasses,
       globtype,constexp,
       paramgr,parabase,cgbase,
       node,nbas,nutils,
       {$ifdef state_tracking}
       nstate,
       {$endif state_tracking}
       symbase,symtype,symsym,symdef,symtable,
       pgentype;

    type
       tcallnodeflag = (
         cnf_typedefset,
         cnf_return_value_used,
         cnf_do_inline,
         cnf_inherited,
         cnf_anon_inherited,
         cnf_new_call,
         cnf_dispose_call,
         cnf_member_call,        { called with implicit methodpointer tree }
         cnf_uses_varargs,       { varargs are used in the declaration }
         cnf_create_failed,      { exception thrown in constructor -> don't call beforedestruction }
         cnf_objc_processed,     { the procedure name has been set to the appropriate objc_msgSend* variant -> don't process again }
         cnf_objc_id_call,       { the procedure is a member call via id -> any ObjC method of any ObjC type in scope is fair game }
         cnf_unit_specified,     { the unit in which the procedure has to be searched has been specified }
         cnf_call_never_returns, { information for the dfa that a subroutine never returns }
         cnf_call_self_node_done,{ the call_self_node has been generated if necessary
                                   (to prevent it from potentially happening again in a wrong context in case of constant propagation or so) }
         cnf_ignore_visibility,  { internally generated call that should ignore visibility checks }
         cnf_check_fpu_exceptions { after the call fpu exceptions shall be checked }
       );
       tcallnodeflags = set of tcallnodeflag;

       tcallparanode = class;

       tcallnode = class(tbinarynode)
       private
          { number of parameters passed from the source, this does not include the hidden parameters }
          paralength   : smallint;
          function getoverrideprocnamedef: tprocdef; inline;
          function  is_simple_para_load(p:tnode; may_be_in_reg: boolean):boolean;
          procedure maybe_load_in_temp(var p:tnode);
          function  gen_high_tree(var p:tnode;paradef:tdef):tnode;
          function  gen_procvar_context_tree_self:tnode;
          function  gen_procvar_context_tree_parentfp:tnode;
          function  gen_self_tree:tnode;
          function  use_caller_self(check_for_callee_self: boolean): boolean;
          procedure maybe_gen_call_self_node;
          function  gen_vmt_tree:tnode;
          function gen_block_context:tnode;
          procedure gen_hidden_parameters;
          function  funcret_can_be_reused:boolean;
          procedure maybe_create_funcret_node;
          procedure bind_parasym;
          procedure add_init_statement(n:tnode);
          procedure add_done_statement(n:tnode);
          procedure convert_carg_array_of_const;
          procedure order_parameters;
          procedure check_inlining;
          function  pass1_normal:tnode;
          procedure register_created_object_types;
          function get_expect_loc: tcgloc;

       protected
          function safe_call_self_node: tnode;
          procedure load_in_temp(var p:tnode);
          procedure gen_vmt_entry_load; virtual;
          procedure gen_syscall_para(para: tcallparanode); virtual;
          procedure objc_convert_to_message_send;virtual;

       protected
          { inlining support }
          inlinelocals            : TFPObjectList;
          inlineinitstatement,
          inlinecleanupstatement  : tstatementnode;
          { checks whether we have to create a temp to store the value of a
            parameter passed to an inline routine to preserve correctness.
            On exit, complexpara contains true if the parameter is a complex
            expression and for which we can try to create a temp (even though
            it's not strictly necessary) for speed and code size reasons.
            Returns true if the temp creation has been handled, false otherwise
          }
          function paraneedsinlinetemp(para: tcallparanode; const pushconstaddr, complexpara: boolean): boolean; virtual;
          function maybecreateinlineparatemp(para: tcallparanode; out complexpara: boolean): boolean;
          procedure createinlineparas;
          procedure wrapcomplexinlinepara(para: tcallparanode); virtual;
          function  replaceparaload(var n: tnode; arg: pointer): foreachnoderesult;
          procedure createlocaltemps(p:TObject;arg:pointer);
          function  optimize_funcret_assignment(inlineblock: tblocknode): tnode;
          function  pass1_inline:tnode;
       protected
          pushedparasize : longint;
          { Objective-C support: force the call node to call the routine with
            this name rather than the name of symtableprocentry (don't store
            to ppu, is set while processing the node). Also used on the JVM
            target for calling virtual methods, as this is name-based and not
            based on VMT entry locations }
          foverrideprocnamedef: tprocdef;
          property overrideprocnamedef: tprocdef read getoverrideprocnamedef;
       public
          { the symbol containing the definition of the procedure }
          { to call                                               }
          symtableprocentry : tprocsym;
          symtableprocentryderef : tderef;
          { symtable where the entry was found, needed for with support }
          symtableproc   : TSymtable;
          { the definition of the procedure to call }
          procdefinition : tabstractprocdef;
          procdefinitionderef : tderef;
          { tree that contains the pointer to the object for this method }
          methodpointer  : tnode;
          { tree representing the VMT entry to call (if any) }
          vmt_entry      : tnode;
          { tree that contains the self/vmt parameter when this node was created
            (so it's still valid when this node is processed in an inline
             context)
          }
          call_self_node,
          call_vmt_node: tnode;
          { initialize/finalization of temps }
          callinitblock,
          callcleanupblock : tblocknode;

          { function return node for initialized types or supplied return variable.
            When the result is passed in a parameter then it is set to nil }
          funcretnode    : tnode;
          { varargs parasyms }
          varargsparas : tvarargsparalist;

          { separately specified resultdef for some compilerprocs (e.g.
            you can't have a function with an "array of char" resultdef
            the RTL) (JM)
          }
          typedef: tdef;
          callnodeflags : tcallnodeflags;

          spezcontext : tspecializationcontext;

          { only the processor specific nodes need to override this }
          { constructor                                             }
          constructor create(l:tnode; v : tprocsym;st : TSymtable; mp: tnode; callflags:tcallnodeflags;sc:tspecializationcontext);virtual;
          constructor create_procvar(l,r:tnode);
          constructor createintern(const name: string; params: tnode);
          constructor createinternfromunit(const fromunit, procname: string; params: tnode);
          constructor createinternres(const name: string; params: tnode; res:tdef);
          constructor createinternresfromunit(const fromunit, procname: string; params: tnode; res:tdef);
          constructor createinternreturn(const name: string; params: tnode; returnnode : tnode);
          constructor createinternmethod(mp: tnode; const name: string; params: tnode);
          constructor createinternmethodres(mp: tnode; const name: string; params: tnode; res:tdef);
          destructor destroy;override;
          constructor ppuload(t:tnodetype;ppufile:tcompilerppufile);override;
          procedure ppuwrite(ppufile:tcompilerppufile);override;
          procedure buildderefimpl;override;
          procedure derefimpl;override;
          function  dogetcopy : tnode;override;
          { Goes through all symbols in a class and subclasses and calls
            verify abstract for each .
          }
          procedure verifyabstractcalls;
          { called for each definition in a class and verifies if a method
            is abstract or not, if it is abstract, give out a warning
          }
          procedure verifyabstract(sym:TObject;arg:pointer);
          procedure insertintolist(l : tnodelist);override;
          function  pass_1 : tnode;override;
          function  pass_typecheck:tnode;override;
       {$ifdef state_tracking}
          function track_state_pass(exec_known:boolean):boolean;override;
       {$endif state_tracking}
          function  docompare(p: tnode): boolean; override;
          procedure printnodedata(var t:text);override;
{$ifdef DEBUG_NODE_XML}
          procedure XMLPrintNodeData(var T: Text); override;
{$endif DEBUG_NODE_XML}
          function  para_count:longint;
          function  required_para_count:longint;
          { checks if there are any parameters which end up at the stack, i.e.
            which have LOC_REFERENCE and set pi_has_stackparameter if this applies }
          procedure check_stack_parameters;
          { force the name of the to-be-called routine to a particular string,
            used for Objective-C message sending.  }
          property parameters : tnode read left write left;
          property pushed_parasize: longint read pushedparasize;
       private
          AbstractMethodsList : TFPHashList;
       end;
       tcallnodeclass = class of tcallnode;

       tcallparaflag = (
          cpf_is_colon_para,
          cpf_varargs_para       { belongs this para to varargs }
       );
       tcallparaflags = set of tcallparaflag;

       tcallparanode = class(ttertiarynode)
       private
          fcontains_stack_tainting_call_cached,
          ffollowed_by_stack_tainting_call_cached : boolean;
       protected
          procedure handlemanagedbyrefpara(orgparadef: tdef);virtual;
          { on some targets, value parameters that are passed by reference must
            be copied to a temp location by the caller (and then a reference to
            this temp location must be passed) }
          procedure copy_value_by_ref_para;
       public
          { in case of copy-out parameters: initialization code, and the code to
            copy back the parameter value after the call (including any required
            finalization code) }
          fparainit,
          fparacopyback: tnode;
          callparaflags : tcallparaflags;
          parasym       : tparavarsym;
          { only the processor specific nodes need to override this }
          { constructor                                             }
          constructor create(expr,next : tnode);virtual;
          destructor destroy;override;
          constructor ppuload(t:tnodetype;ppufile:tcompilerppufile);override;
          procedure ppuwrite(ppufile:tcompilerppufile);override;
          procedure buildderefimpl; override;
          procedure derefimpl; override;
          function dogetcopy : tnode;override;
          procedure insertintolist(l : tnodelist);override;
          function pass_typecheck : tnode;override;
          function pass_1 : tnode;override;
          procedure get_paratype;
          procedure firstcallparan;
          procedure insert_typeconv;
          procedure secondcallparan;virtual;abstract;
          function docompare(p: tnode): boolean; override;
          procedure printnodetree(var t:text);override;
          { returns whether a parameter contains a type conversion from }
          { a refcounted into a non-refcounted type                     }
          function can_be_inlined: boolean;

          property paravalue : tnode read left write left;
          property nextpara : tnode read right write right;
          { third is reused to store the parameter name (only while parsing
            vardispatch calls, never in real node tree) and copy of 'high'
            parameter tree when the parameter is an open array of managed type }
          property parametername : tnode read third write third;

          { returns whether the evaluation of this parameter involves a
            stack tainting call }
          function contains_stack_tainting_call: boolean;
          { initialises the fcontains_stack_tainting_call_cached field with the
            result of contains_stack_tainting_call so that it can be quickly
            accessed via the contains_stack_tainting_call_cached property }
          procedure init_contains_stack_tainting_call_cache;
          { returns result of contains_stack_tainting_call cached during last
            call to init_contains_stack_tainting_call_cache }
          property contains_stack_tainting_call_cached: boolean read fcontains_stack_tainting_call_cached;
          { returns whether this parameter is followed by at least one other
            parameter whose evaluation involves a stack tainting parameter
            (result is only valid after order_parameters has been called) }
          property followed_by_stack_tainting_call_cached: boolean read ffollowed_by_stack_tainting_call_cached;
          property paracopyback: tnode read fparacopyback;
       end;
       tcallparanodeclass = class of tcallparanode;

       tdispcalltype = (
         dct_method,
         dct_propget,
         dct_propput
       );

    procedure reverseparameters(var p: tcallparanode);
    function translate_disp_call(selfnode,parametersnode: tnode; calltype: tdispcalltype; const methodname : ansistring;
      dispid : longint;resultdef : tdef) : tnode;

    var
      ccallnode : tcallnodeclass = tcallnode;
      ccallparanode : tcallparanodeclass = tcallparanode;

      { Current callnode, this is needed for having a link
       between the callparanodes and the callnode they belong to }
      aktcallnode : tcallnode;

    const
      { track current inlining depth }
      inlinelevel : longint = 0;

implementation

    uses
      systems,
      verbose,globals,fmodule,ppu,
      aasmbase,aasmdata,
      symconst,defutil,defcmp,compinnr,
      htypechk,pass_1,
      ncnv,nflw,nld,ninl,nadd,ncon,nmem,nset,nobjc,
      pgenutil,
      ngenutil,objcutil,aasmcnst,
      procinfo,cpuinfo,
      wpobase;

    type
     tobjectinfoitem = class(tlinkedlistitem)
       objinfo : tobjectdef;
       constructor create(def : tobjectdef);
     end;


{****************************************************************************
                             HELPERS
 ****************************************************************************}

    procedure reverseparameters(var p: tcallparanode);
      var
        tmpp,
        hp1, hp2: tcallparanode;
      begin
        hp1:=nil;
        tmpp:=p;
        while assigned(tmpp) do
          begin
             { pull out }
             hp2:=tmpp;
             tmpp:=tcallparanode(tmpp.right);
             { pull in }
             hp2.right:=hp1;
             hp1:=hp2;
          end;
        p:=hp1;
      end;

    function translate_disp_call(selfnode,parametersnode: tnode; calltype: tdispcalltype; const methodname : ansistring;
      dispid : longint;resultdef : tdef) : tnode;
      const
        DISPATCH_METHOD = $1;
        DISPATCH_PROPERTYGET = $2;
        DISPATCH_PROPERTYPUT = $4;
        DISPATCH_PROPERTYPUTREF = $8;
        DISPATCH_CONSTRUCT = $4000;

        calltypes: array[tdispcalltype] of byte = (
          DISPATCH_METHOD, DISPATCH_PROPERTYGET, DISPATCH_PROPERTYPUT
        );
      var
        statements : tstatementnode;
        result_data,
        params : ttempcreatenode;
        paramssize : cardinal;
        resultvalue : tnode;
        para : tcallparanode;
        namedparacount,
        paracount : longint;
        assignmenttype,
        vardatadef,
        pvardatadef : tdef;
        useresult: boolean;
        restype: byte;
        selftemp: ttempcreatenode;
        selfpara: tnode;
        vardispatchparadef: trecorddef;
        vardispatchfield: tsym;
        tcb: ttai_typedconstbuilder;
        calldescsym: tstaticvarsym;
        names : ansistring;
        variantdispatch : boolean;

      function is_byref_para(out assign_type: tdef): boolean;
        begin
          result:=(assigned(para.parasym) and (para.parasym.varspez in [vs_var,vs_out,vs_constref])) or
                  (variantdispatch and valid_for_var(para.left,false));

          if result or (para.left.resultdef.typ in [variantdef]) then
            assign_type:=voidpointertype
          else
            case para.left.resultdef.size of
              1..4:
                assign_type:=u32inttype;
              8:
                assign_type:=u64inttype;
              else
                internalerror(2007042801);
            end;
        end;

      function getvardef(sourcedef: TDef): longint;
        begin
          if is_ansistring(sourcedef) then
            result:=varStrArg
          else
          if is_unicodestring(sourcedef) then
            result:=varUStrArg
          else
          if is_interfacecom_or_dispinterface(sourcedef) then
            begin
              { distinct IDispatch and IUnknown interfaces }
              if def_is_related(tobjectdef(sourcedef),interface_idispatch) then
                result:=vardispatch
              else
                result:=varunknown;
            end
          else
            result:=sourcedef.getvardef;
        end;

      begin
        variantdispatch:=selfnode.resultdef.typ=variantdef;
        result:=internalstatements(statements);
        result_data:=nil;
        selftemp:=nil;
        selfpara:=nil;

        useresult := assigned(resultdef) and not is_void(resultdef);
        if useresult then
          begin
            { get temp for the result }
            result_data:=ctempcreatenode.create(colevarianttype,colevarianttype.size,tt_persistent,true);
            addstatement(statements,result_data);
          end;

        { first, count and check parameters }
        para:=tcallparanode(parametersnode);
        paracount:=0;
        namedparacount:=0;
        while assigned(para) do
          begin
            typecheckpass(para.left);

            { skip hidden dispinterface parameters like $self, $result,
              but count skipped variantdispatch parameters. }
            if (not variantdispatch) and (para.left.nodetype=nothingn) then
              begin
                para:=tcallparanode(para.nextpara);
                continue;
              end;
            inc(paracount);
            if assigned(para.parametername) then
              inc(namedparacount);

            { insert some extra casts }
            if para.left.nodetype=stringconstn then
              inserttypeconv_internal(para.left,cwidestringtype)

            { force automatable boolean type }
            else if is_boolean(para.left.resultdef) then
              inserttypeconv_internal(para.left,bool16type)

            { force automatable float type }
            else if is_extended(para.left.resultdef)
                and (current_settings.fputype<>fpu_none) then
              inserttypeconv_internal(para.left,s64floattype)

            else if is_shortstring(para.left.resultdef) then
              inserttypeconv_internal(para.left,cwidestringtype)

            { skip this check if we've already typecasted to automatable type }
            else if (para.left.nodetype<>nothingn) and (not is_automatable(para.left.resultdef)) then
              CGMessagePos1(para.left.fileinfo,type_e_not_automatable,para.left.resultdef.typename);

            para:=tcallparanode(para.nextpara);
          end;

        { create a temp to store parameter values }
        vardispatchparadef:=crecorddef.create_global_internal('',voidpointertype.size,voidpointertype.size);
        { the size will be set once the vardistpatchparadef record has been completed }
        params:=ctempcreatenode.create(vardispatchparadef,0,tt_persistent,false);
        addstatement(statements,params);

        tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
        tcb.begin_anonymous_record('',1,sizeof(pint),1);

        if not variantdispatch then  { generate a tdispdesc record }
        begin
          { dispid  }
          tcb.emit_ord_const(dispid,s32inttype);
          { restype }
          if useresult then
            restype:=getvardef(resultdef)
          else
            restype:=0;
          tcb.emit_ord_const(restype,u8inttype);
        end;

        tcb.emit_ord_const(calltypes[calltype],u8inttype);
        tcb.emit_ord_const(paracount,u8inttype);
        tcb.emit_ord_const(namedparacount,u8inttype);

        { build up parameters and description }
        para:=tcallparanode(parametersnode);
        paramssize:=0;
        names := #0;
        while assigned(para) do
          begin
            { Skipped parameters are actually (varType=varError, vError=DISP_E_PARAMNOTFOUND).
              Generate only varType here, the value will be added by RTL. }
            if para.left.nodetype=nothingn then
            begin
              if variantdispatch then
                tcb.emit_ord_const(varError,u8inttype);
              para:=tcallparanode(para.nextpara);
              continue;
            end;

            if assigned(para.parametername) then
              begin
                if para.parametername.nodetype=stringconstn then
                  names:=names+tstringconstnode(para.parametername).value_str+#0
                else
                  internalerror(200611041);
              end;

            restype:=getvardef(para.left.resultdef);
            if is_byref_para(assignmenttype) then
              restype:=restype or $80;

            { assign the argument/parameter to the temporary location }
            { for Variants, we always pass a pointer, RTL helpers must handle it
              depending on byref bit }

            vardispatchfield:=vardispatchparadef.add_field_by_def('',assignmenttype);
            if assignmenttype=voidpointertype then
              addstatement(statements,cassignmentnode.create(
                csubscriptnode.create(vardispatchfield,ctemprefnode.create(params)),
                ctypeconvnode.create_internal(caddrnode.create_internal(para.left),voidpointertype)))
            else
              addstatement(statements,cassignmentnode.create(
              csubscriptnode.create(vardispatchfield,ctemprefnode.create(params)),
                ctypeconvnode.create_internal(para.left,assignmenttype)));

            inc(paramssize,max(voidpointertype.size,assignmenttype.size));
            tcb.emit_ord_const(restype,u8inttype);

            para.left:=nil;
            para:=tcallparanode(para.nextpara);
          end;

        { finalize the parameter record }
        trecordsymtable(vardispatchparadef.symtable).addalignmentpadding;

        { Set final size for parameter block }
        params.size:=paramssize;

        { old argument list skeleton isn't needed anymore }
        parametersnode.free;

        pvardatadef:=tpointerdef(search_system_type('PVARDATA').typedef);

        if useresult then
          resultvalue:=caddrnode.create(ctemprefnode.create(result_data))
        else
          resultvalue:=cpointerconstnode.create(0,voidpointertype);

        if variantdispatch then
          begin
            { length-1, because the following names variable *always* starts
              with #0 which will be the terminator for methodname }
            tcb.emit_pchar_const(pchar(methodname),length(methodname)-1,true);
            { length-1 because we added a null terminator to the string itself
              already }
            tcb.emit_pchar_const(pchar(names),length(names)-1,true);
          end;

        { may be referred from other units in case of inlining -> global
          -> must have unique name in entire progream }
        calldescsym:=cstaticvarsym.create(
          internaltypeprefixName[itp_vardisp_calldesc]+current_module.modulename^+'$'+tostr(current_module.localsymtable.SymList.count),
          vs_const,tcb.end_anonymous_record,[vo_is_public,vo_is_typed_const]);
        calldescsym.varstate:=vs_initialised;
        current_module.localsymtable.insert(calldescsym);
        current_asmdata.AsmLists[al_typedconsts].concatList(
          tcb.get_final_asmlist(
            current_asmdata.DefineAsmSymbol(calldescsym.mangledname,AB_GLOBAL,AT_DATA,calldescsym.vardef),
            calldescsym.vardef,sec_rodata_norel,
            lower(calldescsym.mangledname),sizeof(pint)
          )
        );
        tcb.free;

        if variantdispatch then
          begin
            { actual call }
            vardatadef:=trecorddef(search_system_type('TVARDATA').typedef);

            { the Variant should behave similar to hidden 'self' parameter of objects/records,
              see issues #26773 and #27044 }
            if not valid_for_var(selfnode,false) then
              begin
                selftemp:=ctempcreatenode.create(selfnode.resultdef,selfnode.resultdef.size,tt_persistent,false);
                addstatement(statements,selftemp);
                addstatement(statements,cassignmentnode.create(ctemprefnode.create(selftemp),selfnode));
                selfpara:=ctemprefnode.create(selftemp);
              end
            else
              selfpara:=selfnode;

            addstatement(statements,ccallnode.createintern('fpc_dispinvoke_variant',
              { parameters are passed always reverted, i.e. the last comes first }
              ccallparanode.create(caddrnode.create(ctemprefnode.create(params)),
              ccallparanode.create(caddrnode.create(cloadnode.create(calldescsym,current_module.localsymtable)),
              ccallparanode.create(ctypeconvnode.create_internal(selfpara,vardatadef),
              ccallparanode.create(ctypeconvnode.create_internal(resultvalue,pvardatadef),nil)))))
            );
            if assigned(selftemp) then
              addstatement(statements,ctempdeletenode.create(selftemp));
          end
        else
          begin
            addstatement(statements,ccallnode.createintern('fpc_dispatch_by_id',
              { parameters are passed always reverted, i.e. the last comes first }
              ccallparanode.create(caddrnode.create(ctemprefnode.create(params)),
              ccallparanode.create(caddrnode.create(cloadnode.create(calldescsym,current_module.localsymtable)),
              ccallparanode.create(ctypeconvnode.create_internal(selfnode,voidpointertype),
              ccallparanode.create(ctypeconvnode.create_internal(resultvalue,pvardatadef),nil)))))
            );
          end;
        addstatement(statements,ctempdeletenode.create(params));
        if useresult then
          begin
            { clean up }
            addstatement(statements,ctempdeletenode.create_normal_temp(result_data));
            addstatement(statements,ctemprefnode.create(result_data));
          end;
      end;


{****************************************************************************
                              TOBJECTINFOITEM
 ****************************************************************************}

    constructor tobjectinfoitem.create(def : tobjectdef);
      begin
        inherited create;
        objinfo := def;
      end;


{****************************************************************************
                             TCALLPARANODE
 ****************************************************************************}

    procedure tcallparanode.handlemanagedbyrefpara(orgparadef: tdef);
      var
        temp: ttempcreatenode;
        npara: tcallparanode;
        paraaddrtype: tdef;
      begin
        { release memory for reference counted out parameters }
        if (parasym.varspez=vs_out) and
           is_managed_type(orgparadef) and
           (not is_open_array(resultdef) or
            is_managed_type(tarraydef(resultdef).elementdef)) and
           not(target_info.system in systems_garbage_collected_managed_types) then
          begin
            { after converting a parameter to an open array, its resultdef is
              set back to its original resultdef so we can get the value of the
              "high" parameter correctly, even though we already inserted a
              type conversion to "open array". Since here we work on this
              converted parameter, set it back to the type to which it was
              converted in order to avoid type mismatches at the LLVM level }
            if is_open_array(parasym.vardef) and
               is_dynamic_array(orgparadef) then
              begin
                left.resultdef:=resultdef;
                orgparadef:=resultdef;
              end;
            paraaddrtype:=cpointerdef.getreusable(orgparadef);
            { create temp with address of the parameter }
            temp:=ctempcreatenode.create(
              paraaddrtype,paraaddrtype.size,tt_persistent,true);
            { put this code in the init/done statement of the call node, because
              we should finalize all out parameters before other parameters
              are evaluated (in case e.g. a managed out parameter is also
              passed by value, we must not pass the pointer to the now possibly
              freed data as the value parameter, but the finalized/nil value }
            aktcallnode.add_init_statement(temp);
            aktcallnode.add_init_statement(
              cassignmentnode.create(
                ctemprefnode.create(temp),
                caddrnode.create(left)));
            if not is_open_array(resultdef) or
               not is_managed_type(tarraydef(resultdef).elementdef) then
              { finalize the entire parameter }
              aktcallnode.add_init_statement(
                cnodeutils.finalize_data_node(
                  cderefnode.create(ctemprefnode.create(temp))))
            else
              begin
                { passing a (part of, in case of slice) dynamic array as an
                  open array -> finalize the dynamic array contents, not the
                  dynamic array itself }
                npara:=ccallparanode.create(
                         { array length = high + 1 }
                         caddnode.create(addn,third.getcopy,genintconstnode(1)),
                       ccallparanode.create(caddrnode.create_internal
                          (crttinode.create(tstoreddef(tarraydef(resultdef).elementdef),initrtti,rdt_normal)),
                       ccallparanode.create(caddrnode.create_internal(
                          cderefnode.create(ctemprefnode.create(temp))),nil)));
                aktcallnode.add_init_statement(
                  ccallnode.createintern('fpc_finalize_array',npara));
              end;
            left:=cderefnode.create(ctemprefnode.create(temp));
            firstpass(left);
            aktcallnode.add_done_statement(ctempdeletenode.create(temp));
          end;
      end;


    procedure tcallparanode.copy_value_by_ref_para;
      var
        initstat,
        finistat: tstatementnode;
        finiblock: tblocknode;
        paratemp: ttempcreatenode;
        arraysize,
        arraybegin: tnode;
        lefttemp: ttempcreatenode;
        vardatatype,
        temparraydef: tdef;
      begin
        { this routine is for targets where by-reference value parameters need
          to be copied by the caller. It's basically the node-level equivalent
          of thlcgobj.g_copyvalueparas }

        if assigned(fparainit) then
          exit;

        { in case of an array constructor, we don't need a copy since the array
          constructor itself is already constructed on the fly (and hence if
          it's modified by the caller, that's no problem) }
        if not is_array_constructor(left.resultdef) then
          begin
            fparainit:=internalstatements(initstat);
            finiblock:=internalstatements(finistat);
            paratemp:=nil;

            { making a copy of an open array, an array of const or a dynamic
              array requires dynamic memory allocation since we don't know the
              size at compile time }
            if is_open_array(left.resultdef) or
               is_array_of_const(left.resultdef) or
               (is_dynamic_array(left.resultdef) and
                is_open_array(parasym.vardef)) then
              begin
                 paratemp:=ctempcreatenode.create(voidpointertype,voidpointertype.size,tt_persistent,true);
                 if is_dynamic_array(left.resultdef) then
                   begin
                      { note that in insert_typeconv, this dynamic array was
                        already converted into an open array (-> dereferenced)
                        and then its resultdef was restored to the original
                        dynamic array one -> get the address before treating it
                        as a dynamic array here }
                     { first restore the actual resultdef of left }
                     temparraydef:=left.resultdef;
                     left.resultdef:=resultdef;
                     { get its address }
                     lefttemp:=ctempcreatenode.create(voidpointertype,voidpointertype.size,tt_persistent,true);
                     addstatement(initstat,lefttemp);
                     addstatement(finistat,ctempdeletenode.create(lefttemp));
                     addstatement(initstat,
                       cassignmentnode.create(
                         ctemprefnode.create(lefttemp),
                         caddrnode.create_internal(left)
                       )
                     );
                     { now treat that address (correctly) as the original
                       dynamic array to get its start and length }
                     arraybegin:=cvecnode.create(
                       ctypeconvnode.create_explicit(ctemprefnode.create(lefttemp),
                         temparraydef),
                       genintconstnode(0)
                     );
                     arraysize:=caddnode.create(muln,
                       geninlinenode(in_length_x,false,
                         ctypeconvnode.create_explicit(ctemprefnode.create(lefttemp),
                           temparraydef)
                       ),
                       genintconstnode(tarraydef(temparraydef).elementdef.size)
                     );
                   end
                 else
                   begin
                     { no problem here that left is used multiple times, as
                       sizeof() will simply evaluate to the high parameter }
                     arraybegin:=left.getcopy;
                     arraysize:=geninlinenode(in_sizeof_x,false,left);
                   end;
                 addstatement(initstat,paratemp);
                 { paratemp:=getmem(sizeof(para)) }
                 addstatement(initstat,
                   cassignmentnode.create(
                     ctemprefnode.create(paratemp),
                     ccallnode.createintern('fpc_getmem',
                       ccallparanode.create(
                         arraysize.getcopy,nil
                       )
                     )
                   )
                 );
                 { move(para,temp,sizeof(arr)) (no "left.getcopy" below because
                   we replace left afterwards) }
                 addstatement(initstat,
                   cifnode.create_internal(
                     caddnode.create_internal(
                       unequaln,
                       arraysize.getcopy,
                       genintconstnode(0)
                     ),
                     ccallnode.createintern('MOVE',
                       ccallparanode.create(
                         arraysize,
                         ccallparanode.create(
                           cderefnode.create(ctemprefnode.create(paratemp)),
                           ccallparanode.create(
                             arraybegin,nil
                           )
                         )
                       )
                     ),
                     nil
                   )
                 );
                 { no reference count increases, that's still done on the callee
                   side because for compatibility with targets that perform this
                   copy on the callee side, that should only be done for non-
                   assember functions (and we can't know that 100% certain here,
                   e.g. in case of external declarations) (*) }

                 { free the memory again after the call: freemem(paratemp) }
                 addstatement(finistat,
                   ccallnode.createintern('fpc_freemem',
                     ccallparanode.create(
                       ctemprefnode.create(paratemp),nil
                     )
                   )
                 );
                 { replace the original parameter with a dereference of the
                   temp typecasted to the same type as the original parameter
                   (don't free left, it has been reused above) }
                 left:=ctypeconvnode.create_internal(
                   cderefnode.create(ctemprefnode.create(paratemp)),
                   left.resultdef);
              end
            else if is_shortstring(parasym.vardef) then
              begin
                { the shortstring parameter may have a different size than the
                  parameter type -> assign and truncate/extend }
                paratemp:=ctempcreatenode.create(parasym.vardef,parasym.vardef.size,tt_persistent,false);
                addstatement(initstat,paratemp);
                { assign shortstring }
                addstatement(initstat,
                  cassignmentnode.create(
                    ctemprefnode.create(paratemp),left
                  )
                );
                { replace parameter with temp (don't free left, it has been
                  reused above) }
                left:=ctemprefnode.create(paratemp);
              end
            else if parasym.vardef.typ=variantdef then
              begin
                vardatatype:=search_system_type('TVARDATA').typedef;
                paratemp:=ctempcreatenode.create(vardatatype,vardatatype.size,tt_persistent,false);
                addstatement(initstat,paratemp);
                addstatement(initstat,
                  ccallnode.createintern('fpc_variant_copy_overwrite',
                    ccallparanode.create(
                      ctypeconvnode.create_explicit(ctemprefnode.create(paratemp),
                          vardatatype
                        ),
                      ccallparanode.create(ctypeconvnode.create_explicit(left,
                        vardatatype),
                        nil
                      )
                    )
                  )
                );
                { replace parameter with temp (don't free left, it has been
                  reused above) }
                left:=ctypeconvnode.create_explicit(ctemprefnode.create(paratemp),parasym.vardef);
              end
            else if is_managed_type(left.resultdef) then
              begin
                { don't increase/decrease the reference count here, will be done by
                  the callee (see (*) above) -> typecast to array of byte
                  for the assignment to the temp }
                temparraydef:=carraydef.getreusable(u8inttype,left.resultdef.size);
                paratemp:=ctempcreatenode.create(temparraydef,temparraydef.size,tt_persistent,false);
                addstatement(initstat,paratemp);
                addstatement(initstat,
                  cassignmentnode.create(
                    ctemprefnode.create(paratemp),
                    ctypeconvnode.create_internal(left,temparraydef)
                  )
                );
                left:=ctypeconvnode.create_explicit(ctemprefnode.create(paratemp),left.resultdef);
              end
            else
              begin
                paratemp:=ctempcreatenode.create(left.resultdef,left.resultdef.size,tt_persistent,false);
                addstatement(initstat,paratemp);
                addstatement(initstat,
                  cassignmentnode.create(ctemprefnode.create(paratemp),left)
                );
                { replace parameter with temp (don't free left, it has been
                  reused above) }
                left:=ctemprefnode.create(paratemp);
              end;
            { add the finish statements to the call cleanup block }
            addstatement(finistat,ctempdeletenode.create(paratemp));
            aktcallnode.add_done_statement(finiblock);

            firstpass(fparainit);
            firstpass(left);
          end;
      end;


    constructor tcallparanode.create(expr,next : tnode);

      begin
         inherited create(callparan,expr,next,nil);
         if not assigned(expr) then
           internalerror(200305091);
         expr.fileinfo:=fileinfo;
         callparaflags:=[];
         if expr.nodetype = typeconvn then
           ttypeconvnode(expr).warn_pointer_to_signed:=false;
      end;

    destructor tcallparanode.destroy;

      begin
         fparainit.free;
         fparacopyback.free;
         inherited destroy;
      end;


    constructor tcallparanode.ppuload(t:tnodetype;ppufile:tcompilerppufile);
      begin
        inherited ppuload(t,ppufile);
        ppufile.getset(tppuset1(callparaflags));
        fparainit:=ppuloadnode(ppufile);
        fparacopyback:=ppuloadnode(ppufile);
      end;


    procedure tcallparanode.ppuwrite(ppufile:tcompilerppufile);
      begin
        inherited ppuwrite(ppufile);
        ppufile.putset(tppuset1(callparaflags));
        ppuwritenode(ppufile,fparainit);
        ppuwritenode(ppufile,fparacopyback);
      end;


    procedure tcallparanode.buildderefimpl;
      begin
        inherited buildderefimpl;
        if assigned(fparainit) then
          fparainit.buildderefimpl;
        if assigned(fparacopyback) then
          fparacopyback.buildderefimpl;
      end;


    procedure tcallparanode.derefimpl;
      begin
        inherited derefimpl;
        if assigned(fparainit) then
          fparainit.derefimpl;
        if assigned(fparacopyback) then
          fparacopyback.derefimpl;
      end;


    function tcallparanode.dogetcopy : tnode;
      var
         n : tcallparanode;
         initcopy: tnode;
      begin
         initcopy:=nil;
         { must be done before calling inherited getcopy, because can create
           tempcreatenodes for values used in left }
         if assigned(fparainit) then
           initcopy:=fparainit.getcopy;
         n:=tcallparanode(inherited dogetcopy);
         n.callparaflags:=callparaflags;
         n.parasym:=parasym;
         n.fparainit:=initcopy;
         if assigned(fparacopyback) then
           n.fparacopyback:=fparacopyback.getcopy;
         result:=n;
      end;


    procedure tcallparanode.insertintolist(l : tnodelist);
      begin
      end;


    function tcallparanode.pass_typecheck : tnode;
      begin
        { need to use get_paratype }
        internalerror(200709251);
        result:=nil;
      end;


    function tcallparanode.pass_1 : tnode;
      begin
        { need to use firstcallparan }
        internalerror(200709252);
        result:=nil;
      end;


    procedure tcallparanode.get_paratype;
      begin
         if assigned(right) then
          tcallparanode(right).get_paratype;
         if assigned(fparainit) then
          typecheckpass(fparainit);
         typecheckpass(left);
         if assigned(third) then
           typecheckpass(third);
         if assigned(fparacopyback) then
           typecheckpass(fparacopyback);
         if codegenerror then
          resultdef:=generrordef
         else
          resultdef:=left.resultdef;
      end;


    procedure tcallparanode.firstcallparan;
      begin
        if assigned(right) then
          tcallparanode(right).firstcallparan;
        if not assigned(left.resultdef) then
          get_paratype;

        if assigned(parasym) and
           (parasym.varspez in [vs_var,vs_out,vs_constref]) and
           { for record constructors }
           (left.nodetype<>nothingn) then
          handlemanagedbyrefpara(left.resultdef);

        { for targets that have to copy "value parameters by reference" on the
          caller side

          aktcallnode may not be assigned in case firstcallparan is called for
          fake parameters to inline nodes (in that case, we don't have a real
          call and hence no "caller side" either)
          }
        if assigned(aktcallnode) and
           (target_info.system in systems_caller_copy_addr_value_para) and
           ((assigned(parasym) and
             (parasym.varspez=vs_value)) or
            (cpf_varargs_para in callparaflags)) and
           (left.nodetype<>nothingn) and
           not(vo_has_local_copy in parasym.varoptions) and
           ((not is_open_array(parasym.vardef) and
             not is_array_of_const(parasym.vardef)) or
            not(aktcallnode.procdefinition.proccalloption in cdecl_pocalls)) and
           paramanager.push_addr_param(vs_value,parasym.vardef,
                      aktcallnode.procdefinition.proccalloption) then
          copy_value_by_ref_para;

        if assigned(fparainit) then
          firstpass(fparainit);
        firstpass(left);
        if assigned(fparacopyback) then
          firstpass(fparacopyback);
        if assigned(third) then
          firstpass(third);
        expectloc:=left.expectloc;
      end;


    procedure tcallparanode.insert_typeconv;
      var
        olddef  : tdef;
        hp      : tnode;
        block : tblocknode;
        statements : tstatementnode;
        temp : ttempcreatenode;
        owningprocdef: tprocdef;
      begin
         { Be sure to have the resultdef }
         if not assigned(left.resultdef) then
           typecheckpass(left);

         if (left.nodetype<>nothingn) then
           begin
             { convert loads of the function result variable into procvars
               representing the current function in case the formal parameter is
               a procvar (CodeWarrior Pascal contains the same kind of
               automatic disambiguation; you can use the function name in both
               meanings, so we cannot statically pick either the function result
               or the function definition in pexpr) }
             if (m_mac in current_settings.modeswitches) and
                (parasym.vardef.typ=procvardef) and
                is_ambiguous_funcret_load(left,owningprocdef) then
               begin
                 hp:=cloadnode.create_procvar(owningprocdef.procsym,owningprocdef,owningprocdef.procsym.owner);
                 typecheckpass(hp);
                 left.free;
                 left:=hp;
               end;

             { Convert tp procvars, this is needs to be done
               here to make the change permanent. in the overload
               choosing the changes are only made temporarily

               Don't do this for parentfp parameters, as for calls to nested
               procvars they are a copy of right, which is the procvar itself
               and hence turning that into a call would result into endless
               recursion. For regular nested calls, the parentfp node can
               never be a procvar (it's a loadparentfpnode). }
             if not(vo_is_parentfp in parasym.varoptions) and
                (left.resultdef.typ=procvardef) and
                not(parasym.vardef.typ in [procvardef,formaldef]) then
               begin
                 if maybe_call_procvar(left,true) then
                   resultdef:=left.resultdef
               end;

             { Remove implicitly inserted typecast to pointer for
               @procvar in macpas }
             if (m_mac_procvar in current_settings.modeswitches) and
                (parasym.vardef.typ=procvardef) and
                (left.nodetype=typeconvn) and
                is_voidpointer(left.resultdef) and
                (ttypeconvnode(left).left.nodetype=typeconvn) and
                (ttypeconvnode(ttypeconvnode(left).left).convtype=tc_proc_2_procvar) then
               begin
                 hp:=left;
                 left:=ttypeconvnode(left).left;
                 ttypeconvnode(hp).left:=nil;
                 hp.free;
               end;
             maybe_global_proc_to_nested(left,parasym.vardef);

             { Handle varargs and hidden paras directly, no typeconvs or }
             { pass_typechecking needed                                  }
             if (cpf_varargs_para in callparaflags) then
               begin
                 { this should only happen vor C varargs                    }
                 { the necessary conversions have already been performed in }
                 { tarrayconstructornode.insert_typeconvs                   }
                 set_varstate(left,vs_read,[vsf_must_be_valid]);
                 insert_varargstypeconv(left,true);
                 resultdef:=left.resultdef;
                 { also update parasym type to get the correct parameter location
                   for the new types }
                 parasym.vardef:=left.resultdef;
               end
             else
              if (vo_is_hidden_para in parasym.varoptions) then
               begin
                 set_varstate(left,vs_read,[vsf_must_be_valid]);
                 resultdef:=left.resultdef;
               end
             else
               begin

                 { Do we need arrayconstructor -> set conversion, then insert
                   it here before the arrayconstructor node breaks the tree
                   with its conversions of enum->ord }
                 if (left.nodetype=arrayconstructorn) and
                    (parasym.vardef.typ=setdef) then
                   inserttypeconv(left,parasym.vardef);

                 { if an array constructor can be a set and it is passed to
                   a formaldef, a set must be passed, see also issue #37796 }
                 if (left.nodetype=arrayconstructorn) and
                    (parasym.vardef.typ=formaldef) and
                    (arrayconstructor_can_be_set(left)) then
                   left:=arrayconstructor_to_set(left,false);

                 { set some settings needed for arrayconstructor }
                 if is_array_constructor(left.resultdef) then
                  begin
                    if left.nodetype<>arrayconstructorn then
                      internalerror(200504041);
                    if is_array_of_const(parasym.vardef) then
                     begin
                       { force variant array }
                       include(left.flags,nf_forcevaria);
                     end
                    else
                     begin
                       include(left.flags,nf_novariaallowed);
                       { now that the resultting type is know we can insert the required
                         typeconvs for the array constructor }
                       if parasym.vardef.typ=arraydef then
                         tarrayconstructornode(left).force_type(tarraydef(parasym.vardef).elementdef);
                     end;
                  end;

                 { check if local proc/func is assigned to procvar }
                 if left.resultdef.typ=procvardef then
                   test_local_to_procvar(tprocvardef(left.resultdef),parasym.vardef);

                 { test conversions }
                 if not(is_shortstring(left.resultdef) and
                        is_shortstring(parasym.vardef)) and
                    (parasym.vardef.typ<>formaldef) and
                    not(parasym.univpara) then
                   begin
                      { Process open parameters }
                      if paramanager.keep_para_array_range(parasym.varspez,parasym.vardef,aktcallnode.procdefinition.proccalloption) then
                       begin
                         { insert type conv but hold the ranges of the array }
                         olddef:=left.resultdef;
                         inserttypeconv(left,parasym.vardef);
                         left.resultdef:=olddef;
                       end
                      else
                       begin
                         check_ranges(left.fileinfo,left,parasym.vardef);
                         inserttypeconv(left,parasym.vardef);
                       end;
                      if codegenerror then
                        exit;
                   end;

                { truncate shortstring value parameters at the caller side if }
                { they are passed by value (if passed by reference, then the  }
                { callee will truncate when copying in the string)            }
                { This happens e.g. on x86_64 for small strings               }
                 if is_shortstring(left.resultdef) and
                    is_shortstring(parasym.vardef) and
                    (parasym.varspez=vs_value) and
                    not paramanager.push_addr_param(parasym.varspez,parasym.vardef,
                          aktcallnode.procdefinition.proccalloption) and
                    ((is_open_string(left.resultdef) and
                      (tstringdef(parasym.vardef).len < 255)) or
                     (not is_open_string(left.resultdef) and
                      { when a stringconstn is typeconverted, then only its  }
                      { def is modified, not the contents (needed because in }
                      { Delphi/TP, if you pass a longer string to a const    }
                      { parameter, then the callee has to see this longer    }
                      { string)                                              }
                      (((left.nodetype<>stringconstn) and
                        (tstringdef(parasym.vardef).len<tstringdef(left.resultdef).len)) or
                       ((left.nodetype=stringconstn) and
                        (tstringdef(parasym.vardef).len<tstringconstnode(left).len))))) then
                   begin
                     block:=internalstatements(statements);
                     { temp for the new string }
                     temp:=ctempcreatenode.create(parasym.vardef,parasym.vardef.size,
                       tt_persistent,true);
                     addstatement(statements,temp);
                     { assign parameter to temp }
                     addstatement(statements,cassignmentnode.create(ctemprefnode.create(temp),left));
                     left:=nil;
                     { release temp after next use }
                     addstatement(statements,ctempdeletenode.create_normal_temp(temp));
                     addstatement(statements,ctemprefnode.create(temp));
                     typecheckpass(tnode(block));
                     left:=block;
                   end;

                 { check var strings }
                 if (cs_strict_var_strings in current_settings.localswitches) and
                    is_shortstring(left.resultdef) and
                    is_shortstring(parasym.vardef) and
                    (parasym.varspez in [vs_out,vs_var,vs_constref]) and
                    not(is_open_string(parasym.vardef)) and
                    not(equal_defs(left.resultdef,parasym.vardef)) then
                   begin
                     CGMessagePos(left.fileinfo,type_e_strict_var_string_violation);
                   end;

                 { passing a value to an "univ" parameter implies an explicit
                   typecast to the parameter type. Must be done before the
                   valid_for_var() check, since the typecast can result in
                   an invalid lvalue in case of var/out parameters. }
                 if (parasym.univpara) then
                   begin
                     { load procvar if a procedure is passed }
                     if ((m_tp_procvar in current_settings.modeswitches) or
                         (m_mac_procvar in current_settings.modeswitches)) and
                        (left.nodetype=calln) and
                        (is_void(left.resultdef)) then
                       begin
                         load_procvar_from_calln(left);
                         { load_procvar_from_calln() creates a loadn for a
                           a procedure, which means that the type conversion
                           below will type convert the first instruction
                           bytes of the procedure -> convert to a procvar }
                         left:=ctypeconvnode.create_proc_to_procvar(left);
                         typecheckpass(left);
                       end;
                     inserttypeconv_explicit(left,parasym.vardef);
                   end;

                 { Handle formal parameters separate }
                 if (parasym.vardef.typ=formaldef) then
                   begin
                     { load procvar if a procedure is passed }
                     if ((m_tp_procvar in current_settings.modeswitches) or
                         (m_mac_procvar in current_settings.modeswitches)) and
                        (left.nodetype=calln) and
                        (is_void(left.resultdef)) then
                       load_procvar_from_calln(left);

                     case parasym.varspez of
                       vs_var,
                       vs_out :
                         begin
                           if not valid_for_formal_var(left,true) then
                            CGMessagePos(left.fileinfo,parser_e_illegal_parameter_list);
                         end;
                       vs_constref:
                         begin
                           if not valid_for_formal_constref(left,true) then
                            CGMessagePos(left.fileinfo,parser_e_illegal_parameter_list);
                         end;
                       vs_const :
                         begin
                           if not valid_for_formal_const(left,true) then
                            CGMessagePos(left.fileinfo,parser_e_illegal_parameter_list)
                           else if (target_info.system in systems_managed_vm) and
                              (left.resultdef.typ in [orddef,floatdef]) then
                             begin
                               left:=cinlinenode.create(in_box_x,false,ccallparanode.create(left,nil));
                               typecheckpass(left);
                             end;
                         end;
                       else
                         ;
                     end;
                   end
                 else
                   begin
                     { check if the argument is allowed }
                     if (parasym.varspez in [vs_out,vs_var]) then
                       valid_for_var(left,true);
                   end;

                 if parasym.varspez in [vs_var,vs_out,vs_constref] then
                   set_unique(left);

                 if (parasym.varspez=vs_const) and (parasym.vardef.typ=formaldef) then
                   begin
                     { compilerprocs never capture the address of their
                       parameters }
                     if not(po_compilerproc in aktcallnode.procdefinition.procoptions) then
                       make_not_regable(left,[ra_addr_regable,ra_addr_taken])
                     else
                       make_not_regable(left,[ra_addr_regable])
                   end
                 else
                  case parasym.varspez of
                    vs_out :
                      begin
                        { first set written separately to avoid false }
                        { uninitialized warnings (tbs/tb0542)         }
                        set_varstate(left,vs_written,[]);
                        set_varstate(left,vs_readwritten,[]);
                        { compilerprocs never capture the address of their
                          parameters }
                        if not(po_compilerproc in aktcallnode.procdefinition.procoptions) then
                          make_not_regable(left,[ra_addr_regable,ra_addr_taken])
                        else
                          make_not_regable(left,[ra_addr_regable])
                      end;
                    vs_var,
                    vs_constref:
                      begin
                        set_varstate(left,vs_readwritten,[vsf_must_be_valid,vsf_use_hints]);
                        { compilerprocs never capture the address of their
                          parameters }
                        if not(po_compilerproc in aktcallnode.procdefinition.procoptions) then
                          make_not_regable(left,[ra_addr_regable,ra_addr_taken])
                        else
                          make_not_regable(left,[ra_addr_regable])
                      end;
                    else
                      set_varstate(left,vs_read,[vsf_must_be_valid]);
                  end;
                 { must only be done after typeconv PM }
                 resultdef:=parasym.vardef;
               end;
            end;

         { process next node }
         if assigned(right) then
           tcallparanode(right).insert_typeconv;
      end;


    function tcallparanode.can_be_inlined: boolean;
      var
        n: tnode;
      begin
        n:=left;
        result:=false;
        while assigned(n) and
              (n.nodetype=typeconvn) do
          begin
            { look for type conversion nodes which convert a }
            { refcounted type into a non-refcounted type     }
            if not is_managed_type(n.resultdef) and
               is_managed_type(ttypeconvnode(n).left.resultdef) then
              exit;
            n:=ttypeconvnode(n).left;
          end;
        { also check for dereferencing constant pointers, like }
        { tsomerecord(nil^) passed to a const r: tsomerecord   }
        { parameter                                           }
        if (n.nodetype=derefn) then
          begin
            repeat
              n:=tunarynode(n).left;
            until (n.nodetype<>typeconvn);
            if (n.nodetype in [niln,pointerconstn]) then
              exit
          end;
        result:=true;
      end;


    function check_contains_stack_tainting_call(var n: tnode; arg: pointer): foreachnoderesult;
      begin
        if (n.nodetype=calln) and
           tcallnode(n).procdefinition.stack_tainting_parameter(callerside) then
          result:=fen_norecurse_true
        else
          result:=fen_false;
      end;


    function tcallparanode.contains_stack_tainting_call: boolean;
      begin
        result:=foreachnodestatic(pm_postprocess,left,@check_contains_stack_tainting_call,nil);
      end;


    procedure tcallparanode.init_contains_stack_tainting_call_cache;
      begin
        fcontains_stack_tainting_call_cached:=contains_stack_tainting_call;
      end;


    function tcallparanode.docompare(p: tnode): boolean;
      begin
        docompare :=
          inherited docompare(p) and
          fparainit.isequal(tcallparanode(p).fparainit) and
          fparacopyback.isequal(tcallparanode(p).fparacopyback) and
          (callparaflags = tcallparanode(p).callparaflags)
          ;
      end;


    procedure tcallparanode.printnodetree(var t:text);
      var
        hp: tbinarynode;
      begin
        hp:=self;
        while assigned(hp) do
         begin
           write(t,printnodeindention,'(');
           printnodeindent;
           hp.printnodeinfo(t);
           writeln(t);
           if assigned(tcallparanode(hp).fparainit) then
             begin
               writeln(t,printnodeindention,'(parainit =');
               printnodeindent;
               printnode(t,tcallparanode(hp).fparainit);
               printnodeunindent;
               writeln(t,printnodeindention,')');
             end;
           if assigned(tcallparanode(hp).fparacopyback) then
             begin
               writeln(t,printnodeindention,'(fparacopyback =');
               printnodeindent;
               printnode(t,tcallparanode(hp).fparacopyback);
               printnodeunindent;
               writeln(t,printnodeindention,')');
             end;
           printnode(t,hp.left);
           writeln(t);
           printnodeunindent;
           writeln(t,printnodeindention,')');
           hp:=tbinarynode(hp.right);
         end;
      end;


{****************************************************************************
                                 TCALLNODE
 ****************************************************************************}

    constructor tcallnode.create(l:tnode;v : tprocsym;st : TSymtable; mp: tnode; callflags:tcallnodeflags;sc:tspecializationcontext);
      var
        srsym: tsym;
        srsymtable: tsymtable;
      begin
         inherited create(calln,l,nil);
         spezcontext:=sc;
         symtableprocentry:=v;
         symtableproc:=st;
         callnodeflags:=callflags+[cnf_return_value_used];
         methodpointer:=mp;
         callinitblock:=nil;
         callcleanupblock:=nil;
         procdefinition:=nil;
         funcretnode:=nil;
         paralength:=-1;
         varargsparas:=nil;
         if assigned(current_structdef) and
            assigned(mp) and
            assigned(current_procinfo) then
           begin
            { only needed when calling a destructor from an exception block in a
              contructor of a TP-style object }
            if (current_procinfo.procdef.proctypeoption=potype_constructor) and
               (cnf_create_failed in callflags) then
              if is_object(current_structdef) then
                call_vmt_node:=load_vmt_pointer_node
              else if is_class(current_structdef) then
                begin
                  if not searchsym(copy(internaltypeprefixName[itp_vmt_afterconstruction_local],2,255),srsym,srsymtable) then
                    internalerror(2016090801);
                  call_vmt_node:=cloadnode.create(srsym,srsymtable);
                end;
           end;
      end;


    constructor tcallnode.create_procvar(l,r:tnode);
      begin
         create(l,nil,nil,nil,[],nil);
         right:=r;
      end;


     constructor tcallnode.createintern(const name: string; params: tnode);
       var
         srsym: tsym;
       begin
         srsym := tsym(systemunit.Find(name));
         { in case we are looking for a non-external compilerproc of which we
           only have parsed the declaration until now (the symbol name will
           still be uppercased, because it needs to be matched when we
           encounter the implementation) }
         if not assigned(srsym) and
            (cs_compilesystem in current_settings.moduleswitches) then
           srsym := tsym(systemunit.Find(upper(name)));
         if not assigned(srsym) or
            (srsym.typ<>procsym) then
           Message1(cg_f_unknown_compilerproc,name);
         create(params,tprocsym(srsym),srsym.owner,nil,[],nil);
       end;


     constructor tcallnode.createinternfromunit(const fromunit, procname: string; params: tnode);
       var
         srsym: tsym;
         srsymtable: tsymtable;
       begin
         srsym:=nil;
         if not searchsym_in_named_module(fromunit,procname,srsym,srsymtable) or
            (srsym.typ<>procsym) then
           Message1(cg_f_unknown_compilerproc,fromunit+'.'+procname);
         create(params,tprocsym(srsym),srsymtable,nil,[],nil);
       end;


    constructor tcallnode.createinternres(const name: string; params: tnode; res:tdef);
      var
        pd : tprocdef;
      begin
        createintern(name,params);
        typedef:=res;
        include(callnodeflags,cnf_typedefset);
        pd:=tprocdef(symtableprocentry.ProcdefList[0]);
        { both the normal and specified resultdef either have to be returned via a }
        { parameter or not, but no mixing (JM)                                      }
        if paramanager.ret_in_param(typedef,pd) xor
          paramanager.ret_in_param(pd.returndef,pd) then
          internalerror(2001082911);
      end;


    constructor tcallnode.createinternresfromunit(const fromunit, procname: string; params: tnode; res:tdef);
      var
        pd : tprocdef;
      begin
        createinternfromunit(fromunit,procname,params);
        typedef:=res;
        include(callnodeflags,cnf_typedefset);
        pd:=tprocdef(symtableprocentry.ProcdefList[0]);
        { both the normal and specified resultdef either have to be returned via a }
        { parameter or not, but no mixing (JM)                                      }
        if paramanager.ret_in_param(typedef,pd) xor
          paramanager.ret_in_param(pd.returndef,pd) then
          internalerror(200108291);
      end;


    constructor tcallnode.createinternreturn(const name: string; params: tnode; returnnode : tnode);
      begin
        createintern(name,params);
        funcretnode:=returnnode;
      end;


    constructor tcallnode.createinternmethod(mp: tnode; const name: string; params: tnode);
      var
        ps: tsym;
        recdef: tabstractrecorddef;
      begin
        typecheckpass(mp);
        if mp.resultdef.typ=classrefdef then
          recdef:=tabstractrecorddef(tclassrefdef(mp.resultdef).pointeddef)
        else
          recdef:=tabstractrecorddef(mp.resultdef);
        ps:=search_struct_member(recdef,name);
        if not assigned(ps) or
           (ps.typ<>procsym) then
          internalerror(2011062806);
        create(params,tprocsym(ps),ps.owner,mp,[],nil);
      end;


    constructor tcallnode.createinternmethodres(mp: tnode; const name: string; params: tnode; res: tdef);
      begin
        createinternmethod(mp,name,params);
        typedef:=res;
        include(callnodeflags,cnf_typedefset)
      end;


    destructor tcallnode.destroy;
      begin
         methodpointer.free;
         callinitblock.free;
         callcleanupblock.free;
         funcretnode.free;
         if assigned(varargsparas) then
           varargsparas.free;
         call_self_node.free;
         call_vmt_node.free;
         vmt_entry.free;
         spezcontext.free;
         inherited destroy;
      end;


    constructor tcallnode.ppuload(t:tnodetype;ppufile:tcompilerppufile);
      begin
        callinitblock:=tblocknode(ppuloadnode(ppufile));
        methodpointer:=ppuloadnode(ppufile);
        call_self_node:=ppuloadnode(ppufile);
        call_vmt_node:=ppuloadnode(ppufile);
        callcleanupblock:=tblocknode(ppuloadnode(ppufile));
        funcretnode:=ppuloadnode(ppufile);
        inherited ppuload(t,ppufile);
        ppufile.getderef(symtableprocentryderef);
{ TODO: FIXME: No withsymtable support}
        symtableproc:=nil;
        ppufile.getderef(procdefinitionderef);
        ppufile.getset(tppuset4(callnodeflags));
      end;


    procedure tcallnode.ppuwrite(ppufile:tcompilerppufile);
      begin
        ppuwritenode(ppufile,callinitblock);
        ppuwritenode(ppufile,methodpointer);
        ppuwritenode(ppufile,call_self_node);
        ppuwritenode(ppufile,call_vmt_node);
        ppuwritenode(ppufile,callcleanupblock);
        ppuwritenode(ppufile,funcretnode);
        inherited ppuwrite(ppufile);
        ppufile.putderef(symtableprocentryderef);
        ppufile.putderef(procdefinitionderef);
        ppufile.putset(tppuset4(callnodeflags));
      end;


    procedure tcallnode.buildderefimpl;
      begin
        inherited buildderefimpl;
        symtableprocentryderef.build(symtableprocentry);
        procdefinitionderef.build(procdefinition);
        if assigned(methodpointer) then
          methodpointer.buildderefimpl;
        if assigned(call_self_node) then
          call_self_node.buildderefimpl;
        if assigned(call_vmt_node) then
          call_vmt_node.buildderefimpl;
        if assigned(callinitblock) then
          callinitblock.buildderefimpl;
        if assigned(callcleanupblock) then
          callcleanupblock.buildderefimpl;
        if assigned(funcretnode) then
          funcretnode.buildderefimpl;
      end;


    procedure tcallnode.derefimpl;
      var
        pt : tcallparanode;
        i  : integer;
      begin
        inherited derefimpl;
        symtableprocentry:=tprocsym(symtableprocentryderef.resolve);
        if assigned(symtableprocentry) then
          symtableproc:=symtableprocentry.owner;
        procdefinition:=tabstractprocdef(procdefinitionderef.resolve);
        if assigned(methodpointer) then
          methodpointer.derefimpl;
        if assigned(call_self_node) then
          call_self_node.derefimpl;
        if assigned(call_vmt_node) then
          call_vmt_node.derefimpl;
        if assigned(callinitblock) then
          callinitblock.derefimpl;
        if assigned(callcleanupblock) then
          callcleanupblock.derefimpl;
        if assigned(funcretnode) then
          funcretnode.derefimpl;
        { generic method has no procdefinition }
        if assigned(procdefinition) then
          begin
            { Connect parasyms }
            pt:=tcallparanode(left);
            while assigned(pt) and
                  (cpf_varargs_para in pt.callparaflags) do
              pt:=tcallparanode(pt.right);
            for i:=procdefinition.paras.count-1 downto 0 do
              begin
                if not assigned(pt) then
                  internalerror(200311077);
                pt.parasym:=tparavarsym(procdefinition.paras[i]);
                pt:=tcallparanode(pt.right);
              end;
            if assigned(pt) then
              internalerror(200311078);
          end;
      end;


    function tcallnode.dogetcopy : tnode;
      var
        n : tcallnode;
        i : integer;
        hp,hpn : tparavarsym;
        oldleft, oldright : tnode;
        para: tcallparanode;
      begin
        { Need to use a hack here to prevent the parameters from being copied.
          The parameters must be copied between callinitblock/callcleanupblock because
          they can reference methodpointer }
        { same goes for right (= self/context for procvars) }
        oldleft:=left;
        left:=nil;
        oldright:=right;
        right:=nil;
        n:=tcallnode(inherited dogetcopy);
        left:=oldleft;
        right:=oldright;
        n.symtableprocentry:=symtableprocentry;
        n.symtableproc:=symtableproc;
        n.procdefinition:=procdefinition;
        n.typedef := typedef;
        n.callnodeflags := callnodeflags;
        n.pushedparasize:=pushedparasize;
        if assigned(callinitblock) then
          n.callinitblock:=tblocknode(callinitblock.dogetcopy)
        else
          n.callinitblock:=nil;
        { callinitblock is copied, now references to the temp will also be copied
          correctly. We can now copy the parameters, funcret and methodpointer }
        if assigned(left) then
          n.left:=left.dogetcopy
        else
          n.left:=nil;
        if assigned(right) then
          n.right:=right.dogetcopy
        else
          n.right:=nil;
        if assigned(methodpointer) then
          n.methodpointer:=methodpointer.dogetcopy
        else
          n.methodpointer:=nil;
        if assigned(call_self_node) then
          n.call_self_node:=call_self_node.dogetcopy
        else
          n.call_self_node:=nil;
        if assigned(call_vmt_node) then
          n.call_vmt_node:=call_vmt_node.dogetcopy
        else
          n.call_vmt_node:=nil;
        if assigned(vmt_entry) then
          n.vmt_entry:=vmt_entry.dogetcopy
        else
          n.vmt_entry:=nil;
        { must be copied before the funcretnode, because the callcleanup block
          may contain a ttempdeletenode that sets the tempinfo of the
          corresponding temp to ti_nextref_set_hookoncopy_nil, and this nextref
          itself may be the funcretnode }
        if assigned(callcleanupblock) then
          n.callcleanupblock:=tblocknode(callcleanupblock.dogetcopy)
        else
          n.callcleanupblock:=nil;
        if assigned(funcretnode) then
          n.funcretnode:=funcretnode.dogetcopy
        else
          n.funcretnode:=nil;
        if assigned(varargsparas) then
         begin
           n.varargsparas:=tvarargsparalist.create(true);
           for i:=0 to varargsparas.count-1 do
             begin
               hp:=tparavarsym(varargsparas[i]);
               hpn:=cparavarsym.create(hp.realname,hp.paranr,hp.varspez,hp.vardef,[]);
               n.varargsparas.add(hpn);
               para:=tcallparanode(n.left);
               while assigned(para) do
                 begin
                   if (para.parasym=hp) then
                     para.parasym:=hpn;
                   para:=tcallparanode(para.right);
                 end;
             end;
         end
        else
         n.varargsparas:=nil;
        n.foverrideprocnamedef:=foverrideprocnamedef;
        result:=n;
      end;


    function tcallnode.docompare(p: tnode): boolean;
      begin
        docompare :=
          inherited docompare(p) and
          (symtableprocentry = tcallnode(p).symtableprocentry) and
          (procdefinition = tcallnode(p).procdefinition) and
          { this implicitly also compares the vmt_entry node, as it is
            deterministically based on the methodpointer }
          (methodpointer.isequal(tcallnode(p).methodpointer)) and
          (((cnf_typedefset in callnodeflags) and (cnf_typedefset in tcallnode(p).callnodeflags) and
            (equal_defs(typedef,tcallnode(p).typedef))) or
           (not(cnf_typedefset in callnodeflags) and not(cnf_typedefset in tcallnode(p).callnodeflags)));
      end;

{$ifdef DEBUG_NODE_XML}
    procedure TCallNode.XMLPrintNodeData(var T: Text);
      begin
        if assigned(procdefinition) and (procdefinition.typ=procdef) then
          WriteLn(T, PrintNodeIndention, '<procname>', SanitiseXMLString(TProcDef(procdefinition).FullProcName(True)), '</procname>')
        else
          begin
            if assigned(symtableprocentry) then
              WriteLn(T, PrintNodeIndention, '<procname>', symtableprocentry.name, '</procname>')
          end;

        if assigned(methodpointer) then
          begin
            WriteLn(T, PrintNodeIndention, '<methodpointer>');
            PrintNodeIndent;
            XMLPrintNode(T, methodpointer);
            PrintNodeUnindent;
            WriteLn(T, PrintNodeIndention, '</methodpointer>');
          end;

        if assigned(funcretnode) then
          begin
            WriteLn(T, PrintNodeIndention, '<funcretnode>');
            PrintNodeIndent;
            XMLPrintNode(T, funcretnode);
            PrintNodeUnindent;
            WriteLn(T, PrintNodeIndention, '</funcretnode>');
          end;

        if assigned(callinitblock) then
          begin
            WriteLn(T, PrintNodeIndention, '<callinitblock>');
            PrintNodeIndent;
            XMLPrintNode(T, callinitblock);
            PrintNodeUnindent;
            WriteLn(T, PrintNodeIndention, '</callinitblock>');
          end;

        if assigned(callcleanupblock) then
          begin
            WriteLn(T, PrintNodeIndention, '<callcleanupblock>');
            PrintNodeIndent;
            XMLPrintNode(T, callcleanupblock);
            PrintNodeUnindent;
            WriteLn(T, PrintNodeIndention, '</callcleanupblock>');
          end;

        inherited XMLPrintNodeData(T);
      end;
{$endif DEBUG_NODE_XML}

    procedure tcallnode.printnodedata(var t:text);
      begin
        if assigned(procdefinition) and
           (procdefinition.typ=procdef) then
          writeln(t,printnodeindention,'proc = ',tprocdef(procdefinition).fullprocname(true))
        else
          begin
            if assigned(symtableprocentry) then
              writeln(t,printnodeindention,'proc = ',symtableprocentry.name)
            else
              writeln(t,printnodeindention,'proc = <nil>');
          end;

        if assigned(methodpointer) then
          begin
            writeln(t,printnodeindention,'methodpointer =');
            printnode(t,methodpointer);
          end;

        if assigned(funcretnode) then
          begin
            writeln(t,printnodeindention,'funcretnode =');
            printnode(t,funcretnode);
          end;

        if assigned(callinitblock) then
          begin
            writeln(t,printnodeindention,'callinitblock =');
            printnode(t,callinitblock);
          end;

        if assigned(callcleanupblock) then
          begin
            writeln(t,printnodeindention,'callcleanupblock =');
            printnode(t,callcleanupblock);
          end;

        if assigned(right) then
          begin
            writeln(t,printnodeindention,'right =');
            printnode(t,right);
          end;

        if assigned(left) then
          begin
            writeln(t,printnodeindention,'left =');
            printnode(t,left);
          end;
      end;


    procedure tcallnode.insertintolist(l : tnodelist);
      begin
      end;


    procedure tcallnode.add_init_statement(n:tnode);
      var
        lastinitstatement, before_firstpass : tstatementnode;
        was_first_statement : boolean;
      begin
        if not assigned(n) then
          exit;
        if not assigned(callinitblock) then
          begin
            callinitblock:=internalstatements(lastinitstatement);
            lastinitstatement.left.free;
            lastinitstatement.left:=n;
            firstpass(tnode(callinitblock));
            exit;
          end;
        lastinitstatement:=laststatement(callinitblock);
        was_first_statement:=(lastinitstatement=callinitblock.statements);
        { all these nodes must be immediately typechecked, because this routine }
        { can be called from pass_1 (i.e., after typecheck has already run) and }
        { moreover, the entire blocks themselves are also only typechecked in   }
        { pass_1, while the the typeinfo is already required after the          }
        { typecheck pass for simplify purposes (not yet perfect, because the    }
        { statementnodes themselves are not typechecked this way)               }
        addstatement(lastinitstatement,n);
        before_firstpass:=lastinitstatement;
        firstpass(tnode(lastinitstatement));
        if was_first_statement and (lastinitstatement<>before_firstpass) then
          callinitblock.statements:=lastinitstatement;
        { Update expectloc for callinitblock }
        callinitblock.expectloc:=lastinitstatement.expectloc;
      end;


    procedure tcallnode.add_done_statement(n:tnode);
      var
        lastdonestatement, before_firstpass : tstatementnode;
        was_first_statement : boolean;
      begin
        if not assigned(n) then
          exit;
        if not assigned(callcleanupblock) then
          begin
            callcleanupblock:=internalstatements(lastdonestatement);
            lastdonestatement.left.free;
            lastdonestatement.left:=n;
            firstpass(tnode(callcleanupblock));
            exit;
          end;
        lastdonestatement:=laststatement(callcleanupblock);
        was_first_statement:=(lastdonestatement=callcleanupblock.statements);
        { see comments in add_init_statement }
        addstatement(lastdonestatement,n);
        before_firstpass:=lastdonestatement;
        firstpass(tnode(lastdonestatement));
        if was_first_statement and (lastdonestatement<>before_firstpass) then
          callcleanupblock.statements:=lastdonestatement;
        { Update expectloc for callcleanupblock }
        callcleanupblock.expectloc:=lastdonestatement.expectloc;
      end;


    function tcallnode.para_count:longint;
      var
        ppn : tcallparanode;
      begin
        result:=0;
        ppn:=tcallparanode(left);
        while assigned(ppn) do
          begin
            if not(assigned(ppn.parasym) and
                   (vo_is_hidden_para in ppn.parasym.varoptions)) then
              inc(result);
            ppn:=tcallparanode(ppn.right);
          end;
      end;


    function tcallnode.required_para_count: longint;
      var
        ppn : tcallparanode;
      begin
        result:=0;
        ppn:=tcallparanode(left);
        while assigned(ppn) do
          begin
            if not(assigned(ppn.parasym) and
                   ((vo_is_hidden_para in ppn.parasym.varoptions) or
                    assigned(ppn.parasym.defaultconstsym))) then
              inc(result);
            ppn:=tcallparanode(ppn.right);
          end;
      end;


    function tcallnode.is_simple_para_load(p:tnode; may_be_in_reg: boolean):boolean;
      var
        hp : tnode;
      begin
        hp:=p;
        while assigned(hp) and
              (hp.nodetype=typeconvn) and
              (ttypeconvnode(hp).convtype=tc_equal) do
          hp:=tunarynode(hp).left;
        result:=(hp.nodetype in [typen,loadvmtaddrn,loadn,temprefn,arrayconstructorn,addrn]);
        if result and
           not(may_be_in_reg) then
          case hp.nodetype of
            loadn:
              result:=(tabstractvarsym(tloadnode(hp).symtableentry).varregable in [vr_none,vr_addr]);
            temprefn:
              result:=not(ti_may_be_in_reg in ttemprefnode(hp).tempflags);
            else
              ;
          end;
      end;


    function tcallnode.getoverrideprocnamedef: tprocdef; inline;
      begin
        result:=foverrideprocnamedef;
      end;


    function look_for_call(var n: tnode; arg: pointer): foreachnoderesult;
      begin
        case n.nodetype of
          calln,asn:
            result := fen_norecurse_true;
          typen,loadvmtaddrn,loadn,temprefn,arrayconstructorn:
            result := fen_norecurse_false;
        else
          result := fen_false;
        end;
      end;

    procedure tcallnode.maybe_load_in_temp(var p:tnode);
      begin
        { Load all complex loads into a temp to prevent
          double calls to a function. We can't simply check for a hp.nodetype=calln }
        if assigned(p) and
           foreachnodestatic(p,@look_for_call,nil) then
          load_in_temp(p);
      end;


    procedure tcallnode.load_in_temp(var p:tnode);
      var
        loadp,
        refp  : tnode;
        hdef : tdef;
        ptemp : ttempcreatenode;
        usederef : boolean;
      begin
        if assigned(p) then
          begin
            { temp create }
            usederef:=(p.resultdef.typ in [arraydef,recorddef]) or
                      is_shortstring(p.resultdef) or
                      is_object(p.resultdef);

            if usederef then
              hdef:=cpointerdef.getreusable(p.resultdef)
            else
              hdef:=p.resultdef;

            ptemp:=ctempcreatenode.create(hdef,hdef.size,tt_persistent,true);
            if usederef then
              begin
                loadp:=caddrnode.create_internal(p);
                refp:=cderefnode.create(ctemprefnode.create(ptemp));
              end
            else
              begin
                loadp:=p;
                refp:=ctemprefnode.create(ptemp)
              end;
            add_init_statement(ptemp);
            add_init_statement(cassignmentnode.create(
                ctemprefnode.create(ptemp),
                loadp));
            add_done_statement(ctempdeletenode.create(ptemp));
            { new tree is only a temp reference }
            p:=refp;
            typecheckpass(p);
          end;
      end;


    function tcallnode.gen_high_tree(var p:tnode;paradef:tdef):tnode;
      { When passing an array to an open array, or a string to an open string,
        some code is needed that generates the high bound of the array. This
        function returns a tree containing the nodes for it. }
      var
        temp: tnode;
        len : integer;
        loadconst : boolean;
        hightree,l,r : tnode;
        defkind: tdeftyp;
      begin
        len:=-1;
        loadconst:=true;
        hightree:=nil;
        { constant strings are internally stored as array of char, but if the
          parameter is a string also treat it like one  }
        defkind:=p.resultdef.typ;
        if (p.nodetype=stringconstn) and
           (paradef.typ=stringdef) then
          defkind:=stringdef;
        case defkind of
          arraydef :
            begin
              if (paradef.typ<>arraydef) then
                internalerror(200405241);
              { passing a string to an array of char }
              if (p.nodetype=stringconstn) and
                 is_char(tarraydef(paradef).elementdef) then
                begin
                  len:=tstringconstnode(p).len;
                  if len>0 then
                   dec(len);
                end
              else
              { handle special case of passing an single array to an array of array }
              if compare_defs(tarraydef(paradef).elementdef,p.resultdef,nothingn)>=te_equal then
                len:=0
              else
                begin
                  { handle via a normal inline in_high_x node }
                  loadconst:=false;
                  { slice? }
                  if (p.nodetype=inlinen) and (tinlinenode(p).inlinenumber=in_slice_x) then
                    with Tcallparanode(Tinlinenode(p).left) do
                      begin
                        {Array slice using slice builtin function.}
                        l:=Tcallparanode(right).left;
                        hightree:=caddnode.create(subn,geninlinenode(in_ord_x,false,l),genintconstnode(1));
                        Tcallparanode(right).left:=nil;

                        {Remove the inline node.}
                        temp:=p;
                        p:=left;
                        Tcallparanode(tinlinenode(temp).left).left:=nil;
                        temp.free;

                        typecheckpass(hightree);
                      end
                  else if (p.nodetype=vecn) and (Tvecnode(p).right.nodetype=rangen) then
                    begin
                      {Array slice using .. operator.}
                      with Trangenode(Tvecnode(p).right) do
                        begin
                          l:=geninlinenode(in_ord_x,false,left);  {Get lower bound.}
                          r:=geninlinenode(in_ord_x,false,right); {Get upper bound.}
                        end;
                      {In the procedure the array range is 0..(upper_bound-lower_bound).}
                      hightree:=caddnode.create(subn,r,l);

                      {Replace the rangnode in the tree by its lower_bound, and
                       dispose the rangenode.}
                      temp:=Tvecnode(p).right;
                      Tvecnode(p).right:=l.getcopy;

                      {Typecheckpass can only be performed *after* the l.getcopy since it
                       can modify the tree, and l is in the hightree.}
                      typecheckpass(hightree);

                      with Trangenode(temp) do
                        begin
                          left:=nil;
                          right:=nil;
                        end;
                      temp.free;

                      {Tree changed from p[l..h] to p[l], recalculate resultdef.}
                      p.resultdef:=nil;
                      typecheckpass(p);
                    end
                  else
                    begin
                      maybe_load_in_temp(p);
                      hightree:=geninlinenode(in_ord_x,false,geninlinenode(in_high_x,false,p.getcopy));
                      typecheckpass(hightree);
                      { only substract low(array) if it's <> 0 }
                      temp:=geninlinenode(in_ord_x,false,geninlinenode(in_low_x,false,p.getcopy));
                      typecheckpass(temp);
                      if (temp.nodetype <> ordconstn) or
                         (tordconstnode(temp).value <> 0) then
                        begin
                          hightree:=caddnode.create(subn,hightree,temp);
                          include(hightree.flags,nf_internal);
                        end
                      else
                        temp.free;
                    end;
                end;
            end;
          stringdef :
            begin
              if is_open_string(paradef) then
               begin
                 { a stringconstn is not a simple parameter and hence would be
                   loaded in a temp, but in that case the high() node
                     a) goes wrong (it cannot deal with a temp node)
                     b) would give a generic result instead of one specific to
                        this constant string
                 }
                 if p.nodetype<>stringconstn then
                   maybe_load_in_temp(p);
                 { handle via a normal inline in_high_x node }
                 loadconst := false;
                 hightree := geninlinenode(in_high_x,false,p.getcopy);
               end
              else
               { handle special case of passing an single string to an array of string }
               if compare_defs(tarraydef(paradef).elementdef,p.resultdef,nothingn)>=te_equal then
                len:=0
              else
               { passing a string to an array of char }
               if (p.nodetype=stringconstn) and
                  is_char(tarraydef(paradef).elementdef) then
                 begin
                   len:=tstringconstnode(p).len;
                   if len>0 then
                    dec(len);
                 end
              else
                begin
                  maybe_load_in_temp(p);
                  hightree:=caddnode.create(subn,geninlinenode(in_length_x,false,p.getcopy),
                                            cordconstnode.create(1,sizesinttype,false));
                  loadconst:=false;
                end;
           end;
        else
          len:=0;
        end;
        if loadconst then
          hightree:=cordconstnode.create(len,sizesinttype,true)
        else
          begin
            if not assigned(hightree) then
              internalerror(200304071);
            { Need to use explicit, because it can also be a enum }
            hightree:=ctypeconvnode.create_internal(hightree,sizesinttype);
          end;
        result:=hightree;
      end;


    function tcallnode.gen_procvar_context_tree_self:tnode;
      begin
        { Load tmehodpointer(right).self }
        result:=genloadfield(ctypeconvnode.create_internal(
          right.getcopy,methodpointertype),
          'self');
      end;


    function tcallnode.gen_procvar_context_tree_parentfp: tnode;
      begin
        { Load tnestedprocpointer(right).parentfp }
        result:=genloadfield(ctypeconvnode.create_internal(
          right.getcopy,nestedprocpointertype),
          'parentfp');
      end;


    function tcallnode.gen_self_tree:tnode;
      var
        selftree : tnode;
        selfdef  : tdef;
        temp     : ttempcreatenode;
      begin
        selftree:=nil;

        { When methodpointer was a callnode we must load it first into a
          temp to prevent processing the callnode twice }
        if (methodpointer.nodetype=calln) then
          internalerror(200405121);

        { Objective-C: objc_convert_to_message_send() already did all necessary
          transformation on the methodpointer }
        if (procdefinition.typ=procdef) and
           (po_objc in tprocdef(procdefinition).procoptions) then
          selftree:=methodpointer.getcopy
        { inherited }
        else if (cnf_inherited in callnodeflags) then
          begin
            selftree:=safe_call_self_node.getcopy;
           { we can call an inherited class static/method from a regular method
             -> self node must change from instance pointer to vmt pointer)
           }
           if (procdefinition.procoptions*[po_classmethod,po_staticmethod] <> []) and
              (selftree.resultdef.typ<>classrefdef) then
             selftree:=cloadvmtaddrnode.create(selftree);
          end
        else
          { constructors }
          if (procdefinition.proctypeoption=potype_constructor) then
            begin
              if (methodpointer.resultdef.typ=classrefdef) or
                 (cnf_new_call in callnodeflags) then
                if not is_javaclass(tdef(procdefinition.owner.defowner)) then
                  begin
                    if (cnf_new_call in callnodeflags) then
                      { old-style object: push 0 as self }
                      selftree:=cpointerconstnode.create(0,voidpointertype)
                    else
                      begin
                        { class-style: push classtype }
                        selftree:=methodpointer.getcopy;
                        if selftree.nodetype=typen then
                          begin
                            selftree:=cloadvmtaddrnode.create(selftree);
                            tloadvmtaddrnode(selftree).forcall:=true;
                          end;
                      end;
                  end
                else
                 { special handling for Java constructors, handled in
                   tjvmcallnode.extra_pre_call_code }
                  selftree:=cnothingnode.create
              else
                begin
                  if methodpointer.nodetype=typen then
                    if (methodpointer.resultdef.typ<>objectdef) then
                      begin
                        if not(target_info.system in systems_jvm) then
                          begin
                            { TSomeRecord.Constructor call. We need to allocate }
                            { self node as a temp node of the result type       }
                            temp:=ctempcreatenode.create(methodpointer.resultdef,methodpointer.resultdef.size,tt_persistent,false);
                            add_init_statement(temp);
                            add_done_statement(ctempdeletenode.create_normal_temp(temp));
                            selftree:=ctemprefnode.create(temp);
                          end
                        else
                          begin
                            { special handling for Java constructors, handled in
                              tjvmcallnode.extra_pre_call_code }
                            selftree:=cnothingnode.create
                          end;
                      end
                    else
                      selftree:=safe_call_self_node.getcopy
                  else
                    selftree:=methodpointer.getcopy;
                end;
            end
        else
          { Calling a static/class method }
          if (po_classmethod in procdefinition.procoptions) or
             (po_staticmethod in procdefinition.procoptions) then
            begin
              if (procdefinition.typ<>procdef) then
                internalerror(200305062);
              { if the method belongs to a helper then we need to use the
                extended type for references to Self }
              if is_objectpascal_helper(tprocdef(procdefinition).struct) then
                selfdef:=tobjectdef(tprocdef(procdefinition).struct).extendeddef
              else
                selfdef:=tprocdef(procdefinition).struct;
              if ((selfdef.typ in [recorddef,objectdef]) and
                  (oo_has_vmt in tabstractrecorddef(selfdef).objectoptions)) or
                 { all Java classes have a "VMT" }
                 (target_info.system in systems_jvm) then
                begin
                  { we only need the vmt, loading self is not required and there is no
                    need to check for typen, because that will always get the
                    loadvmtaddrnode added }
                  selftree:=methodpointer.getcopy;
                  if (methodpointer.resultdef.typ<>classrefdef) or
                     (methodpointer.nodetype = typen) then
                    selftree:=cloadvmtaddrnode.create(selftree);
                end
              else
                selftree:=cpointerconstnode.create(0,voidpointertype);
            end
        else
          begin
            if methodpointer.nodetype=typen then
              selftree:=safe_call_self_node.getcopy
            else
              selftree:=methodpointer.getcopy;
          end;
        result:=selftree;
      end;

    function tcallnode.use_caller_self(check_for_callee_self: boolean): boolean;
      var
        i: longint;
        ps: tparavarsym;
      begin
        result:=false;
        { is there a self parameter? }
        if check_for_callee_self then
          begin
            ps:=nil;
            for i:=0 to procdefinition.paras.count-1 do
              begin
                ps:=tparavarsym(procdefinition.paras[i]);
                if vo_is_self in ps.varoptions then
                  break;
                ps:=nil;
              end;

            if not assigned(ps) then
              exit;
          end;

        { we need to load the'self' parameter of the current routine as the
          'self' parameter of the called routine if
            1) we're calling an inherited routine
            2) we're calling a constructor via type.constructorname and
               type is not a classrefdef (i.e., we're calling a constructor like
               a regular method)
            3) we're calling any regular (non-class/non-static) method via
               a typenode (the methodpointer is then that typenode, but the
               passed self node must become the current self node)

          In other cases, we either don't have to pass the 'self' parameter of
          the current routine to the called one, or methodpointer will already
          contain it (e.g. because a method was called via "method", in which
          case the parser already passed 'self' as the method pointer, or via
          "self.method") }
        if (cnf_inherited in callnodeflags) or
           ((procdefinition.proctypeoption=potype_constructor) and
            not((methodpointer.resultdef.typ=classrefdef) or
                (cnf_new_call in callnodeflags)) and
               (methodpointer.nodetype=typen) and
               (methodpointer.resultdef.typ=objectdef)) or
           (assigned(methodpointer) and
            (procdefinition.proctypeoption<>potype_constructor) and
            not(po_classmethod in procdefinition.procoptions) and
            not(po_staticmethod in procdefinition.procoptions) and
            (methodpointer.nodetype=typen)) then
          result:=true;
      end;


    procedure tcallnode.maybe_gen_call_self_node;
      begin
        if cnf_call_self_node_done in callnodeflags then
          exit;
        include(callnodeflags,cnf_call_self_node_done);
        if use_caller_self(true) then
          call_self_node:=load_self_node;
      end;


    procedure tcallnode.register_created_object_types;

      function checklive(def: tdef): boolean;
        begin
          if assigned(current_procinfo) and
             not(po_inline in current_procinfo.procdef.procoptions) and
             not wpoinfomanager.symbol_live(current_procinfo.procdef.mangledname) then
            begin
{$ifdef debug_deadcode}
              writeln(' NOT adding creadion of ',def.typename,' because performed in dead stripped proc: ',current_procinfo.procdef.typename);
{$endif debug_deadcode}
              result:=false;
            end
          else
            result:=true;
        end;

      var
        crefdef,
        systobjectdef : tdef;
      begin
        { only makes sense for methods }
        if not assigned(methodpointer) then
          exit;
        if (methodpointer.resultdef.typ=classrefdef) then
          begin
            { constructor call via classreference => allocate memory }
            if (procdefinition.proctypeoption=potype_constructor) then
              begin
                { Only a typenode can be passed when it is called with <class of xx>.create }
                if (methodpointer.nodetype=typen) then
                  begin
                    if checklive(methodpointer.resultdef) then
                      { we know the exact class type being created }
                      tclassrefdef(methodpointer.resultdef).pointeddef.register_created_object_type
                  end
                else
                  begin
                    { the loadvmtaddrnode is already created in case of classtype.create }
                    if (methodpointer.nodetype=loadvmtaddrn) and
                       (tloadvmtaddrnode(methodpointer).left.nodetype=typen) then
                      begin
                        if checklive(methodpointer.resultdef) then
                          tclassrefdef(methodpointer.resultdef).pointeddef.register_created_object_type
                      end
                    else
                      begin
                        if checklive(methodpointer.resultdef) then
                          begin
                            { special case: if the classref comes from x.classtype (with classtype,
                              being tobject.classtype) then the created instance is x or a descendant
                              of x (rather than tobject or a descendant of tobject)
                            }
                            systobjectdef:=search_system_type('TOBJECT').typedef;
                            if (methodpointer.nodetype=calln) and
                               { not a procvar call }
                               not assigned(right) and
                               { procdef is owned by system.tobject }
                               (tprocdef(tcallnode(methodpointer).procdefinition).owner.defowner=systobjectdef) and
                               { we're calling system.tobject.classtype }
                               (tcallnode(methodpointer).symtableprocentry.name='CLASSTYPE') and
                               { could again be a classrefdef, but unlikely }
                               (tcallnode(methodpointer).methodpointer.resultdef.typ=objectdef) and
                               { don't go through this trouble if it was already a tobject }
                               (tcallnode(methodpointer).methodpointer.resultdef<>systobjectdef) then
                              begin
                                { register this object type as classref, so all descendents will also
                                  be marked as instantiatable (only the pointeddef will actually be
                                  recorded, so it's no problem that the clasrefdef is only temporary)
                                }
                                crefdef:=cclassrefdef.create(tcallnode(methodpointer).methodpointer.resultdef);
                                { and register it }
                                crefdef.register_created_object_type;
                              end
                             else
                               { the created class can be any child class as well -> register classrefdef }
                               methodpointer.resultdef.register_created_object_type;
                          end;
                      end;
                  end;
              end
          end
        else
        { Old style object }
         if is_object(methodpointer.resultdef) then
          begin
            { constructor with extended syntax called from new }
            if (cnf_new_call in callnodeflags) then
              begin
                if checklive(methodpointer.resultdef) then
                  methodpointer.resultdef.register_created_object_type;
              end
            else
            { normal object call like obj.proc }
              if not(cnf_dispose_call in callnodeflags) and
                 not(cnf_inherited in callnodeflags) and
                 not(cnf_member_call in callnodeflags) then
                begin
                  if (procdefinition.proctypeoption=potype_constructor) then
                    begin
                      if (methodpointer.nodetype<>typen) and
                         checklive(methodpointer.resultdef) then
                        methodpointer.resultdef.register_created_object_type;
                    end
                end;
          end;
       end;


    function tcallnode.get_expect_loc: tcgloc;
      var
        realresdef: tstoreddef;
      begin
        if not assigned(typedef) then
          realresdef:=tstoreddef(resultdef)
        else
          realresdef:=tstoreddef(typedef);
        if realresdef.is_intregable then
          result:=LOC_REGISTER
        else if (realresdef.typ=floatdef) and
          not(cs_fp_emulation in current_settings.moduleswitches) then
          if use_vectorfpu(realresdef) then
            result:=LOC_MMREGISTER
          else
            result:=LOC_FPUREGISTER
        else
          result:=LOC_REFERENCE
      end;


    function tcallnode.safe_call_self_node: tnode;
      begin
        if not assigned(call_self_node) then
          begin
            CGMessage(parser_e_illegal_expression);
            call_self_node:=cerrornode.create;
          end;
        result:=call_self_node;
      end;


    procedure tcallnode.gen_vmt_entry_load;
      var
        vmt_def: trecorddef;
      begin
        if not assigned(right) and
           not assigned(overrideprocnamedef) and
           (po_virtualmethod in procdefinition.procoptions) and
           not is_objectpascal_helper(tprocdef(procdefinition).struct) and
           assigned(methodpointer) and
           (methodpointer.nodetype<>typen) then
          begin
            vmt_entry:=load_vmt_for_self_node(methodpointer.getcopy);
            { get the right entry in the VMT }
            vmt_entry:=cderefnode.create(vmt_entry);
            typecheckpass(vmt_entry);
            vmt_def:=trecorddef(vmt_entry.resultdef);
            { tobjectdef(tprocdef(procdefinition).struct) can be a parent of the
              methodpointer's resultdef, but the vmtmethodoffset of the method
              in that objectdef is obviously the same as in any child class }
            vmt_entry:=csubscriptnode.create(
                trecordsymtable(vmt_def.symtable).findfieldbyoffset(
                  tobjectdef(tprocdef(procdefinition).struct).vmtmethodoffset(tprocdef(procdefinition).extnumber)
                ),
               vmt_entry
              );
            firstpass(vmt_entry);
          end;
      end;


    procedure tcallnode.gen_syscall_para(para: tcallparanode);
      begin
        { unsupported }
        internalerror(2014040101);
      end;


    procedure tcallnode.objc_convert_to_message_send;
      var
        block,
        selftree      : tnode;
        statements    : tstatementnode;
        field         : tfieldvarsym;
        temp          : ttempcreatenode;
        selfrestype,
        objcsupertype : tdef;
        srsym         : tsym;
        srsymtable    : tsymtable;
        msgsendname   : string;
      begin
        if not(m_objectivec1 in current_settings.modeswitches) then
          Message(parser_f_modeswitch_objc_required);
        { typecheck pass must already have run on the call node,
          because pass1 calls this method
        }

        { default behaviour: call objc_msgSend and friends;
          64 bit targets for Mac OS X can override this as they
          can call messages via an indirect function call similar to
          dynamically linked functions, ARM maybe as well (not checked)

          Which variant of objc_msgSend is used depends on the
          result type, and on whether or not it's an inherited call.
        }

        { make sure we don't perform this transformation twice in case
          firstpass would be called multiple times }
        include(callnodeflags,cnf_objc_processed);

        { make sure the methodpointer doesn't get translated into a call
          as well (endless loop) }
        if methodpointer.nodetype=loadvmtaddrn then
          tloadvmtaddrnode(methodpointer).forcall:=true;

        { A) set the appropriate objc_msgSend* variant to call }

        { The AArch64 abi does not require special handling for struct returns }
{$ifndef aarch64}
        { record returned via implicit pointer }
        if paramanager.ret_in_param(resultdef,procdefinition) then
          begin
            if not(cnf_inherited in callnodeflags) then
              msgsendname:='OBJC_MSGSEND_STRET'
{$if defined(onlymacosx10_6) or defined(arm) }
            else if (target_info.system in systems_objc_nfabi) then
              msgsendname:='OBJC_MSGSENDSUPER2_STRET'
{$endif onlymacosx10_6 or arm}
            else
              msgsendname:='OBJC_MSGSENDSUPER_STRET'
          end
{$ifdef i386}
        { special case for fpu results on i386 for non-inherited calls }
        { TODO: also for x86_64 "extended" results }
        else if (resultdef.typ=floatdef) and
                not(cnf_inherited in callnodeflags) then
          msgsendname:='OBJC_MSGSEND_FPRET'
{$endif i386}
        { default }
        else
{$endif aarch64}
             if not(cnf_inherited in callnodeflags) then
          msgsendname:='OBJC_MSGSEND'
{$if defined(onlymacosx10_6) or defined(arm) or defined(aarch64)}
        else if (target_info.system in systems_objc_nfabi) then
          msgsendname:='OBJC_MSGSENDSUPER2'
{$endif onlymacosx10_6 or arm}
        else
          msgsendname:='OBJC_MSGSENDSUPER';

        { get the mangled name }
        srsym:=nil;
        if not searchsym_in_named_module('OBJC',msgsendname,srsym,srsymtable) or
           (srsym.typ<>procsym) or
           (tprocsym(srsym).ProcdefList.count<>1) then
          Message1(cg_f_unknown_compilerproc,'objc.'+msgsendname);
        foverrideprocnamedef:=tprocdef(tprocsym(srsym).ProcdefList[0]);

        { B) Handle self }
        { 1) in case of sending a message to a superclass, self is a pointer to
             an objc_super record
        }
        if (cnf_inherited in callnodeflags) then
          begin
             block:=internalstatements(statements);
             objcsupertype:=search_named_unit_globaltype('OBJC','OBJC_SUPER',true).typedef;
             if (objcsupertype.typ<>recorddef) then
               internalerror(2009032901);
             { temp for the for the objc_super record }
             temp:=ctempcreatenode.create(objcsupertype,objcsupertype.size,tt_persistent,false);
             addstatement(statements,temp);
             { initialize objc_super record }
             selftree:=safe_call_self_node.getcopy;

             { we can call an inherited class static/method from a regular method
               -> self node must change from instance pointer to vmt pointer)
             }
             if (po_classmethod in procdefinition.procoptions) and
                (selftree.resultdef.typ<>classrefdef) then
               begin
                 selftree:=cloadvmtaddrnode.create(selftree);
                 { since we're in a class method of the current class, its
                   information has already been initialized (and that of all of
                   its parent classes too) }
                 tloadvmtaddrnode(selftree).forcall:=true;
                 typecheckpass(selftree);
               end;
             selfrestype:=selftree.resultdef;
             field:=tfieldvarsym(trecorddef(objcsupertype).symtable.find('RECEIVER'));
             if not assigned(field) then
               internalerror(2009032902);
            { first the destination object/class instance }
             addstatement(statements,
               cassignmentnode.create(
                 csubscriptnode.create(field,ctemprefnode.create(temp)),
                 selftree
               )
             );
             { and secondly, the class type in which the selector must be looked
               up (the parent class in case of an instance method, the parent's
               metaclass in case of a class method) }
             field:=tfieldvarsym(trecorddef(objcsupertype).symtable.find('_CLASS'));
             if not assigned(field) then
               internalerror(2009032903);
             addstatement(statements,
               cassignmentnode.create(
                 csubscriptnode.create(field,ctemprefnode.create(temp)),
                 objcsuperclassnode(selftree.resultdef)
               )
             );
             { result of this block is the address of this temp }
             addstatement(statements,ctypeconvnode.create_internal(
               caddrnode.create_internal(ctemprefnode.create(temp)),selfrestype)
             );
             { replace the method pointer with the address of this temp }
             methodpointer.free;
             methodpointer:=block;
             typecheckpass(block);
          end
        else
        { 2) regular call (not inherited) }
          begin
            { a) If we're calling a class method, use a class ref.  }
            if (po_classmethod in procdefinition.procoptions) and
               ((methodpointer.nodetype=typen) or
                (methodpointer.resultdef.typ<>classrefdef)) then
              begin
                methodpointer:=cloadvmtaddrnode.create(methodpointer);
                { no need to obtain the class ref by calling class(), sending
                  this message will initialize it if necessary }
                tloadvmtaddrnode(methodpointer).forcall:=true;
                firstpass(methodpointer);
              end;
          end;
      end;


    function tcallnode.gen_vmt_tree:tnode;
      var
        vmttree : tnode;
      begin
        vmttree:=nil;
        if not(procdefinition.proctypeoption in [potype_constructor,potype_destructor]) then
          internalerror(200305051);

        { When methodpointer was a callnode we must load it first into a
          temp to prevent the processing callnode twice }
        if (methodpointer.nodetype=calln) then
          internalerror(200405122);

        { Handle classes and legacy objects separate to make it
          more maintainable }
        if (methodpointer.resultdef.typ=classrefdef) then
          begin
            if not is_class(tclassrefdef(methodpointer.resultdef).pointeddef) then
              internalerror(200501041);

            { constructor call via classreference => allocate memory }
            if (procdefinition.proctypeoption=potype_constructor) then
              begin
                vmttree:=cpointerconstnode.create(1,voidpointertype);
              end
            else  { <class of xx>.destroy is not valid }
              InternalError(2014020601);
          end
        else
        { Class style objects }
         if is_class(methodpointer.resultdef) then
          begin
            { inherited call, no create/destroy }
            if (cnf_inherited in callnodeflags) then
              vmttree:=cpointerconstnode.create(0,voidpointertype)
            else
              { do not create/destroy when called from member function
                without specifying self explicit }
              if (cnf_member_call in callnodeflags) then
                begin
                  { destructor (in the same class, since cnf_member_call):
                    if not called from a destructor then
                      call beforedestruction and release instance, vmt=1
                    else
                      don't release instance, vmt=0
                    constructor (in the same class, since cnf_member_call):
                      if called from a constructor then
                        don't call afterconstruction, vmt=0
                      else
                        call afterconstrution but not NewInstance, vmt=-1 }
                  if (procdefinition.proctypeoption=potype_destructor) then
                    if (current_procinfo.procdef.proctypeoption<>potype_constructor) then
                      vmttree:=cpointerconstnode.create(1,voidpointertype)
                    else
                      vmttree:=cpointerconstnode.create(0,voidpointertype)
                  else if (current_procinfo.procdef.proctypeoption=potype_constructor) and
                          (procdefinition.proctypeoption=potype_constructor) then
                    vmttree:=cpointerconstnode.create(0,voidpointertype)
                  else
                    vmttree:=cpointerconstnode.create(TConstPtrUInt(-1),voidpointertype);
                end
            else
            { normal call to method like cl1.proc }
              begin
                { destructor:
                     if not(called from exception block in constructor) or
                        (called from afterconstruction)
                       call beforedestruction and release instance, vmt=1
                     else
                       don't call beforedestruction and release instance, vmt=-1
                  constructor:
                    if called from a constructor in the same class using self.create then
                      don't call afterconstruction, vmt=0
                    else
                      call afterconstruction, vmt=1 }
                if (procdefinition.proctypeoption=potype_destructor) then
                  if (cnf_create_failed in callnodeflags) and
                     is_class(methodpointer.resultdef) then
                    vmttree:=call_vmt_node.getcopy
                  else if not(cnf_create_failed in callnodeflags) then
                    vmttree:=cpointerconstnode.create(1,voidpointertype)
                  else
                    vmttree:=cpointerconstnode.create(TConstPtrUInt(-1),voidpointertype)
                else
                  begin
                    if (current_procinfo.procdef.proctypeoption=potype_constructor) and
                       (procdefinition.proctypeoption=potype_constructor) and
                       (methodpointer.nodetype=loadn) and
                       (loadnf_is_self in tloadnode(methodpointer).loadnodeflags) then
                      vmttree:=cpointerconstnode.create(0,voidpointertype)
                    else
                      vmttree:=cpointerconstnode.create(TConstPtrUInt(-1),voidpointertype);
                  end;
              end;
          end
        else
        { Old style object }
          begin
            { constructor with extended syntax called from new }
            if (cnf_new_call in callnodeflags) then
                vmttree:=cloadvmtaddrnode.create(ctypenode.create(methodpointer.resultdef))
            else
              { destructor with extended syntax called from dispose }
              { value -1 is what fpc_help_constructor() changes VMT to when it allocates memory }
              if (cnf_dispose_call in callnodeflags) then
                vmttree:=cpointerconstnode.create(TConstPtrUInt(-1),voidpointertype)
            else
              { destructor called from exception block in constructor }
              if (cnf_create_failed in callnodeflags) then
                vmttree:=ctypeconvnode.create_internal(call_vmt_node.getcopy,voidpointertype)
            else
              { inherited call, no create/destroy }
              if (cnf_inherited in callnodeflags) then
                vmttree:=cpointerconstnode.create(0,voidpointertype)
            else
              { do not create/destroy when called from member function
                without specifying self explicit }
              if (cnf_member_call in callnodeflags) then
                begin
                  { destructor: don't release instance, vmt=0
                    constructor: don't initialize instance, vmt=0 }
                  vmttree:=cpointerconstnode.create(0,voidpointertype)
                end
            else
            { normal object call like obj.proc }
             begin
               { destructor: direct call, no dispose, vmt=0
                 constructor: initialize object, load vmt }
               if (procdefinition.proctypeoption=potype_constructor) then
                 begin
                   { old styled inherited call? }
                   if (methodpointer.nodetype=typen) then
                     vmttree:=cpointerconstnode.create(0,voidpointertype)
                   else
                     vmttree:=cloadvmtaddrnode.create(ctypenode.create(methodpointer.resultdef))
                 end
               else
                 vmttree:=cpointerconstnode.create(0,voidpointertype);
             end;
          end;
        result:=vmttree;
      end;


    function tcallnode.gen_block_context: tnode;
      begin
        { the self parameter of a block invocation is that address of the
          block literal (which is what right contains) }
        result:=right.getcopy;
      end;


    function check_funcret_used_as_para(var n: tnode; arg: pointer): foreachnoderesult;
      var
        destsym : tsym absolute arg;
      begin
        result := fen_false;
        if (n.nodetype=loadn) and
           (tloadnode(n).symtableentry = destsym) then
          result := fen_norecurse_true;
      end;


    function check_funcret_temp_used_as_para(var n: tnode; arg: pointer): foreachnoderesult;
      var
        tempinfo : ptempinfo absolute arg;
      begin
        result := fen_false;
        if (n.nodetype=temprefn) and
           (ttemprefnode(n).tempinfo = tempinfo) then
          result := fen_norecurse_true;
      end;


    function tcallnode.funcret_can_be_reused:boolean;
      var
        realassignmenttarget: tnode;
        alignment: longint;
      begin
        result:=false;

        { we are processing an assignment node? }
        if not(assigned(aktassignmentnode) and
               (aktassignmentnode.right=self) and
               (aktassignmentnode.left.resultdef=resultdef)) then
          exit;

        { destination must be able to be passed as var parameter }
        if not valid_for_var(aktassignmentnode.left,false) then
          exit;

        { destination must be a simple load so it doesn't need a temp when
          it is evaluated }
        if not is_simple_para_load(aktassignmentnode.left,false) then
          exit;

        { remove possible typecasts }
        realassignmenttarget:=actualtargetnode(@aktassignmentnode.left)^;

        { when the result is returned by value (instead of by writing it to the
          address passed in a hidden parameter), aktassignmentnode.left will
          only be changed once the function has returned and we don't have to
          perform any checks regarding whether it may alias with one of the
          parameters -- unless this is an inline function, in which case
          writes to the function result will directly change it and we do have
          to check for potential aliasing }
        if not paramanager.ret_in_param(resultdef,procdefinition) then
           begin
             if not(cnf_do_inline in callnodeflags) then
                begin
                  result:=true;
                  exit;
                end
             else
               begin
                 { don't replace the function result if we are inlining and if
                   the destination is complex, this could lead to lengthy
                   code in case the function result is used often and it is
                   assigned e.g. to a threadvar }
                 if node_complexity(aktassignmentnode.left)>1 then
                   exit;
               end;
           end;

        { if the result is the same as the self parameter (in case of objects),
          we can't optimise. We have to check this explicitly becaise
          hidden parameters such as self have not yet been inserted at this
          point
        }
        if assigned(methodpointer) and
           realassignmenttarget.isequal(actualtargetnode(@methodpointer)^) then
          exit;

        { when we substitute a function result inside an inlined function,
          we may take the address of this function result. Therefore the
          substituted function result may not be in a register, as we cannot
          take its address in that case                                      }
        if (realassignmenttarget.nodetype=temprefn) and
           not(ti_addr_taken in ttemprefnode(realassignmenttarget).tempflags) and
           not(ti_may_be_in_reg in ttemprefnode(realassignmenttarget).tempflags) then
          begin
            result:=not foreachnodestatic(left,@check_funcret_temp_used_as_para,ttemprefnode(realassignmenttarget).tempinfo);
            exit;
          end;

        if (realassignmenttarget.nodetype=loadn) and
           { nested procedures may access the current procedure's locals }
           (procdefinition.parast.symtablelevel=normal_function_level) and
           { must be a local variable, a value para or a hidden function result }
           { parameter (which can be passed by address, but in that case it got }
           { through these same checks at the caller side and is thus safe )    }
           { other option: we're calling a compilerproc, because those don't
             rely on global state
           }
           ((po_compilerproc in procdefinition.procoptions) or
            (
             (
              (tloadnode(realassignmenttarget).symtableentry.typ=localvarsym) or
              (
               (tloadnode(realassignmenttarget).symtableentry.typ=paravarsym) and
               ((tparavarsym(tloadnode(realassignmenttarget).symtableentry).varspez = vs_value) or
                (vo_is_funcret in tparavarsym(tloadnode(realassignmenttarget).symtableentry).varoptions))
              )
             ) and
             { the address may not have been taken of the variable/parameter, because }
             { otherwise it's possible that the called function can access it via a   }
             { global variable or other stored state                                  }
             (
              not(tabstractvarsym(tloadnode(realassignmenttarget).symtableentry).addr_taken) and
              (tabstractvarsym(tloadnode(realassignmenttarget).symtableentry).varregable in [vr_none,vr_addr])
             )
            )
           ) then
          begin
            { If the funcret is also used as a parameter we can't optimize because the funcret
              and the parameter will point to the same address. That means that a change of the result variable
              will result also in a change of the parameter value }
            result:=not foreachnodestatic(left,@check_funcret_used_as_para,tloadnode(realassignmenttarget).symtableentry);
            { ensure that it is aligned using the default alignment }
            alignment:=tabstractvarsym(tloadnode(realassignmenttarget).symtableentry).vardef.alignment;
            if (used_align(alignment,target_info.alignment.localalignmin,target_info.alignment.localalignmax)<>
                used_align(alignment,current_settings.alignment.localalignmin,current_settings.alignment.localalignmax)) then
              result:=false;
            exit;
          end;
      end;


    procedure tcallnode.maybe_create_funcret_node;
      var
        temp : ttempcreatenode;
      begin
        if procdefinition.proctypeoption=potype_constructor then
          exit;
        { For the function result we need to create a temp node for:
            - Inlined functions
            - Types requiring initialization/finalization
            - Types passed in parameters }
        if not is_void(resultdef) and
           not assigned(funcretnode) and
            (
             (cnf_do_inline in callnodeflags) or
             is_managed_type(resultdef) or
             paramanager.ret_in_param(resultdef,procdefinition)
            ) then
          begin
            { Optimize calls like x:=f() where we can use x directly as
              result instead of using a temp. Condition is that x cannot be accessed from f().
              This implies that x is a local variable or value parameter of the current block
              and its address is not passed to f. One problem: what if someone takes the
              address of x, puts it in a pointer variable/field and then accesses it that way
              from within the function? This is solved (in a conservative way) using the
              ti_addr_taken flag.

              When the result is not not passed in a parameter there are no problem because
              then it means only reference counted types (eg. ansistrings) that need a decr
              of the refcount before being assigned. This is all done after the call so there
              is no issue with exceptions and possible use of the old value in the called
              function }
            if funcret_can_be_reused then
              begin
                funcretnode:=aktassignmentnode.left.getcopy;
                include(funcretnode.flags,nf_is_funcret);
                { notify the assignment node that the assignment can be removed }
                include(aktassignmentnode.flags,nf_assign_done_in_right);
              end
            else
              begin
                temp:=ctempcreatenode.create(resultdef,resultdef.size,tt_persistent,
                  (cnf_do_inline in callnodeflags) and
                  not(tabstractvarsym(tprocdef(procdefinition).funcretsym).varregable in [vr_none,vr_addr]));
                include(temp.flags,nf_is_funcret);
                { if a managed type is returned by reference, assigning something
                  to the result on the caller side will take care of decreasing
                  the reference count }
                if paramanager.ret_in_param(resultdef,procdefinition) then
                  temp.includetempflag(ti_nofini);
                add_init_statement(temp);
                { When the function result is not used in an inlined function
                  we need to delete the temp. This can currently only be done by
                  a tempdeletenode and not after converting it to a normal temp }
                if not(cnf_return_value_used in callnodeflags) and
                   (cnf_do_inline in callnodeflags) then
                  add_done_statement(ctempdeletenode.create(temp))
                else
                  add_done_statement(ctempdeletenode.create_normal_temp(temp));
                funcretnode:=ctemprefnode.create(temp);
                include(funcretnode.flags,nf_is_funcret);
              end;
          end;
      end;


    procedure tcallnode.gen_hidden_parameters;
      var
        para : tcallparanode;
      begin
        para:=tcallparanode(left);
        while assigned(para) do
          begin
            { The processing of high() and typeinfo() is already
              done in the typecheckpass. We only need to process the
              nodes that still have a nothingn }
            if (vo_is_hidden_para in para.parasym.varoptions) and
               (para.left.nodetype=nothingn) then
              begin
                { remove dummy nothingn }
                para.left.free;
                para.left:=nil;
                { generate the corresponding nodes for the hidden parameter type }
                if (vo_is_funcret in para.parasym.varoptions) then
                 begin
                   if not assigned(funcretnode) then
                     internalerror(200709083);
                   { if funcretnode is a temprefnode, we have to keep it intact
                     if it may have been created in maybe_create_funcret_node(),
                     because then it will also be destroyed by a
                     ctempdeletenode.create_normal_temp() in the cleanup code
                     for this call code. In that case we have to copy this
                     ttemprefnode after the tempdeletenode to reset its
                     tempinfo^.hookoncopy. This is done by copying funcretnode
                     in tcallnode.getcopy(), but for that to work we can't reset
                     funcretnode to nil here. }
                   if (funcretnode.nodetype<>temprefn) or
                      (not(cnf_return_value_used in callnodeflags) and
                       (cnf_do_inline in callnodeflags)) then
                     begin
                       para.left:=funcretnode;
                       funcretnode:=nil;
                     end
                   else
                     para.left:=funcretnode.getcopy;
                 end
                else
                 if vo_is_self in para.parasym.varoptions then
                   begin
                     if assigned(right) then
                       para.left:=gen_procvar_context_tree_self
                     else
                       para.left:=gen_self_tree;
                     { make sure that e.g. the self pointer of an advanced
                       record does not become a regvar, because it's a vs_var
                       parameter }
                     if paramanager.push_addr_param(para.parasym.varspez,para.parasym.vardef,
                         procdefinition.proccalloption) then
                       make_not_regable(para.left,[ra_addr_regable]);
                   end
                else
                 if vo_is_vmt in para.parasym.varoptions then
                   begin
                     para.left:=gen_vmt_tree;
                   end
                else
                 if vo_is_syscall_lib in para.parasym.varoptions then
                   gen_syscall_para(para)
                else
                 if vo_is_range_check in para.parasym.varoptions then
                   begin
                     para.left:=cordconstnode.create(Ord(cs_check_range in current_settings.localswitches),pasbool1type,false);
                   end
                else
                 if vo_is_overflow_check in para.parasym.varoptions then
                   begin
                     para.left:=cordconstnode.create(Ord(cs_check_overflow in current_settings.localswitches),pasbool1type,false);
                   end
                else
                  if vo_is_msgsel in para.parasym.varoptions then
                    begin
                      para.left:=cobjcselectornode.create(cstringconstnode.createstr(tprocdef(procdefinition).messageinf.str^));
                    end;
              end;
            if not assigned(para.left) then
              internalerror(200709084);
            para:=tcallparanode(para.right);
          end;
      end;


    procedure tcallnode.verifyabstract(sym:TObject;arg:pointer);
      var
        pd : tprocdef;
        i  : longint;
        j  : integer;
        hs : string;
      begin
        if (tsym(sym).typ<>procsym) then
          exit;
        for i:=0 to tprocsym(sym).ProcdefList.Count-1 do
          begin
            pd:=tprocdef(tprocsym(sym).ProcdefList[i]);
            hs:=pd.procsym.name+pd.typename_paras([]);
            j:=AbstractMethodsList.FindIndexOf(hs);
            if j<>-1 then
              AbstractMethodsList[j]:=pd
            else
              AbstractMethodsList.Add(hs,pd);
          end;
      end;


    procedure tcallnode.verifyabstractcalls;
      var
        objectdf : tobjectdef;
        parents : tlinkedlist;
        objectinfo : tobjectinfoitem;
        pd : tprocdef;
        i  : integer;
      begin
        objectdf := nil;
        { verify if trying to create an instance of a class which contains
          non-implemented abstract methods }

        { first verify this class type, no class than exit  }
        { also, this checking can only be done if the constructor is directly
          called, indirect constructor calls cannot be checked.
        }
        if assigned(methodpointer) and
           not((methodpointer.nodetype=loadn) and
               (loadnf_is_self in tloadnode(methodpointer).loadnodeflags)) then
          begin
            if (methodpointer.resultdef.typ = objectdef) then
              objectdf:=tobjectdef(methodpointer.resultdef)
            else
              if (methodpointer.resultdef.typ = classrefdef) and
                 (tclassrefdef(methodpointer.resultdef).pointeddef.typ = objectdef) and
                 (methodpointer.nodetype in [typen,loadvmtaddrn]) then
                objectdf:=tobjectdef(tclassrefdef(methodpointer.resultdef).pointeddef);
          end;
        if not assigned(objectdf) then
          exit;
        { quick exit if nothing to check }
        if objectdf.abstractcnt = 0 then
          exit;

        parents := tlinkedlist.create;
        AbstractMethodsList := TFPHashList.create;

        { insert all parents in this class : the first item in the
          list will be the base parent of the class .
        }
        while assigned(objectdf) do
          begin
            objectinfo:=tobjectinfoitem.create(objectdf);
            parents.insert(objectinfo);
            objectdf := objectdf.childof;
        end;
        { now all parents are in the correct order
          insert all abstract methods in the list, and remove
          those which are overridden by parent classes.
        }
        objectinfo:=tobjectinfoitem(parents.first);
        while assigned(objectinfo) do
          begin
             objectdf := objectinfo.objinfo;
             if assigned(objectdf.symtable) then
               objectdf.symtable.SymList.ForEachCall(@verifyabstract,nil);
             objectinfo:=tobjectinfoitem(objectinfo.next);
          end;
        if assigned(parents) then
          parents.free;
        { Finally give out a warning for each abstract method still in the list }
        for i:=0 to AbstractMethodsList.Count-1 do
          begin
            pd:=tprocdef(AbstractMethodsList[i]);
            if po_abstractmethod in pd.procoptions then
              begin
                Message2(type_w_instance_with_abstract,objectdf.objrealname^,pd.procsym.RealName);
                MessagePos1(pd.fileinfo,sym_h_abstract_method_list,pd.fullprocname(true));
              end;
          end;
        if assigned(AbstractMethodsList) then
          AbstractMethodsList.Free;
      end;


    procedure tcallnode.convert_carg_array_of_const;
      var
        hp : tarrayconstructornode;
        oldleft : tcallparanode;
      begin
        oldleft:=tcallparanode(left);
        if oldleft.left.nodetype<>arrayconstructorn then
          begin
            CGMessage1(type_e_wrong_type_in_array_constructor,oldleft.left.resultdef.typename);
            exit;
          end;
        include(callnodeflags,cnf_uses_varargs);
        { Get arrayconstructor node and insert typeconvs }
        hp:=tarrayconstructornode(oldleft.left);
        { Add c args parameters }
        { It could be an empty set }
        if assigned(hp) and
           assigned(hp.left) then
          begin
            while assigned(hp) do
              begin
                left:=ccallparanode.create(hp.left,left);
                { set callparanode resultdef and flags }
                left.resultdef:=hp.left.resultdef;
                include(tcallparanode(left).callparaflags,cpf_varargs_para);
                hp.left:=nil;
                hp:=tarrayconstructornode(hp.right);
              end;
          end;
        { Remove value of old array of const parameter, but keep it
          in the list because it is required for bind_parasym.
          Generate a nothign to keep callparanoed.left valid }
        oldleft.left.free;
        oldleft.left:=cnothingnode.create;
      end;


    procedure tcallnode.bind_parasym;
      type
        pcallparanode = ^tcallparanode;
      var
        i        : integer;
        pt       : tcallparanode;
        oldppt   : pcallparanode;
        varargspara,
        currpara : tparavarsym;
        hiddentree : tnode;
        paradef  : tdef;
      begin
        pt:=tcallparanode(left);
        oldppt:=pcallparanode(@left);

        { flag all callparanodes that belong to the varargs }
        i:=paralength;
        while (i>procdefinition.maxparacount) do
          begin
            include(pt.callparaflags,cpf_varargs_para);
            oldppt:=pcallparanode(@pt.right);
            pt:=tcallparanode(pt.right);
            dec(i);
          end;

        { skip varargs that are inserted by array of const }
        while assigned(pt) and
              (cpf_varargs_para in pt.callparaflags) do
          pt:=tcallparanode(pt.right);

        { process normal parameters and insert hidden parameter nodes, the content
          of the hidden parameters will be updated in pass1 }
        for i:=procdefinition.paras.count-1 downto 0 do
         begin
           currpara:=tparavarsym(procdefinition.paras[i]);
           if vo_is_hidden_para in currpara.varoptions then
            begin
               { Here we handle only the parameters that depend on
                 the types of the previous parameter. The typeconversion
                 can change the type in the next step. For example passing
                 an array can be change to a pointer and a deref.

                 We also handle the generation of parentfp parameters, as they
                 must all be created before pass_1 on targets that use explicit
                 parentfp structs (rather than the frame pointer). The reason
                 is that the necessary initialisation code for the these
                 structures is attached to the procedure's nodetree after
                 the resulttype pass.
               }
               if vo_is_high_para in currpara.varoptions then
                begin
                  if not assigned(pt) or (i=0) then
                    internalerror(200304081);
                  { we need the information of the previous parameter }
                  paradef:=tparavarsym(procdefinition.paras[i-1]).vardef;
                  hiddentree:=gen_high_tree(pt.left,paradef);
                  { for open array of managed type, a copy of high parameter is
                    necessary to properly initialize before the call }
                  if is_open_array(paradef) and
                    (tparavarsym(procdefinition.paras[i-1]).varspez=vs_out) and
                     is_managed_type(tarraydef(paradef).elementdef) then
                    begin
                      typecheckpass(hiddentree);
                      {this eliminates double call to fpc_dynarray_high, if any}
                      maybe_load_in_temp(hiddentree);
                      oldppt^.third:=hiddentree.getcopy;
                    end;
                end
              else
                if vo_is_typinfo_para in currpara.varoptions then
                  begin
                    if not assigned(pt) or (i=0) then
                      internalerror(200304082);
                    hiddentree:=caddrnode.create_internal(
                      crttinode.create(Tstoreddef(pt.resultdef),fullrtti,rdt_normal)
                    );
                  end
              else if vo_is_parentfp in currpara.varoptions then
                begin
                  if assigned(right) and (right.resultdef.typ=procvardef) and
                     not tabstractprocdef(right.resultdef).is_addressonly then
                    maybe_load_in_temp(right);
                  if not assigned(right) then
                    begin
                      if assigned(procdefinition.owner.defowner) then
                        begin
                          if paramanager.can_opt_unused_para(currpara) then
                            { If parentfp is unused by the target proc, create a dummy
                              pointerconstnode which will be discarded later. }
                            hiddentree:=cpointerconstnode.create(0,currpara.vardef)
                          else
                            begin
                              hiddentree:=cloadparentfpnode.create(tprocdef(procdefinition.owner.defowner),lpf_forpara);
                              if is_nested_pd(current_procinfo.procdef) then
                                current_procinfo.set_needs_parentfp(tprocdef(procdefinition.owner.defowner).parast.symtablelevel);
                           end;
                        end
                      { exceptfilters called from main level are not owned }
                      else if procdefinition.proctypeoption=potype_exceptfilter then
                        hiddentree:=cloadparentfpnode.create(current_procinfo.procdef,lpf_forpara)
                      else
                        internalerror(200309287);
                    end
                  else if not(po_is_block in procdefinition.procoptions) then
                    hiddentree:=gen_procvar_context_tree_parentfp
                  else
                    hiddentree:=gen_block_context
                end
              else
                hiddentree:=cnothingnode.create;
              pt:=ccallparanode.create(hiddentree,oldppt^);
              oldppt^:=pt;
            end;
           if not assigned(pt) then
             internalerror(200310052);
           pt.parasym:=currpara;
           oldppt:=pcallparanode(@pt.right);
           pt:=tcallparanode(pt.right);
         end;

        { Create parasyms for varargs, first count the number of varargs paras,
          then insert the parameters with numbering in reverse order. The SortParas
          will set the correct order at the end}
        pt:=tcallparanode(left);
        i:=0;
        while assigned(pt) do
          begin
            if cpf_varargs_para in pt.callparaflags then
              inc(i);
            pt:=tcallparanode(pt.right);
          end;
        if (i>0) then
          begin
            include(current_procinfo.flags,pi_calls_c_varargs);
            varargsparas:=tvarargsparalist.create;
            pt:=tcallparanode(left);
            while assigned(pt) do
              begin
                if cpf_varargs_para in pt.callparaflags then
                  begin
                    varargspara:=cparavarsym.create('va'+tostr(i),i,vs_value,pt.resultdef,[]);
                    dec(i);
                    { varargspara is left-right, use insert
                      instead of concat }
                    varargsparas.add(varargspara);
                    pt.parasym:=varargspara;
                  end;
                pt:=tcallparanode(pt.right);
              end;
            varargsparas.sortparas;
          end;
      end;


    function tcallnode.pass_typecheck:tnode;

      function is_undefined_recursive(def:tdef):boolean;
        begin
          { might become more refined in the future }
          if def.typ=undefineddef then
            result:=true
          else if def.typ=arraydef then
            result:=is_undefined_recursive(tarraydef(def).elementdef)
          else
            result:=false;
        end;

      var
        candidates : tcallcandidates;
        oldcallnode : tcallnode;
        hpt,tmp : tnode;
        pt : tcallparanode;
        lastpara : longint;
        paraidx,
        cand_cnt : integer;
        i : longint;
        ignoregenericparacall,
        ignorevisibility,
        is_const : boolean;
        statements : tstatementnode;
        converted_result_data : ttempcreatenode;
        calltype: tdispcalltype;
      begin
         result:=nil;
         candidates:=nil;

         oldcallnode:=aktcallnode;
         aktcallnode:=self;

         try
           { determine length of parameter list }
           pt:=tcallparanode(left);
           paralength:=0;
           while assigned(pt) do
            begin
              inc(paralength);
              pt:=tcallparanode(pt.right);
            end;

           { determine the type of the parameters }
           if assigned(left) then
            begin
              tcallparanode(left).get_paratype;
              if codegenerror then
                exit;
            end;

           if assigned(methodpointer) then
             typecheckpass(methodpointer);

           { procedure variable ? }
           if assigned(right) then
             begin
                set_varstate(right,vs_read,[vsf_must_be_valid]);
                typecheckpass(right);
                if codegenerror then
                  exit;

                procdefinition:=tabstractprocdef(right.resultdef);

                { Compare parameters from right to left }
                paraidx:=procdefinition.Paras.count-1;
                { Skip default parameters }
                if not(po_varargs in procdefinition.procoptions) then
                  begin
                    { ignore hidden parameters }
                    while (paraidx>=0) and (vo_is_hidden_para in tparavarsym(procdefinition.paras[paraidx]).varoptions) do
                      dec(paraidx);
                    for i:=1 to procdefinition.maxparacount-paralength do
                      begin
                        if paraidx<0 then
                          internalerror(200402265);
                        if not assigned(tparavarsym(procdefinition.paras[paraidx]).defaultconstsym) then
                          begin
                            CGMessage1(parser_e_wrong_parameter_size,'<Procedure Variable>');
                            exit;
                          end;
                        dec(paraidx);
                      end;
                  end;
                while (paraidx>=0) and (vo_is_hidden_para in tparavarsym(procdefinition.paras[paraidx]).varoptions) do
                  dec(paraidx);
                pt:=tcallparanode(left);
                lastpara:=paralength;
                while (paraidx>=0) and assigned(pt) do
                  begin
                    { only goto next para if we're out of the varargs }
                    if not(po_varargs in procdefinition.procoptions) or
                       (lastpara<=procdefinition.maxparacount) then
                     begin
                       repeat
                         dec(paraidx);
                       until (paraidx<0) or not(vo_is_hidden_para in tparavarsym(procdefinition.paras[paraidx]).varoptions);
                     end;
                    pt:=tcallparanode(pt.right);
                    dec(lastpara);
                  end;
                if assigned(pt) or
                   ((paraidx>=0) and
                    not assigned(tparavarsym(procdefinition.paras[paraidx]).defaultconstsym)) then
                  begin
                     if assigned(pt) then
                       current_filepos:=pt.fileinfo;
                     CGMessage1(parser_e_wrong_parameter_size,'<Procedure Variable>');
                     exit;
                  end;
             end
           else
           { not a procedure variable }
             begin
               { do we know the procedure to call ? }
               if not(assigned(procdefinition)) then
                 begin
                   { according to bug reports 32539 and 20551, real variant of sqr/abs should be used when they are called for variants to be
                     delphi compatible, this is in contrast to normal overloading behaviour, so fix this by a terrible hack to be compatible }
                   if assigned(left) and assigned(tcallparanode(left).left) and
                     (tcallparanode(left).left.resultdef.typ=variantdef) and assigned(symtableproc.name) and (symtableproc.name^='SYSTEM') then
                     begin
                       if symtableprocentry.Name='SQR' then
                         begin
                           result:=cinlinenode.createintern(in_sqr_real,false,tcallparanode(left).left.getcopy);
                           exit;
                         end;
                       if symtableprocentry.Name='ABS' then
                         begin
                           result:=cinlinenode.createintern(in_abs_real,false,tcallparanode(left).left.getcopy);
                           exit;
                         end;
                     end;
                   { ignore possible private for properties or in delphi mode for anon. inherited (FK) }
                   ignorevisibility:=(nf_isproperty in flags) or
                                     ((m_delphi in current_settings.modeswitches) and (cnf_anon_inherited in callnodeflags)) or
                                     (cnf_ignore_visibility in callnodeflags);
                   candidates:=tcallcandidates.create(symtableprocentry,symtableproc,left,ignorevisibility,
                     not(nf_isproperty in flags),cnf_objc_id_call in callnodeflags,cnf_unit_specified in callnodeflags,
                     callnodeflags*[cnf_anon_inherited,cnf_inherited]=[],cnf_anon_inherited in callnodeflags,spezcontext);

                   { no procedures found? then there is something wrong
                     with the parameter size or the procedures are
                     not accessible }
                   if candidates.count=0 then
                    begin
                      { when it's an auto inherited call and there
                        is no procedure found, but the procedures
                        were defined with overload directive and at
                        least two procedures are defined then we ignore
                        this inherited by inserting a nothingn. Only
                        do this ugly hack in Delphi mode as it looks more
                        like a bug. It's also not documented }
                      if (m_delphi in current_settings.modeswitches) and
                         (cnf_anon_inherited in callnodeflags) and
                         (symtableprocentry.owner.symtabletype=ObjectSymtable) and
                         (po_overload in tprocdef(symtableprocentry.ProcdefList[0]).procoptions) and
                         (symtableprocentry.ProcdefList.Count>=2) then
                        result:=cnothingnode.create
                      else
                        begin
                          { in tp mode we can try to convert to procvar if
                            there are no parameters specified }
                          if not(assigned(left)) and
                             not(cnf_inherited in callnodeflags) and
                             ((m_tp_procvar in current_settings.modeswitches) or
                              (m_mac_procvar in current_settings.modeswitches)) and
                             (not assigned(methodpointer) or
                              (methodpointer.nodetype <> typen)) then
                            begin
                              hpt:=cloadnode.create(tprocsym(symtableprocentry),symtableproc);
                              if assigned(methodpointer) then
                                tloadnode(hpt).set_mp(methodpointer.getcopy);
                              typecheckpass(hpt);
                              result:=hpt;
                            end
                          else
                            begin
                              CGMessagePos1(fileinfo,parser_e_wrong_parameter_size,symtableprocentry.realname);
                              symtableprocentry.write_parameter_lists(nil);
                            end;
                        end;
                      candidates.free;
                      exit;
                    end;

                   { Retrieve information about the candidates }
                   candidates.get_information;
{$ifdef EXTDEBUG}
                   { Display info when multiple candidates are found }
                   if candidates.count>1 then
                     candidates.dump_info(V_Debug);
{$endif EXTDEBUG}

                   { Choose the best candidate and count the number of
                     candidates left }
                   cand_cnt:=candidates.choose_best(procdefinition,
                     assigned(left) and
                     not assigned(tcallparanode(left).right) and
                     (tcallparanode(left).left.resultdef.typ=variantdef));

                   { All parameters are checked, check if there are any
                     procedures left }
                   if cand_cnt>0 then
                    begin
                      { Multiple candidates left? }
                      if cand_cnt>1 then
                       begin
                         { if we're inside a generic and call another function
                           with generic types as arguments we don't complain in
                           the generic, but only during the specialization }
                         ignoregenericparacall:=false;
                         if df_generic in current_procinfo.procdef.defoptions then
                           begin
                             pt:=tcallparanode(left);
                             while assigned(pt) do
                              begin
                                if is_undefined_recursive(pt.resultdef) then
                                  begin
                                    ignoregenericparacall:=true;
                                    break;
                                  end;
                                pt:=tcallparanode(pt.right);
                              end;
                           end;

                         if not ignoregenericparacall then
                           begin
                             CGMessage(type_e_cant_choose_overload_function);
{$ifdef EXTDEBUG}
                             candidates.dump_info(V_Hint);
{$else EXTDEBUG}
                             candidates.list(false);
{$endif EXTDEBUG}
                           end;
                         { we'll just use the first candidate to make the
                           call }
                       end;

                      { assign procdefinition }
                      if symtableproc=nil then
                        symtableproc:=procdefinition.owner;
                    end
                   else
                    begin
                      { No candidates left, this must be a type error,
                        because wrong size is already checked. procdefinition
                        is filled with the first (random) definition that is
                        found. We use this definition to display a nice error
                        message that the wrong type is passed }
                      candidates.find_wrong_para;
                      candidates.list(true);
{$ifdef EXTDEBUG}
                      candidates.dump_info(V_Hint);
{$endif EXTDEBUG}

                      { We can not proceed, release all procs and exit }
                      candidates.free;
                      exit;
                    end;

                   { if the final procedure definition is not yet owned,
                     ensure that it is }
                   procdefinition.register_def;
                   if procdefinition.is_specialization and (procdefinition.typ=procdef) then
                     maybe_add_pending_specialization(procdefinition);

                   candidates.free;
                 end; { end of procedure to call determination }
             end;

            { check for hints (deprecated etc) }
            if procdefinition.typ = procdef then
              check_hints(tprocdef(procdefinition).procsym,tprocdef(procdefinition).symoptions,tprocdef(procdefinition).deprecatedmsg);

            { add reference to corresponding procsym; may not be the one
              originally found/passed to the constructor because of overloads }
            if procdefinition.typ = procdef then
              addsymref(tprocdef(procdefinition).procsym,procdefinition);

            { add needed default parameters }
            if (paralength<procdefinition.maxparacount) then
             begin
               paraidx:=0;
               i:=0;
               while (i<paralength) do
                begin
                  if paraidx>=procdefinition.Paras.count then
                    internalerror(200306181);
                  if not(vo_is_hidden_para in tparavarsym(procdefinition.paras[paraidx]).varoptions) then
                    inc(i);
                  inc(paraidx);
                end;
               while (paraidx<procdefinition.paras.count) and (vo_is_hidden_para in tparavarsym(procdefinition.paras[paraidx]).varoptions) do
                 inc(paraidx);
               while (paraidx<procdefinition.paras.count) do
                begin
                  if not assigned(tparavarsym(procdefinition.paras[paraidx]).defaultconstsym) then
                   internalerror(200212142);
                  left:=ccallparanode.create(genconstsymtree(
                      tconstsym(tparavarsym(procdefinition.paras[paraidx]).defaultconstsym)),left);
                  { Ignore vs_hidden parameters }
                  repeat
                    inc(paraidx);
                  until (paraidx>=procdefinition.paras.count) or
                    not(vo_is_hidden_para in tparavarsym(procdefinition.paras[paraidx]).varoptions);
                end;
             end;

            { recursive call? }
            if assigned(current_procinfo) and
               (procdefinition=current_procinfo.procdef) then
              include(current_procinfo.flags,pi_is_recursive);

            { handle predefined procedures }
            is_const:=(po_internconst in procdefinition.procoptions) and
                      ((block_type in [bt_const,bt_type,bt_const_type,bt_var_type]) or
                       (assigned(left) and ((tcallparanode(left).left.nodetype in [realconstn,ordconstn])
                        and (not assigned(tcallparanode(left).right) or (tcallparanode(tcallparanode(left).right).left.nodetype in [realconstn,ordconstn])))));
            if (procdefinition.proccalloption=pocall_internproc) or is_const then
             begin
               if assigned(left) then
                begin
                  { convert types to those of the prototype, this is required by functions like ror, rol, sar
                    some use however a dummy type (Typedfile) so this would break them }
                  if not(tinlinenumber(tprocdef(procdefinition).extnumber) in
                       [in_Reset_TypedFile,in_Rewrite_TypedFile,in_reset_typedfile_name,in_rewrite_typedfile_name]) then
                    begin
                      { bind parasyms to the callparanodes and insert hidden parameters }
                      bind_parasym;

                      { insert type conversions for parameters }
                      if assigned(left) then
                        tcallparanode(left).insert_typeconv;
                    end;

                  { ptr and settextbuf need two args }
                  if assigned(tcallparanode(left).right) then
                   begin
                     hpt:=geninlinenode(tinlinenumber(tprocdef(procdefinition).extnumber),is_const,left);
                     left:=nil;
                   end
                  else
                   begin
                     hpt:=geninlinenode(tinlinenumber(tprocdef(procdefinition).extnumber),is_const,tcallparanode(left).left);
                     tcallparanode(left).left:=nil;
                   end;
                end
               else
                hpt:=geninlinenode(tinlinenumber(tprocdef(procdefinition).extnumber),is_const,nil);
               result:=hpt;
               exit;
             end;

            { in case this is an Objective-C message that returns a related object type by convention,
              override the default result type }
            if po_objc_related_result_type in procdefinition.procoptions then
              begin
                { don't crash in case of syntax errors }
                if assigned(methodpointer) then
                  begin
                    include(callnodeflags,cnf_typedefset);
                    typedef:=methodpointer.resultdef;
                    if typedef.typ=classrefdef then
                      typedef:=tclassrefdef(typedef).pointeddef;
                  end;
              end;

           { ensure that the result type is set }
           if not(cnf_typedefset in callnodeflags) then
            begin
              { constructors return their current class type, not the type where the
                constructor is declared, this can be different because of inheritance }
              if (procdefinition.proctypeoption=potype_constructor) and
                 assigned(methodpointer) and
                 assigned(methodpointer.resultdef) and
                 (methodpointer.resultdef.typ=classrefdef) then
                resultdef:=tclassrefdef(methodpointer.resultdef).pointeddef
              else
              { Member call to a (inherited) constructor from the class, the return
                value is always self, so we change it to voidtype to generate an
                error and to prevent users from generating non-working code
                when they expect to clone the current instance, see bug 3662 (PFV) }
                if (procdefinition.proctypeoption=potype_constructor) and
                   is_class(tprocdef(procdefinition).struct) and
                   assigned(methodpointer) and
                   (methodpointer.nodetype=loadn) and
                   (loadnf_is_self in tloadnode(methodpointer).loadnodeflags) then
                  resultdef:=voidtype
                else
                  resultdef:=procdefinition.returndef;
             end
           else
             resultdef:=typedef;

           { Check object/class for methods }
           if assigned(methodpointer) then
            begin
              { direct call to inherited abstract method, then we
                can already give a error in the compiler instead
                of a runtime error }
              if (cnf_inherited in callnodeflags) and
                 (po_abstractmethod in procdefinition.procoptions) then
                begin
                  if (m_delphi in current_settings.modeswitches) and
                    (cnf_anon_inherited in callnodeflags) then
                    begin
                      CGMessage(cg_h_inherited_ignored);
                      result:=cnothingnode.create;
                      exit;
                    end
                  else
                    CGMessage(cg_e_cant_call_abstract_method);
                end;

              { directly calling an interface/protocol/category/class helper
                method via its type is not possible (always must be called via
                the actual instance) }
              if (methodpointer.nodetype=typen) and
                 ((
                   is_interface(methodpointer.resultdef) and not
                   is_objectpascal_helper(tdef(procdefinition.owner.defowner))
                  ) or
                  is_objc_protocol_or_category(methodpointer.resultdef)) then
                CGMessage1(type_e_class_type_expected,methodpointer.resultdef.typename);

              { if an inherited con- or destructor should be  }
              { called in a con- or destructor then a warning }
              { will be made                                  }
              { con- and destructors need a pointer to the vmt }
              if (cnf_inherited in callnodeflags) and
                 (procdefinition.proctypeoption in [potype_constructor,potype_destructor]) and
                 is_object(methodpointer.resultdef) and
                 not(current_procinfo.procdef.proctypeoption in [potype_constructor,potype_destructor]) then
               CGMessage(cg_w_member_cd_call_from_method);

              if methodpointer.nodetype<>typen then
               begin
                 { if the value a type helper works on is a derefentiation (before
                   removing postix operators) we need to pass the original pointer
                   as Self as the Self value might be changed by the helper }
                 if is_objectpascal_helper(tdef(procdefinition.owner.defowner)) and
                    not is_implicit_pointer_object_type(tobjectdef(procdefinition.owner.defowner).extendeddef) then
                   begin
                     hpt:=methodpointer;

                     hpt:=actualtargetnode(@hpt)^;
                     if hpt.nodetype=derefn then
                       begin
                         tmp:=tderefnode(hpt).left;
                         tderefnode(hpt).left:=nil;
                         methodpointer.free;
                         methodpointer:=tmp;
                       end;
                   end;

                  hpt:=methodpointer;

                  { Remove all postfix operators }
                  while assigned(hpt) and (hpt.nodetype in [subscriptn,vecn]) do
                    hpt:=tunarynode(hpt).left;

                  if ((hpt.nodetype=loadvmtaddrn) or
                     ((hpt.nodetype=loadn) and assigned(tloadnode(hpt).resultdef) and (tloadnode(hpt).resultdef.typ=classrefdef))) and
                     not (procdefinition.proctypeoption=potype_constructor) and
                     not (po_classmethod in procdefinition.procoptions) and
                     not (po_staticmethod in procdefinition.procoptions) then
                    { error: we are calling instance method from the class method/static method }
                    CGMessage(parser_e_only_class_members);

                 if (procdefinition.proctypeoption=potype_constructor) and
                    assigned(symtableproc) and
                    (symtableproc.symtabletype=withsymtable) and
                    (tnode(twithsymtable(symtableproc).withrefnode).nodetype=temprefn) then
                   CGmessage(cg_e_cannot_call_cons_dest_inside_with);

                 { skip (absolute and other simple) type conversions -- only now,
                   because the checks above have to take type conversions into
                   e.g. class reference types account }
                 hpt:=actualtargetnode(@hpt)^;

                 { R.Init then R will be initialized by the constructor,
                   Also allow it for simple loads }
                 if (procdefinition.proctypeoption=potype_constructor) or
                    ((hpt.nodetype=loadn) and
                     (((methodpointer.resultdef.typ=objectdef) and
                       not(oo_has_virtual in tobjectdef(methodpointer.resultdef).objectoptions)) or
                      (methodpointer.resultdef.typ=recorddef)
                     )
                    ) then
                   { a constructor will and a method may write something to }
                   { the fields                                             }
                   set_varstate(methodpointer,vs_readwritten,[])
                 else
                   set_varstate(methodpointer,vs_read,[vsf_must_be_valid]);
               end;

              { if we are calling the constructor check for abstract
                methods. Ignore inherited and member calls, because the
                class is then already created }
              if (procdefinition.proctypeoption=potype_constructor) and
                 not(cnf_inherited in callnodeflags) and
                 not(cnf_member_call in callnodeflags) then
                verifyabstractcalls;
            end
           else
            begin
              { When this is method the methodpointer must be available }
              if (right=nil) and
                 (procdefinition.owner.symtabletype in [ObjectSymtable,recordsymtable]) and
                 not procdefinition.no_self_node then
                internalerror(200305061);
            end;

           { Set flag that the procedure uses varargs, also if they are not passed it is still
             needed for x86_64 to pass the number of SSE registers used }
           if po_varargs in procdefinition.procoptions then
             include(callnodeflags,cnf_uses_varargs);

           { set the appropriate node flag if the call never returns }
           if po_noreturn in procdefinition.procoptions then
             include(callnodeflags,cnf_call_never_returns);

           { Change loading of array of const to varargs }
           if assigned(left) and
              is_array_of_const(tparavarsym(procdefinition.paras[procdefinition.paras.count-1]).vardef) and
              (procdefinition.proccalloption in cdecl_pocalls) then
             convert_carg_array_of_const;

           { bind parasyms to the callparanodes and insert hidden parameters }
           bind_parasym;

           { insert type conversions for parameters }
           if assigned(left) then
             tcallparanode(left).insert_typeconv;

           { dispinterface methode invoke? }
           if assigned(methodpointer) and is_dispinterface(methodpointer.resultdef) then
             begin
               case procdefinition.proctypeoption of
                 potype_propgetter: calltype:=dct_propget;
                 potype_propsetter: calltype:=dct_propput;
               else
                 calltype:=dct_method;
               end;
               { if the result is used, we've to insert a call to convert the type to be on the "safe side" }
               if (cnf_return_value_used in callnodeflags) and not is_void(procdefinition.returndef) then
                 begin
                   result:=internalstatements(statements);
                   converted_result_data:=ctempcreatenode.create(procdefinition.returndef,sizeof(procdefinition.returndef),
                     tt_persistent,true);
                   addstatement(statements,converted_result_data);
                   addstatement(statements,cassignmentnode.create(ctemprefnode.create(converted_result_data),
                     ctypeconvnode.create_internal(
                       translate_disp_call(methodpointer,parameters,calltype,'',tprocdef(procdefinition).dispid,procdefinition.returndef),
                     procdefinition.returndef)));
                   addstatement(statements,ctempdeletenode.create_normal_temp(converted_result_data));
                   addstatement(statements,ctemprefnode.create(converted_result_data));
                 end
               else
                 result:=translate_disp_call(methodpointer,parameters,calltype,'',tprocdef(procdefinition).dispid,voidtype);

               { don't free reused nodes }
               methodpointer:=nil;
               parameters:=nil;
             end;

         maybe_gen_call_self_node;

         if assigned(call_self_node) then
           typecheckpass(call_self_node);
         if assigned(call_vmt_node) then
           typecheckpass(call_vmt_node);

         finally
           aktcallnode:=oldcallnode;
         end;
      end;


    procedure tcallnode.order_parameters;
      var
        hp,hpcurr,hpnext,hpfirst,hpprev : tcallparanode;
        currloc : tcgloc;
      begin
        hpfirst:=nil;
        hpcurr:=tcallparanode(left);
        { cache all info about parameters containing stack tainting calls,
          since we will need it a lot below and calculting it can be expensive }
        while assigned(hpcurr) do
          begin
            hpcurr.init_contains_stack_tainting_call_cache;
            hpcurr:=tcallparanode(hpcurr.right);
          end;
        hpcurr:=tcallparanode(left);
        while assigned(hpcurr) do
          begin
            { pull out }
            hpnext:=tcallparanode(hpcurr.right);
            { pull in at the correct place.
              Used order:
                1. vs_out for a reference-counted type
                2. LOC_REFERENCE with smallest offset (i386 only)
                3. LOC_REFERENCE with least complexity (non-i386 only)
                4. LOC_REFERENCE with most complexity (non-i386 only)
                5. LOC_REGISTER with most complexity
                6. LOC_REGISTER with least complexity
              For the moment we only look at the first parameter field. Combining it
              with multiple parameter fields will make things a lot complexer (PFV)

              The reason for the difference regarding complexity ordering
              between LOC_REFERENCE and LOC_REGISTER is mainly for calls:
              we first want to treat the LOC_REFERENCE destinations whose
              calculation does not require a call, because their location
              may contain registers which might otherwise have to be saved
              if a call has to be evaluated first. The calculated value is
              stored on the stack and will thus no longer occupy any
              register.

              Similarly, for the register parameters we first want to
              evaluate the calls, because otherwise the already loaded
              register parameters will have to be saved so the intermediate
              call can be evaluated (JM) }
            if not assigned(hpcurr.parasym.paraloc[callerside].location) then
              internalerror(200412152);
            currloc:=hpcurr.parasym.paraloc[callerside].location^.loc;
            hpprev:=nil;
            hp:=hpfirst;
            { on fixed_stack targets, always evaluate parameters containing
              a call with stack parameters before all other parameters,
              because they will prevent any other parameters from being put
              in their final place; if both the current and the next para
              contain a stack tainting call, don't do anything to prevent
              them from keeping on chasing eachother's tail }
            while assigned(hp) do
              begin
                if paramanager.use_fixed_stack and
                   hpcurr.contains_stack_tainting_call_cached then
                  break;
                case currloc of
                  LOC_REFERENCE :
                    begin
                      case hp.parasym.paraloc[callerside].location^.loc of
                        LOC_REFERENCE :
                          begin
                            { Offset is calculated like:
                               sub esp,12
                               mov [esp+8],para3
                               mov [esp+4],para2
                               mov [esp],para1
                               call function
                              That means the for pushes the para with the
                              highest offset (see para3) needs to be pushed first
                            }
{$if defined(i386) or defined(i8086) or defined(m68k) or defined(z80)}
                            { the i386, i8086, m68k, z80 and jvm code generators expect all reference }
                            { parameters to be in this order so they can use   }
                            { pushes in case of no fixed stack                 }
                            if (not paramanager.use_fixed_stack and
                                (hpcurr.parasym.paraloc[callerside].location^.reference.offset>
                                 hp.parasym.paraloc[callerside].location^.reference.offset)) or
                               (paramanager.use_fixed_stack and
                                (node_complexity(hpcurr.left)<node_complexity(hp.left))) then
{$elseif defined(jvm) or defined(wasm)}
                            if (hpcurr.parasym.paraloc[callerside].location^.reference.offset<hp.parasym.paraloc[callerside].location^.reference.offset) then
{$else jvm}
                            if (node_complexity(hpcurr.left)<node_complexity(hp.left)) then
{$endif jvm}
                              break;
                          end;
                        LOC_MMREGISTER,
                        LOC_REGISTER,
                        LOC_FPUREGISTER :
                          break;
                        else
                          ;
                      end;
                    end;
                  LOC_MMREGISTER,
                  LOC_FPUREGISTER,
                  LOC_REGISTER :
                    begin
                      if (hp.parasym.paraloc[callerside].location^.loc<>LOC_REFERENCE) and
                         (node_complexity(hpcurr.left)>node_complexity(hp.left)) then
                        break;
                    end;
                  else
                    ;
                end;
                hpprev:=hp;
                hp:=tcallparanode(hp.right);
              end;
            hpcurr.right:=hp;
            if assigned(hpprev) then
              hpprev.right:=hpcurr
            else
              hpfirst:=hpcurr;
            { next }
            hpcurr:=hpnext;
          end;
        left:=hpfirst;
        { now mark each parameter that is followed by a stack-tainting call,
          to determine on use_fixed_stack targets which ones can immediately be
          put in their final destination. Unforunately we can never put register
          parameters immediately in their final destination (even on register-
          rich architectures such as the PowerPC), because the code generator
          can still insert extra calls that only make use of register
          parameters (fpc_move() etc. }
        hpcurr:=hpfirst;
        while assigned(hpcurr) do
          begin
            if hpcurr.contains_stack_tainting_call_cached then
              begin
                { all parameters before this one are followed by a stack
                  tainting call }
                hp:=hpfirst;
                while hp<>hpcurr do
                  begin
                    hp.ffollowed_by_stack_tainting_call_cached:=true;
                    hp:=tcallparanode(hp.right);
                  end;
                hpfirst:=hpcurr;
              end;
            hpcurr:=tcallparanode(hpcurr.right);
          end;
      end;


    procedure tcallnode.check_stack_parameters;
      var
        hp : tcallparanode;
      begin
        hp:=tcallparanode(left);
        while assigned(hp) do
          begin
             if assigned(hp.parasym) and
                assigned(hp.parasym.paraloc[callerside].location) and
               (hp.parasym.paraloc[callerside].location^.loc=LOC_REFERENCE) then
               include(current_procinfo.flags,pi_has_stackparameter);
             hp:=tcallparanode(hp.right);
          end;
      end;


    procedure tcallnode.check_inlining;
      var
        st   : tsymtable;
        para : tcallparanode;
      begin
        { Can we inline the procedure? }
        if (po_inline in procdefinition.procoptions) and
           (procdefinition.typ=procdef) and
           tprocdef(procdefinition).has_inlininginfo and
           {  Prevent too deep inlining recursion and code bloat by inlining

              The actual formuala is
                                inlinelevel/3+1    /-------
                  node count <  -----------------\/  10000

              This allows exponential grow of the code only to a certain limit.

              Remarks
               - The current approach calculates the inlining level top down, so outer call nodes (nodes closer to the leaf) might not be inlined
                 if the max. complexity is reached. This is done because it makes the implementation easier and because
                 there might be situations were it is more beneficial to inline inner nodes and do the calls to the outer nodes
                 if the outer nodes are in a seldomly used code path
               - The code avoids to use functions from the math unit
           }
           (node_count(tprocdef(procdefinition).inlininginfo^.code)<round(exp((1.0/(inlinelevel/3.0+1))*ln(10000)))) then
          begin
            include(callnodeflags,cnf_do_inline);
            { Check if we can inline the procedure when it references proc/var that
              are not in the globally available }
            st:=procdefinition.owner;
            while (st.symtabletype in [ObjectSymtable,recordsymtable]) do
              st:=st.defowner.owner;
            if not(tf_supports_hidden_symbols in target_info.flags) and
               (pi_uses_static_symtable in tprocdef(procdefinition).inlininginfo^.flags) and
               (st.symtabletype=globalsymtable) and
               (not st.iscurrentunit) then
              begin
                Comment(V_lineinfo+V_Debug,'Not inlining "'+tprocdef(procdefinition).procsym.realname+'", references private symbols from other unit');
                exclude(callnodeflags,cnf_do_inline);
              end;
            para:=tcallparanode(parameters);
            while assigned(para) do
              begin
                if not para.can_be_inlined then
                  begin
                    Comment(V_lineinfo+V_Debug,'Not inlining "'+tprocdef(procdefinition).procsym.realname+
                      '", invocation parameter contains an unsafe/unsupported construct');
                    exclude(callnodeflags,cnf_do_inline);
                    break;
                  end;
                para:=tcallparanode(para.nextpara);
              end;
          end;
      end;


    function tcallnode.pass_1 : tnode;

      procedure mark_unregable_parameters;
        var
          hp : tcallparanode;
        begin
          hp:=tcallparanode(left);
          while assigned(hp) do
            begin
              do_typecheckpass(hp.left);
              { When the address needs to be pushed then the register is
                not regable. Exception is when the location is also a var
                parameter and we can pass the address transparently (but
                that is handled by make_not_regable if ra_addr_regable is
                passed, and make_not_regable always needs to called for
                the ra_addr_taken info for non-invisble parameters) }
              if (not (cpf_varargs_para in hp.callparaflags)) and (
                  not(
                      (vo_is_hidden_para in hp.parasym.varoptions) and
                      (hp.left.resultdef.typ in [pointerdef,classrefdef])
                     ) and
                  paramanager.push_addr_param(hp.parasym.varspez,hp.parasym.vardef,
                      self.procdefinition.proccalloption)
                 ) then
                { pushing the address of a variable to take the place of a temp
                  as the complex function result of a function does not make its
                  address escape the current block, as the "address of the
                  function result" is not something which can be stored
                  persistently by the callee (it becomes invalid when the callee
                  returns)                                                       }
                if not(vo_is_funcret in hp.parasym.varoptions) and
                   not(po_compilerproc in procdefinition.procoptions) then
                  make_not_regable(hp.left,[ra_addr_regable,ra_addr_taken])
                else
                  make_not_regable(hp.left,[ra_addr_regable]);
              hp:=tcallparanode(hp.right);
            end;
        end;

      var
        para: tcallparanode;
        oldcallnode: tcallnode;
      begin
         result:=nil;

         oldcallnode:=aktcallnode;
         aktcallnode:=self;

         try
           { as pass_1 is never called on the methodpointer node, we must check
             here that it's not a helper type }
           if assigned(methodpointer) and
               (methodpointer.nodetype=typen) and
               is_objectpascal_helper(ttypenode(methodpointer).typedef) and
               not ttypenode(methodpointer).helperallowed then
             begin
               CGMessage(parser_e_no_category_as_types);
               { we get an internal error when trying to insert the hidden
                 parameters in this case }
               exit;
             end;

           { can we get rid of the call? }
           if (cs_opt_remove_empty_proc in current_settings.optimizerswitches) and
              not(cnf_return_value_used in callnodeflags) and
             (procdefinition.typ=procdef) and
             tprocdef(procdefinition).isempty and
             { allow only certain proc options }
             ((tprocdef(procdefinition).procoptions-[po_none,po_classmethod,po_staticmethod,
               po_interrupt,po_iocheck,po_assembler,po_msgstr,po_msgint,po_exports,po_external,po_overload,
               po_nostackframe,po_has_mangledname,po_has_public_name,po_forward,po_global,
               po_inline,po_compilerproc,po_has_importdll,po_has_importname,po_kylixlocal,po_dispid,po_delphi_nested_cc,
               po_rtlproc,po_ignore_for_overload_resolution,po_auto_raised_visibility])=[]) then
             begin
               { check parameters for side effects }
               para:=tcallparanode(left);
               while assigned(para) do
                 begin
                   if (para.parasym.typ = paravarsym) and
                      ((para.parasym.refs>0) or
                      { array of consts are converted later on so we need to skip them here
                        else no error detection is done }
                       is_array_of_const(para.parasym.vardef) or
                       not(cs_opt_dead_values in current_settings.optimizerswitches) or
                       might_have_sideeffects(para.left)) then
                       break;
                    para:=tcallparanode(para.right);
                 end;
               { finally, remove it if no parameter with side effect has been found }
               if para=nil then
                 begin
                   result:=cnothingnode.create;
                   exit;
                 end;
             end;

           { convert Objective-C calls into a message call }
           if (procdefinition.typ=procdef) and
              (po_objc in tprocdef(procdefinition).procoptions) then
             begin
               if not(cnf_objc_processed in callnodeflags) then
                 objc_convert_to_message_send;
             end
           else
             begin
               { The following don't apply to obj-c: obj-c methods can never be
                 inlined because they're always virtual and the destination can
                 change at run, and for the same reason we also can't perform
                 WPO on them (+ they have no constructors) }

               { Check if the call can be inlined, sets the cnf_do_inline flag }
               check_inlining;

               { must be called before maybe_load_in_temp(methodpointer), because
                 it converts the methodpointer into a temp in case it's a call
                 (and we want to know the original call)
               }
               register_created_object_types;
             end;

           { Maybe optimize the loading of the methodpointer using a temp. When the methodpointer
             is a calln this is even required to not execute the calln twice.
             This needs to be done after the resulttype pass, because in the resulttype we can still convert the
             calln to a loadn (PFV) }
           if assigned(methodpointer) then
             maybe_load_in_temp(methodpointer);
           if assigned(right) and (right.resultdef.typ=procvardef) and
              not tabstractprocdef(right.resultdef).is_addressonly then
             maybe_load_in_temp(right);

           { the return value might be stored on the current stack by allocating a temp. }
           if not(paramanager.ret_in_param(procdefinition.returndef,procdefinition)) then
             inc(current_procinfo.estimatedtempsize,procdefinition.returndef.size);

           { Create destination (temp or assignment-variable reuse) for function result if it not yet set }
           maybe_create_funcret_node;

           { Insert the self,vmt,function result in the parameters }
           gen_hidden_parameters;

           { Remove useless nodes from init/final blocks }
           { (simplify depends on typecheck info)        }
           if assigned(callinitblock) then
             begin
               typecheckpass(tnode(callinitblock));
               doinlinesimplify(tnode(callinitblock));
             end;
           if assigned(callcleanupblock) then
             begin
               typecheckpass(tnode(callcleanupblock));
               doinlinesimplify(tnode(callcleanupblock));
             end;

           { If a constructor calls another constructor of the same or of an
             inherited class, some targets (jvm) have to generate different
             entry code for the constructor. }
           if (current_procinfo.procdef.proctypeoption=potype_constructor) and
              (procdefinition.typ=procdef) and
              (tprocdef(procdefinition).proctypeoption=potype_constructor) and
              ([cnf_member_call,cnf_inherited] * callnodeflags <> []) then
             current_procinfo.ConstructorCallingConstructor:=true;

           { Continue with checking a normal call or generate the inlined code }
           if cnf_do_inline in callnodeflags then
             result:=pass1_inline
           else
             begin
               if (po_inline in procdefinition.procoptions) and not(po_compilerproc in procdefinition.procoptions) and
                  (procdefinition.typ=procdef) and
                  not (pio_inline_not_possible in tprocdef(procdefinition).implprocoptions) then
                 begin
                   Message1(cg_n_no_inline,tprocdef(procdefinition).customprocname([pno_proctypeoption, pno_paranames,pno_ownername, pno_noclassmarker]));
                 end;
               mark_unregable_parameters;
               result:=pass1_normal;
             end;
         finally
           aktcallnode:=oldcallnode;
         end;
      end;


    function tcallnode.pass1_normal : tnode;
      begin
         result:=nil;

         { calculate the parameter info for the procdef }
         procdefinition.init_paraloc_info(callerside);

         { calculate the parameter size needed for this call include varargs if they are available }
         if assigned(varargsparas) then
           pushedparasize:=paramanager.create_varargs_paraloc_info(procdefinition,callerside,varargsparas)
         else
           pushedparasize:=procdefinition.callerargareasize;

         { record maximum parameter size used in this proc }
         current_procinfo.allocate_push_parasize(pushedparasize);

         { check for stacked parameters }
         if assigned(left) and
            (current_settings.optimizerswitches*[cs_opt_stackframe,cs_opt_level1]<>[]) then
           check_stack_parameters;

         if assigned(callinitblock) then
           firstpass(tnode(callinitblock));

         { function result node (tempref or simple load) }
         if assigned(funcretnode) then
           firstpass(funcretnode);

         { parameters }
         if assigned(left) then
           tcallparanode(left).firstcallparan;

         { procedure variable ? }
         if assigned(right) then
           firstpass(right);

         if assigned(methodpointer) and
            (methodpointer.nodetype<>typen) then
           firstpass(methodpointer);

         if assigned(callcleanupblock) then
           firstpass(tnode(callcleanupblock));

         if not (block_type in [bt_const,bt_type,bt_const_type,bt_var_type]) then
           include(current_procinfo.flags,pi_do_call);

         { order parameters }
         order_parameters;

         { get a register for the return value }
         if (not is_void(resultdef)) then
           begin
              if paramanager.ret_in_param(resultdef,procdefinition) then
               begin
                 expectloc:=LOC_REFERENCE;
               end
             else
             { ansi/widestrings must be registered, so we can dispose them }
              if is_ansistring(resultdef) or
                 is_widestring(resultdef) or
                 is_unicodestring(resultdef) then
               begin
                 expectloc:=LOC_REFERENCE;
               end
             else
             { we have only to handle the result if it is used }
              if (cnf_return_value_used in callnodeflags) then
                expectloc:=get_expect_loc
             else
               expectloc:=LOC_VOID;
           end
         else
           expectloc:=LOC_VOID;

         { create tree for VMT entry if required }
         gen_vmt_entry_load;
      end;

{$ifdef state_tracking}
    function Tcallnode.track_state_pass(exec_known:boolean):boolean;

    var hp:Tcallparanode;
        value:Tnode;

    begin
        track_state_pass:=false;
        hp:=Tcallparanode(left);
        while assigned(hp) do
            begin
                if left.track_state_pass(exec_known) then
                    begin
                        left.resultdef:=nil;
                        do_typecheckpass(left);
                    end;
                value:=aktstate.find_fact(hp.left);
                if value<>nil then
                    begin
                        track_state_pass:=true;
                        hp.left.destroy;
                        hp.left:=value.getcopy;
                        do_typecheckpass(hp.left);
                    end;
                hp:=Tcallparanode(hp.right);
            end;
    end;
{$endif}


{**************************************************************************
                       INLINING SUPPORT
**************************************************************************}

    function tcallnode.replaceparaload(var n: tnode; arg: pointer): foreachnoderesult;
      var
        paras: tcallparanode;
        temp: tnode;
        indexnr : integer;
      begin
        result := fen_false;
        n.fileinfo := pfileposinfo(arg)^;
        if (n.nodetype = loadn) then
          begin
            case tloadnode(n).symtableentry.typ of
              paravarsym :
                begin
                  paras := tcallparanode(left);
                  while assigned(paras) and
                        (paras.parasym <> tloadnode(n).symtableentry) do
                    paras := tcallparanode(paras.right);
                  if assigned(paras) then
                    begin
                      temp:=paras.left.getcopy;
                      { inherit modification information, this is needed by the dfa/cse }
                      temp.flags:=temp.flags+(n.flags*[nf_modify,nf_write,nf_address_taken]);
                      n.free;
                      n:=temp;
                      typecheckpass(n);
                      result := fen_true;
                    end;
                end;
              localvarsym :
                begin
                  { local? }
                  if (tloadnode(n).symtableentry.owner <> tprocdef(procdefinition).localst) then
                    exit;
                  indexnr:=tloadnode(n).symtableentry.owner.SymList.IndexOf(tloadnode(n).symtableentry);
                  if (indexnr >= inlinelocals.count) or
                     not assigned(inlinelocals[indexnr]) then
                    internalerror(20040720);
                  temp := tnode(inlinelocals[indexnr]).getcopy;
                  { inherit modification information, this is needed by the dfa/cse }
                  temp.flags:=temp.flags+(n.flags*[nf_modify,nf_write,nf_address_taken]);
                  n.free;
                  n:=temp;
                  typecheckpass(n);
                  result := fen_true;
                end;
              else
                ;
            end;
          end;
      end;


    procedure tcallnode.createlocaltemps(p:TObject;arg:pointer);
      var
        tempnode: ttempcreatenode;
        indexnr : integer;
      begin
        if (TSym(p).typ <> localvarsym) then
          exit;
        indexnr:=TSym(p).Owner.SymList.IndexOf(p);
        if (indexnr >= inlinelocals.count) then
          inlinelocals.count:=indexnr+10;
        if (vo_is_funcret in tabstractvarsym(p).varoptions) then
          begin
            if not assigned(funcretnode) then
              internalerror(200709081);
            inlinelocals[indexnr] := funcretnode.getcopy
          end
        else
          begin
            tempnode :=ctempcreatenode.create(tabstractvarsym(p).vardef,
              tabstractvarsym(p).vardef.size,tt_persistent,tabstractvarsym(p).is_regvar(false));
            addstatement(inlineinitstatement,tempnode);

            if localvartrashing <> -1 then
              cnodeutils.maybe_trash_variable(inlineinitstatement,tabstractnormalvarsym(p),ctemprefnode.create(tempnode));

            addstatement(inlinecleanupstatement,ctempdeletenode.create(tempnode));
            { inherit addr_taken flag }
            if (tabstractvarsym(p).addr_taken) then
              tempnode.includetempflag(ti_addr_taken);
            inlinelocals[indexnr] := ctemprefnode.create(tempnode);
          end;
      end;


    function nonlocalvars(var n: tnode; arg: pointer): foreachnoderesult;
      begin
        result := fen_false;
        { this is just to play it safe, there are more safe situations }
        if (n.nodetype = derefn) or
           ((n.nodetype = loadn) and
            { can be nil in case of internally generated labels like $raiseaddr }
            assigned(tloadnode(n).symtable) and
            { globals and fields of (possibly global) objects could always be changed in the callee }
            ((tloadnode(n).symtable.symtabletype in [globalsymtable,ObjectSymtable]) or
            { statics can only be modified by functions in the same unit }
             ((tloadnode(n).symtable.symtabletype = staticsymtable) and
              (tloadnode(n).symtable = TSymtable(arg))) or
             { if the addr of the symbol is taken somewhere, it can be also non-local }
             ((tloadnode(n).symtableentry.typ in [localvarsym,paravarsym,staticvarsym]) and
	      (tabstractvarsym(tloadnode(n).symtableentry).addr_taken))
            )
           ) or
           ((n.nodetype = subscriptn) and
            (tsubscriptnode(n).vs.owner.symtabletype = ObjectSymtable)) then
          result := fen_norecurse_true;
      end;


    function tcallnode.paraneedsinlinetemp(para: tcallparanode; const pushconstaddr, complexpara: boolean): boolean;
      begin
        { if it's an assignable call-by-reference parameter, we cannot pass a
          temp since then the modified valua will be lost }
        if para.parasym.varspez in [vs_var,vs_out] then
          exit(false);

        { We cannot create a formaldef temp and assign something to it }
        if para.parasym.vardef.typ=formaldef then
          exit(false);

        { We don't need temps for parameters that are already temps, except if
          the passed temp could be put in a regvar while the parameter inside
          the routine cannot be (e.g., because its address is taken in the
          routine), or if the temp is a const and the parameter gets modified }
        if (para.left.nodetype=temprefn) and
           (not(ti_may_be_in_reg in ttemprefnode(para.left).tempflags) or
            not(tparavarsym(para.parasym).varregable in [vr_none,vr_addr])) and
           (not(ti_const in ttemprefnode(para.left).tempflags) or
            (tparavarsym(para.parasym).varstate in [vs_initialised,vs_declared,vs_read])) then
          exit(false);

        { We need a temp if the passed value will not be in memory, while
          the parameter inside the routine must be in memory }
        if (tparavarsym(para.parasym).varregable in [vr_none,vr_addr]) and
           not(para.left.expectloc in [LOC_REFERENCE,LOC_CREFERENCE]) then
          exit(true);

        { We try to handle complex expressions later by taking their address
          and storing this address in a temp (which is then dereferenced when
          the value is used; that doesn't work if we cannot take the address
          of the expression though, in which case we store the result of the
          expression in a temp }
        if (complexpara and not(para.left.expectloc in [LOC_REFERENCE,LOC_CREFERENCE]) or
           (complexpara and
            (not valid_for_addr(para.left,false) or
             (para.left.nodetype=calln) or
             is_constnode(para.left)))) then
          exit(true);

        { Normally, we do not need to create a temp for value parameters that
          are not modified in the inlined function, and neither for const
          parameters that are passed by value.

          However, if we pass a global variable, an object field, a variable
          whose address has been taken, or an expression containing a pointer
          dereference as parameter, this value could be modified in other ways
          as well (even inside the callee) and in such cases we still create a
          temp to be on the safe side.

          We *must not* create a temp for global variables passed by
          reference to a const parameter, because if not inlined then any
          changes to the original value will also be visible in the callee
          (although this is technically undefined behaviour, since with
           "const" the programmer tells the compiler this argument will not
           change). }
        if (((para.parasym.varspez=vs_value) and
             (para.parasym.varstate in [vs_initialised,vs_declared,vs_read])) or
            ((para.parasym.varspez=vs_const) and
             not pushconstaddr)) and
           foreachnodestatic(para.left,@nonlocalvars,pointer(symtableproc)) then
          exit(true);

        { Value parameters of which we know they are modified by definition
          have to be copied to a temp }
        if (para.parasym.varspez=vs_value) and
           not(para.parasym.varstate in [vs_initialised,vs_declared,vs_read]) then
          exit(true);

        { the compiler expects that it can take the address of parameters passed by reference in
          the case of const so we can't replace the node simply by a constant node
          When playing with this code, ensure that
          function f(const a,b  : longint) : longint;inline;
            begin
              result:=a*b;
            end;

          [...]
          ...:=f(10,20));
          [...]

          is still folded. (FK)
          }
        if (para.parasym.varspez=vs_const) and
           { const para's can get vs_readwritten if their address is taken ->
             in case they are not passed by reference, to keep the same
             behaviour as without inlining we have to make a copy in case the
             originally passed parameter value gets changed inside the callee
           }
           (not pushconstaddr and
            (para.parasym.varstate=vs_readwritten)
           ) or
           { call-by-reference const's may need to be passed by reference to
             function called in the inlined code }
           (pushconstaddr and
            not valid_for_addr(para.left,false)) then
          exit(true);

        result:=false;
      end;


    function tcallnode.maybecreateinlineparatemp(para: tcallparanode; out complexpara: boolean): boolean;
      var
        tempnode: ttempcreatenode;
        realtarget: tnode;
        paracomplexity: longint;
        pushconstaddr: boolean;
      begin
        result:=false;
        { determine how a parameter is passed to the inlined body
          There are three options:
            - insert the node tree of the callparanode directly
              If a parameter is used only once, this is the best option if we can do so
            - get the address of the argument, store it in a temp and insert a dereference to this temp
              If the node tree cannot be inserted directly, taking the address of the argument and using it
              is the second best option, but even this is not always possible
            - assign the value of the argument to a newly created temp
              This is the fall back which works always
          Notes:
            - we need to take care that we use the type of the defined parameter and not of the
              passed parameter, because these can be different in case of a formaldef (PFV)
        }

        { pre-compute some values }
        paracomplexity:=node_complexity(para.left);
        if para.parasym.varspez=vs_const then
          pushconstaddr:=paramanager.push_addr_param(vs_const,para.parasym.vardef,procdefinition.proccalloption)
        else
          pushconstaddr:=false;
        realtarget:=actualtargetnode(@para.left)^;

        { if the parameter is "complex", try to take the address of the
          parameter expression, store it in a temp and replace occurrences of
          the parameter with dereferencings of this temp
        }
        complexpara:=
          { don't create a temp. for function results }
          not(nf_is_funcret in realtarget.flags) and
          { this makes only sense if the parameter is reasonably complex,
            otherwise inserting directly is a better solution }
          (
           (paracomplexity>2) or
           { don't create a temp. for the often seen case that p^ is passed to a var parameter }
           ((paracomplexity>1) and
            not((realtarget.nodetype=derefn) and (para.parasym.varspez in [vs_var,vs_out,vs_constref])) and
            not((realtarget.nodetype=loadn) and tloadnode(realtarget).is_addr_param_load) and
            not(realtarget.nodetype=realconstn)
           )
          );

        { check if we have to create a temp, assign the parameter's
          contents to that temp and then substitute the parameter
          with the temp everywhere in the function                  }
        if paraneedsinlinetemp(para,pushconstaddr,complexpara) then
          begin
            tempnode:=ctempcreatenode.create(para.parasym.vardef,para.parasym.vardef.size,
              tt_persistent,tparavarsym(para.parasym).is_regvar(false));
            addstatement(inlineinitstatement,tempnode);

            addstatement(inlinecleanupstatement,ctempdeletenode.create(tempnode));

            addstatement(inlineinitstatement,cassignmentnode.create(ctemprefnode.create(tempnode),
              para.left));

            para.left := ctemprefnode.create(tempnode);
            { inherit addr_taken flag }
            if (tabstractvarsym(para.parasym).addr_taken) then
              tempnode.includetempflag(ti_addr_taken);

            { inherit const }
            if tabstractvarsym(para.parasym).varspez=vs_const then
              begin
                tempnode.includetempflag(ti_const);

                { apply less strict rules for the temp. to be a register than
                  ttempcreatenode does

                  this way, dyn. array, ansistrings etc. can be put into registers as well }
                if tparavarsym(para.parasym).is_regvar(false) then
                  tempnode.includetempflag(ti_may_be_in_reg);
              end;

            result:=true;
          end
        { for formaldefs, we do not need a temp., but it must be inherited if they are not regable }
        else if (para.parasym.vardef.typ=formaldef) and not(tparavarsym(para.parasym).is_regvar(false)) then
          make_not_regable(para.left,[ra_addr_regable]);
      end;


    procedure tcallnode.createinlineparas;
      var
        para: tcallparanode;
        n: tnode;
        complexpara: boolean;
      begin
        { parameters }
        para := tcallparanode(left);
        while assigned(para) do
          begin
            if (para.parasym.typ = paravarsym) and
               ((para.parasym.refs>0) or
                not(cs_opt_dead_values in current_settings.optimizerswitches) or
                might_have_sideeffects(para.left)) then
              begin
                { must take copy of para.left, because if it contains a       }
                { temprefn pointing to a copied temp (e.g. methodpointer),    }
                { then this parameter must be changed to point to the copy of }
                { that temp (JM)                                              }
                n := para.left.getcopy;
                para.left.free;
                para.left := n;

                firstpass(para.left);

                if not maybecreateinlineparatemp(para,complexpara) and
                   complexpara then
                  wrapcomplexinlinepara(para);
              end;
            para := tcallparanode(para.right);
          end;
        { local variables }
        if not assigned(tprocdef(procdefinition).localst) or
           (tprocdef(procdefinition).localst.SymList.count = 0) then
          exit;
        inlinelocals.count:=tprocdef(procdefinition).localst.SymList.count;
        tprocdef(procdefinition).localst.SymList.ForEachCall(@createlocaltemps,nil);
      end;


    procedure tcallnode.wrapcomplexinlinepara(para: tcallparanode);
      var
        ptrtype: tdef;
        tempnode: ttempcreatenode;
        paraaddr: taddrnode;
        isfuncretnode : boolean;
      begin
        ptrtype:=cpointerdef.getreusable(para.left.resultdef);
        tempnode:=ctempcreatenode.create(ptrtype,ptrtype.size,tt_persistent,true);
        addstatement(inlineinitstatement,tempnode);
        isfuncretnode:=nf_is_funcret in para.left.flags;
        if isfuncretnode then
          addstatement(inlinecleanupstatement,ctempdeletenode.create_normal_temp(tempnode))
        else
          addstatement(inlinecleanupstatement,ctempdeletenode.create(tempnode));
        { inherit addr_taken flag }
        if (tabstractvarsym(para.parasym).addr_taken) then
          tempnode.includetempflag(ti_addr_taken);
        { inherit read only }
        if tabstractvarsym(para.parasym).varspez=vs_const then
          tempnode.includetempflag(ti_const);
        paraaddr:=caddrnode.create_internal(para.left);
        include(paraaddr.addrnodeflags,anf_typedaddr);
        addstatement(inlineinitstatement,cassignmentnode.create(ctemprefnode.create(tempnode),
          paraaddr));
        para.left:=cderefnode.create(ctemprefnode.create(tempnode));
        if isfuncretnode then
          Include(para.left.flags,nf_is_funcret);
      end;


    function UsesTmp(var n: tnode; arg: pointer): foreachnoderesult;
      begin
        Result:=fen_false;
        if (n.nodetype=temprefn) and (ttemprefnode(n).tempinfo=arg) then
          Result:=fen_norecurse_true;
      end;


    function tcallnode.optimize_funcret_assignment(inlineblock: tblocknode): tnode;
      var
        hp  : tstatementnode;
        hp2 : tnode;
        resassign : tassignmentnode;
      begin
        result:=nil;
        if not assigned(funcretnode) or
           not(cnf_return_value_used in callnodeflags) then
          exit;

        { block already optimized? }
        if not(inlineblock.nodetype=blockn) then
          exit;

        { tempcreatenode for the function result }
        hp:=tstatementnode(inlineblock.left);
        if not(assigned(hp)) or
           (hp.left.nodetype <> tempcreaten) or
           not(nf_is_funcret in hp.left.flags) then
          exit;

        hp:=tstatementnode(hp.right);
        if not(assigned(hp)) or
           (hp.left.nodetype<>assignn)
          { FK: check commented, original comment was:

              constant assignment? right must be a constant (mainly to avoid trying
              to reuse local temps which may already be freed afterwards once these
              checks are made looser)

            or
            not is_constnode(tassignmentnode(hp.left).right)

            So far I found no example why removing this check might be a problem.
            If this needs to be revert, issue #36279 must be checked/solved again.
          }
          then
          exit;

        { left must be function result }
        resassign:=tassignmentnode(hp.left);
        hp2:=resassign.left;
        { can have extra type conversion due to absolute mapping
          of <fucntionname> on function result var }
        if (hp2.nodetype=typeconvn) and (ttypeconvnode(hp2).convtype=tc_equal) then
          hp2:=ttypeconvnode(hp2).left;
        if (hp2.nodetype<>temprefn) or
          { check if right references the temp. being removed, i.e. using an uninitialized result }
          foreachnodestatic(resassign.right,@UsesTmp,ttemprefnode(hp2).tempinfo) or
          not(nf_is_funcret in hp2.flags) then
          exit;

        { tempdelete to normal of the function result }
        hp:=tstatementnode(hp.right);
        if not(assigned(hp)) or
           (hp.left.nodetype <> tempdeleten) then
          exit;

        { the function result once more }
        hp:=tstatementnode(hp.right);
        if not(assigned(hp)) or
           (hp.left.nodetype<>temprefn) or
           not(nf_is_funcret in hp.left.flags) then
          exit;

        { should be the end }
        if assigned(hp.right) then
          exit;

        { we made it! }
        result:=ctypeconvnode.create_internal(tassignmentnode(resassign).right.getcopy,hp2.resultdef);
        firstpass(result);
      end;


    { this procedure removes the user code flag because it prevents optimizations }
    function removeusercodeflag(var n : tnode; arg : pointer) : foreachnoderesult;
      begin
        result:=fen_false;
        if nf_usercode_entry in n.flags then
          begin
            exclude(n.flags,nf_usercode_entry);
            result:=fen_norecurse_true;
          end;
      end;


    { reference symbols that are imported from another unit }
    function importglobalsyms(var n:tnode; arg:pointer):foreachnoderesult;
      var
        sym : tsym;
      begin
        result:=fen_false;
        if n.nodetype=loadn then
          begin
            sym:=tloadnode(n).symtableentry;
            if sym.typ=staticvarsym then
              begin
                if FindUnitSymtable(tloadnode(n).symtable).moduleid<>current_module.moduleid then
                  current_module.addimportedsym(sym);
              end
            else if (sym.typ=constsym) and (tconstsym(sym).consttyp=constresourcestring) then
              begin
                if tloadnode(n).symtableentry.owner.moduleid<>current_module.moduleid then
                  current_module.addimportedsym(sym);
              end;
          end
        else if (n.nodetype=calln) then
          begin
            if (assigned(tcallnode(n).procdefinition)) and
               (tcallnode(n).procdefinition.typ=procdef) and
               (findunitsymtable(tcallnode(n).procdefinition.owner).moduleid<>current_module.moduleid) then
              current_module.addimportedsym(tprocdef(tcallnode(n).procdefinition).procsym);
          end;
      end;


    function tcallnode.pass1_inline:tnode;
      var
        n,
        body : tnode;
        para : tcallparanode;
        inlineblock,
        inlinecleanupblock : tblocknode;
      begin
        inc(inlinelevel);
        result:=nil;
        if not(assigned(tprocdef(procdefinition).inlininginfo) and
               assigned(tprocdef(procdefinition).inlininginfo^.code)) then
          internalerror(200412021);

        inlinelocals:=TFPObjectList.create(true);

        { inherit flags }
        current_procinfo.flags:=current_procinfo.flags+
          ((procdefinition as tprocdef).inlininginfo^.flags*inherited_inlining_flags);

        { Create new code block for inlining }
        inlineblock:=internalstatements(inlineinitstatement);
        { make sure that valid_for_assign() returns false for this block
          (otherwise assigning values to the block will result in assigning
           values to the inlined function's result) }
        include(inlineblock.flags,nf_no_lvalue);
        inlinecleanupblock:=internalstatements(inlinecleanupstatement);

        if assigned(callinitblock) then
          addstatement(inlineinitstatement,callinitblock.getcopy);

        { replace complex parameters with temps }
        createinlineparas;

        { create a copy of the body and replace parameter loads with the parameter values }
        body:=tprocdef(procdefinition).inlininginfo^.code.getcopy;
        foreachnodestatic(pm_postprocess,body,@removeusercodeflag,nil);
        foreachnodestatic(pm_postprocess,body,@importglobalsyms,nil);
        foreachnode(pm_preprocess,body,@replaceparaload,@fileinfo);

        { Concat the body and finalization parts }
        addstatement(inlineinitstatement,body);
        addstatement(inlineinitstatement,inlinecleanupblock);
        inlinecleanupblock:=nil;

        if assigned(callcleanupblock) then
          addstatement(inlineinitstatement,callcleanupblock.getcopy);

        { the last statement of the new inline block must return the
          location and type of the function result.
          This is not needed when the result is not used, also the tempnode is then
          already destroyed  by a tempdelete in the callcleanupblock tree }
        if not is_void(resultdef) and
           (cnf_return_value_used in callnodeflags) then
          begin
            if assigned(funcretnode) then
              addstatement(inlineinitstatement,funcretnode.getcopy)
            else
              begin
                para:=tcallparanode(left);
                while assigned(para) do
                  begin
                    if (vo_is_hidden_para in para.parasym.varoptions) and
                       (vo_is_funcret in para.parasym.varoptions) then
                      begin
                        addstatement(inlineinitstatement,para.left.getcopy);
                        break;
                      end;
                    para:=tcallparanode(para.right);
                  end;
              end;
          end;

        typecheckpass(tnode(inlineblock));
        doinlinesimplify(tnode(inlineblock));
        node_reset_flags(tnode(inlineblock),[nf_pass1_done]);
        firstpass(tnode(inlineblock));
        result:=inlineblock;

        { if the function result is used then verify that the blocknode
          returns the same result type as the original callnode }
        if (cnf_return_value_used in callnodeflags) and
           (result.resultdef<>resultdef) then
          internalerror(200709171);

        { free the temps for the locals }
        inlinelocals.free;
        inlinelocals:=nil;
        inlineinitstatement:=nil;
        inlinecleanupstatement:=nil;

        n:=optimize_funcret_assignment(inlineblock);
        if assigned(n) then
          begin
            inlineblock.free;
            result:=n;
          end;

{$ifdef DEBUGINLINE}
        writeln;
        writeln('**************************',tprocdef(procdefinition).mangledname);
        printnode(output,result);
{$endif DEBUGINLINE}
        dec(inlinelevel);
      end;

end.