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
|
//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This provides Objective-C code generation targetting the Apple runtime.
//
//===----------------------------------------------------------------------===//
#include "CGObjCRuntime.h"
#include "CodeGenModule.h"
#include "CodeGenFunction.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/LangOptions.h"
#include "llvm/Module.h"
#include "llvm/Support/IRBuilder.h"
#include "llvm/Target/TargetData.h"
#include <sstream>
using namespace clang;
using namespace CodeGen;
namespace {
typedef std::vector<llvm::Constant*> ConstantVector;
// FIXME: We should find a nicer way to make the labels for
// metadata, string concatenation is lame.
/// ObjCTypesHelper - Helper class that encapsulates lazy
/// construction of varies types used during ObjC generation.
class ObjCTypesHelper {
private:
CodeGen::CodeGenModule &CGM;
llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
*MessageSendSuperFpretFn;
public:
const llvm::Type *ShortTy, *IntTy, *LongTy;
const llvm::Type *Int8PtrTy;
/// ObjectPtrTy - LLVM type for object handles (typeof(id))
const llvm::Type *ObjectPtrTy;
/// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
const llvm::Type *SelectorPtrTy;
/// ProtocolPtrTy - LLVM type for external protocol handles
/// (typeof(Protocol))
const llvm::Type *ExternalProtocolPtrTy;
// SuperCTy - clang type for struct objc_super.
QualType SuperCTy;
// SuperPtrCTy - clang type for struct objc_super *.
QualType SuperPtrCTy;
/// SuperTy - LLVM type for struct objc_super.
const llvm::StructType *SuperTy;
/// SuperPtrTy - LLVM type for struct objc_super *.
const llvm::Type *SuperPtrTy;
/// SymtabTy - LLVM type for struct objc_symtab.
const llvm::StructType *SymtabTy;
/// SymtabPtrTy - LLVM type for struct objc_symtab *.
const llvm::Type *SymtabPtrTy;
/// ModuleTy - LLVM type for struct objc_module.
const llvm::StructType *ModuleTy;
/// ProtocolTy - LLVM type for struct objc_protocol.
const llvm::StructType *ProtocolTy;
/// ProtocolPtrTy - LLVM type for struct objc_protocol *.
const llvm::Type *ProtocolPtrTy;
/// ProtocolExtensionTy - LLVM type for struct
/// objc_protocol_extension.
const llvm::StructType *ProtocolExtensionTy;
/// ProtocolExtensionTy - LLVM type for struct
/// objc_protocol_extension *.
const llvm::Type *ProtocolExtensionPtrTy;
/// MethodDescriptionTy - LLVM type for struct
/// objc_method_description.
const llvm::StructType *MethodDescriptionTy;
/// MethodDescriptionListTy - LLVM type for struct
/// objc_method_description_list.
const llvm::StructType *MethodDescriptionListTy;
/// MethodDescriptionListPtrTy - LLVM type for struct
/// objc_method_description_list *.
const llvm::Type *MethodDescriptionListPtrTy;
/// PropertyTy - LLVM type for struct objc_property (struct _prop_t
/// in GCC parlance).
const llvm::StructType *PropertyTy;
/// PropertyListTy - LLVM type for struct objc_property_list
/// (_prop_list_t in GCC parlance).
const llvm::StructType *PropertyListTy;
/// PropertyListPtrTy - LLVM type for struct objc_property_list*.
const llvm::Type *PropertyListPtrTy;
/// ProtocolListTy - LLVM type for struct objc_property_list.
const llvm::Type *ProtocolListTy;
/// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
const llvm::Type *ProtocolListPtrTy;
/// CategoryTy - LLVM type for struct objc_category.
const llvm::StructType *CategoryTy;
/// ClassTy - LLVM type for struct objc_class.
const llvm::StructType *ClassTy;
/// ClassPtrTy - LLVM type for struct objc_class *.
const llvm::Type *ClassPtrTy;
/// ClassExtensionTy - LLVM type for struct objc_class_ext.
const llvm::StructType *ClassExtensionTy;
/// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
const llvm::Type *ClassExtensionPtrTy;
/// CacheTy - LLVM type for struct objc_cache.
const llvm::Type *CacheTy;
/// CachePtrTy - LLVM type for struct objc_cache *.
const llvm::Type *CachePtrTy;
// IvarTy - LLVM type for struct objc_ivar.
const llvm::StructType *IvarTy;
/// IvarListTy - LLVM type for struct objc_ivar_list.
const llvm::Type *IvarListTy;
/// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
const llvm::Type *IvarListPtrTy;
// MethodTy - LLVM type for struct objc_method.
const llvm::StructType *MethodTy;
/// MethodListTy - LLVM type for struct objc_method_list.
const llvm::Type *MethodListTy;
/// MethodListPtrTy - LLVM type for struct objc_method_list *.
const llvm::Type *MethodListPtrTy;
llvm::Function *GetPropertyFn, *SetPropertyFn;
llvm::Function *EnumerationMutationFn;
/// ExceptionDataTy - LLVM type for struct _objc_exception_data.
const llvm::Type *ExceptionDataTy;
/// ExceptionThrowFn - LLVM objc_exception_throw function.
llvm::Function *ExceptionThrowFn;
/// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
llvm::Function *ExceptionTryEnterFn;
/// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
llvm::Function *ExceptionTryExitFn;
/// ExceptionExtractFn - LLVM objc_exception_extract function.
llvm::Function *ExceptionExtractFn;
/// ExceptionMatchFn - LLVM objc_exception_match function.
llvm::Function *ExceptionMatchFn;
/// SetJmpFn - LLVM _setjmp function.
llvm::Function *SetJmpFn;
public:
ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
~ObjCTypesHelper();
llvm::Function *getSendFn(bool IsSuper) {
return IsSuper ? MessageSendSuperFn : MessageSendFn;
}
llvm::Function *getSendStretFn(bool IsSuper) {
return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
}
llvm::Function *getSendFpretFn(bool IsSuper) {
return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
}
};
class CGObjCMac : public CodeGen::CGObjCRuntime {
private:
CodeGen::CodeGenModule &CGM;
ObjCTypesHelper ObjCTypes;
/// ObjCABI - FIXME: Not sure yet.
unsigned ObjCABI;
/// LazySymbols - Symbols to generate a lazy reference for. See
/// DefinedSymbols and FinishModule().
std::set<IdentifierInfo*> LazySymbols;
/// DefinedSymbols - External symbols which are defined by this
/// module. The symbols in this list and LazySymbols are used to add
/// special linker symbols which ensure that Objective-C modules are
/// linked properly.
std::set<IdentifierInfo*> DefinedSymbols;
/// ClassNames - uniqued class names.
llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
/// MethodVarNames - uniqued method variable names.
llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
/// MethodVarTypes - uniqued method type signatures. We have to use
/// a StringMap here because have no other unique reference.
llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
/// MethodDefinitions - map of methods which have been defined in
/// this translation unit.
llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
/// PropertyNames - uniqued method variable names.
llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
/// ClassReferences - uniqued class references.
llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
/// SelectorReferences - uniqued selector references.
llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
/// Protocols - Protocols for which an objc_protocol structure has
/// been emitted. Forward declarations are handled by creating an
/// empty structure whose initializer is filled in when/if defined.
llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
/// DefinedClasses - List of defined classes.
std::vector<llvm::GlobalValue*> DefinedClasses;
/// DefinedCategories - List of defined categories.
std::vector<llvm::GlobalValue*> DefinedCategories;
/// UsedGlobals - List of globals to pack into the llvm.used metadata
/// to prevent them from being clobbered.
std::vector<llvm::GlobalVariable*> UsedGlobals;
/// EmitImageInfo - Emit the image info marker used to encode some module
/// level information.
void EmitImageInfo();
/// EmitModuleInfo - Another marker encoding module level
/// information.
void EmitModuleInfo();
/// EmitModuleSymols - Emit module symbols, the list of defined
/// classes and categories. The result has type SymtabPtrTy.
llvm::Constant *EmitModuleSymbols();
/// FinishModule - Write out global data structures at the end of
/// processing a translation unit.
void FinishModule();
/// EmitClassExtension - Generate the class extension structure used
/// to store the weak ivar layout and properties. The return value
/// has type ClassExtensionPtrTy.
llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
/// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
/// for the given class.
llvm::Value *EmitClassRef(llvm::IRBuilder<> &Builder,
const ObjCInterfaceDecl *ID);
CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
QualType ResultType,
Selector Sel,
llvm::Value *Arg0,
QualType Arg0Ty,
bool IsSuper,
const CallArgList &CallArgs);
/// EmitIvarList - Emit the ivar list for the given
/// implementation. If ForClass is true the list of class ivars
/// (i.e. metaclass ivars) is emitted, otherwise the list of
/// interface ivars will be emitted. The return value has type
/// IvarListPtrTy.
llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
bool ForClass,
const llvm::Type *InterfaceTy);
/// EmitMetaClass - Emit a forward reference to the class structure
/// for the metaclass of the given interface. The return value has
/// type ClassPtrTy.
llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
/// EmitMetaClass - Emit a class structure for the metaclass of the
/// given implementation. The return value has type ClassPtrTy.
llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
llvm::Constant *Protocols,
const llvm::Type *InterfaceTy,
const ConstantVector &Methods);
llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
/// EmitMethodList - Emit the method list for the given
/// implementation. The return value has type MethodListPtrTy.
llvm::Constant *EmitMethodList(const std::string &Name,
const char *Section,
const ConstantVector &Methods);
/// EmitMethodDescList - Emit a method description list for a list of
/// method declarations.
/// - TypeName: The name for the type containing the methods.
/// - IsProtocol: True iff these methods are for a protocol.
/// - ClassMethds: True iff these are class methods.
/// - Required: When true, only "required" methods are
/// listed. Similarly, when false only "optional" methods are
/// listed. For classes this should always be true.
/// - begin, end: The method list to output.
///
/// The return value has type MethodDescriptionListPtrTy.
llvm::Constant *EmitMethodDescList(const std::string &Name,
const char *Section,
const ConstantVector &Methods);
/// EmitPropertyList - Emit the given property list. The return
/// value has type PropertyListPtrTy.
llvm::Constant *EmitPropertyList(const std::string &Name,
const Decl *Container,
ObjCPropertyDecl * const *begin,
ObjCPropertyDecl * const *end);
/// EmitProtocolExtension - Generate the protocol extension
/// structure used to store optional instance and class methods, and
/// protocol properties. The return value has type
/// ProtocolExtensionPtrTy.
llvm::Constant *
EmitProtocolExtension(const ObjCProtocolDecl *PD,
const ConstantVector &OptInstanceMethods,
const ConstantVector &OptClassMethods);
/// EmitProtocolList - Generate the list of referenced
/// protocols. The return value has type ProtocolListPtrTy.
llvm::Constant *EmitProtocolList(const std::string &Name,
ObjCProtocolDecl::protocol_iterator begin,
ObjCProtocolDecl::protocol_iterator end);
/// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
/// for the given selector.
llvm::Value *EmitSelector(llvm::IRBuilder<> &Builder, Selector Sel);
/// GetProtocolRef - Return a reference to the internal protocol
/// description, creating an empty one if it has not been
/// defined. The return value has type pointer-to ProtocolTy.
llvm::GlobalVariable *GetProtocolRef(const ObjCProtocolDecl *PD);
/// GetClassName - Return a unique constant for the given selector's
/// name. The return value has type char *.
llvm::Constant *GetClassName(IdentifierInfo *Ident);
/// GetMethodVarName - Return a unique constant for the given
/// selector's name. The return value has type char *.
llvm::Constant *GetMethodVarName(Selector Sel);
llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
llvm::Constant *GetMethodVarName(const std::string &Name);
/// GetMethodVarType - Return a unique constant for the given
/// selector's name. The return value has type char *.
// FIXME: This is a horrible name.
llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
llvm::Constant *GetMethodVarType(const std::string &Name);
/// GetPropertyName - Return a unique constant for the given
/// name. The return value has type char *.
llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
// FIXME: This can be dropped once string functions are unified.
llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
const Decl *Container);
/// GetNameForMethod - Return a name for the given method.
/// \param[out] NameOut - The return value.
void GetNameForMethod(const ObjCMethodDecl *OMD,
std::string &NameOut);
public:
CGObjCMac(CodeGen::CodeGenModule &cgm);
virtual llvm::Constant *GenerateConstantString(const std::string &String);
virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
QualType ResultType,
Selector Sel,
llvm::Value *Receiver,
bool IsClassMessage,
const CallArgList &CallArgs);
virtual CodeGen::RValue
GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
QualType ResultType,
Selector Sel,
const ObjCInterfaceDecl *Class,
llvm::Value *Receiver,
bool IsClassMessage,
const CallArgList &CallArgs);
virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder,
const ObjCInterfaceDecl *ID);
virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
const ObjCProtocolDecl *PD);
virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
virtual llvm::Function *ModuleInitFunction();
virtual llvm::Function *GetPropertyGetFunction();
virtual llvm::Function *GetPropertySetFunction();
virtual llvm::Function *EnumerationMutationFunction();
virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
const ObjCAtTryStmt &S);
virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
const ObjCAtThrowStmt &S);
};
} // end anonymous namespace
/* *** Helper Functions *** */
/// getConstantGEP() - Help routine to construct simple GEPs.
static llvm::Constant *getConstantGEP(llvm::Constant *C,
unsigned idx0,
unsigned idx1) {
llvm::Value *Idxs[] = {
llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
};
return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
}
/* *** CGObjCMac Public Interface *** */
CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
: CGM(cgm),
ObjCTypes(cgm),
ObjCABI(1)
{
// FIXME: How does this get set in GCC? And what does it even mean?
if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
ObjCABI = 2;
EmitImageInfo();
}
/// GetClass - Return a reference to the class for the given interface
/// decl.
llvm::Value *CGObjCMac::GetClass(llvm::IRBuilder<> &Builder,
const ObjCInterfaceDecl *ID) {
return EmitClassRef(Builder, ID);
}
/// GetSelector - Return the pointer to the unique'd string for this selector.
llvm::Value *CGObjCMac::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
return EmitSelector(Builder, Sel);
}
/// Generate a constant CFString object.
/*
struct __builtin_CFString {
const int *isa; // point to __CFConstantStringClassReference
int flags;
const char *str;
long length;
};
*/
llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
return CGM.GetAddrOfConstantCFString(String);
}
/// Generates a message send where the super is the receiver. This is
/// a message send to self with special delivery semantics indicating
/// which class's method should be called.
CodeGen::RValue
CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
QualType ResultType,
Selector Sel,
const ObjCInterfaceDecl *Class,
llvm::Value *Receiver,
bool IsClassMessage,
const CodeGen::CallArgList &CallArgs) {
// Create and init a super structure; this is a (receiver, class)
// pair we will pass to objc_msgSendSuper.
llvm::Value *ObjCSuper =
CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
llvm::Value *ReceiverAsObject =
CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
CGF.Builder.CreateStore(ReceiverAsObject,
CGF.Builder.CreateStructGEP(ObjCSuper, 0));
// If this is a class message the metaclass is passed as the target.
llvm::Value *Target;
if (IsClassMessage) {
llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
Target = Super;
} else {
Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
}
// FIXME: We shouldn't need to do this cast, rectify the ASTContext
// and ObjCTypes types.
const llvm::Type *ClassTy =
CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Target = CGF.Builder.CreateBitCast(Target, ClassTy);
CGF.Builder.CreateStore(Target,
CGF.Builder.CreateStructGEP(ObjCSuper, 1));
return EmitMessageSend(CGF, ResultType, Sel,
ObjCSuper, ObjCTypes.SuperPtrCTy,
true, CallArgs);
}
/// Generate code for a message send expression.
CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
QualType ResultType,
Selector Sel,
llvm::Value *Receiver,
bool IsClassMessage,
const CallArgList &CallArgs) {
llvm::Value *Arg0 =
CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
return EmitMessageSend(CGF, ResultType, Sel,
Arg0, CGF.getContext().getObjCIdType(),
false, CallArgs);
}
CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
QualType ResultType,
Selector Sel,
llvm::Value *Arg0,
QualType Arg0Ty,
bool IsSuper,
const CallArgList &CallArgs) {
CallArgList ActualArgs;
ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
Sel)),
CGF.getContext().getObjCSelType()));
ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
const llvm::FunctionType *FTy =
CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
false);
llvm::Constant *Fn;
if (CGM.ReturnTypeUsesSret(ResultType)) {
Fn = ObjCTypes.getSendStretFn(IsSuper);
} else if (ResultType->isFloatingType()) {
// FIXME: Sadly, this is wrong. This actually depends on the
// architecture. This happens to be right for x86-32 though.
Fn = ObjCTypes.getSendFpretFn(IsSuper);
} else {
Fn = ObjCTypes.getSendFn(IsSuper);
}
Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
return CGF.EmitCall(Fn, ResultType, ActualArgs);
}
llvm::Value *CGObjCMac::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
const ObjCProtocolDecl *PD) {
// FIXME: I don't understand why gcc generates this, or where it is
// resolved. Investigate. Its also wasteful to look this up over and
// over.
LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
ObjCTypes.ExternalProtocolPtrTy);
}
/*
// APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
struct _objc_protocol {
struct _objc_protocol_extension *isa;
char *protocol_name;
struct _objc_protocol_list *protocol_list;
struct _objc__method_prototype_list *instance_methods;
struct _objc__method_prototype_list *class_methods
};
See EmitProtocolExtension().
*/
void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
// FIXME: I don't understand why gcc generates this, or where it is
// resolved. Investigate. Its also wasteful to look this up over and
// over.
LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
const char *ProtocolName = PD->getName();
// Construct method lists.
std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
e = PD->instmeth_end(); i != e; ++i) {
ObjCMethodDecl *MD = *i;
llvm::Constant *C = GetMethodDescriptionConstant(MD);
if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
OptInstanceMethods.push_back(C);
} else {
InstanceMethods.push_back(C);
}
}
for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
e = PD->classmeth_end(); i != e; ++i) {
ObjCMethodDecl *MD = *i;
llvm::Constant *C = GetMethodDescriptionConstant(MD);
if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
OptClassMethods.push_back(C);
} else {
ClassMethods.push_back(C);
}
}
std::vector<llvm::Constant*> Values(5);
Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Values[1] = GetClassName(PD->getIdentifier());
Values[2] =
EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
PD->protocol_begin(),
PD->protocol_end());
Values[3] =
EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
+ PD->getName(),
"__OBJC,__cat_inst_meth,regular,no_dead_strip",
InstanceMethods);
Values[4] =
EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
+ PD->getName(),
"__OBJC,__cat_cls_meth,regular,no_dead_strip",
ClassMethods);
llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Values);
llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
if (Entry) {
// Already created, just update the initializer
Entry->setInitializer(Init);
} else {
Entry =
new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
llvm::GlobalValue::InternalLinkage,
Init,
std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
&CGM.getModule());
Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
UsedGlobals.push_back(Entry);
// FIXME: Is this necessary? Why only for protocol?
Entry->setAlignment(4);
}
}
llvm::GlobalVariable *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
if (!Entry) {
std::vector<llvm::Constant*> Values(5);
Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Values[1] = GetClassName(PD->getIdentifier());
Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Values[3] = Values[4] =
llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Values);
Entry =
new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
llvm::GlobalValue::InternalLinkage,
Init,
std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
&CGM.getModule());
Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
UsedGlobals.push_back(Entry);
// FIXME: Is this necessary? Why only for protocol?
Entry->setAlignment(4);
}
return Entry;
}
/*
struct _objc_protocol_extension {
uint32_t size;
struct objc_method_description_list *optional_instance_methods;
struct objc_method_description_list *optional_class_methods;
struct objc_property_list *instance_properties;
};
*/
llvm::Constant *
CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
const ConstantVector &OptInstanceMethods,
const ConstantVector &OptClassMethods) {
uint64_t Size =
CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
std::vector<llvm::Constant*> Values(4);
Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Values[1] =
EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
+ PD->getName(),
"__OBJC,__cat_inst_meth,regular,no_dead_strip",
OptInstanceMethods);
Values[2] =
EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
+ PD->getName(),
"__OBJC,__cat_cls_meth,regular,no_dead_strip",
OptClassMethods);
Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
PD->getName(),
0,
PD->classprop_begin(),
PD->classprop_end());
// Return null if no extension bits are used.
if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
Values[3]->isNullValue())
return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
llvm::Constant *Init =
llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
llvm::GlobalValue::InternalLinkage,
Init,
(std::string("\01L_OBJC_PROTOCOLEXT_") +
PD->getName()),
&CGM.getModule());
// No special section, but goes in llvm.used
UsedGlobals.push_back(GV);
return GV;
}
/*
struct objc_protocol_list {
struct objc_protocol_list *next;
long count;
Protocol *list[];
};
*/
llvm::Constant *
CGObjCMac::EmitProtocolList(const std::string &Name,
ObjCProtocolDecl::protocol_iterator begin,
ObjCProtocolDecl::protocol_iterator end) {
std::vector<llvm::Constant*> ProtocolRefs;
for (; begin != end; ++begin)
ProtocolRefs.push_back(GetProtocolRef(*begin));
// Just return null for empty protocol lists
if (ProtocolRefs.empty())
return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
// This list is null terminated.
ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
std::vector<llvm::Constant*> Values(3);
// This field is only used by the runtime.
Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
Values[2] =
llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
ProtocolRefs.size()),
ProtocolRefs);
llvm::Constant *Init = llvm::ConstantStruct::get(Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(Init->getType(), false,
llvm::GlobalValue::InternalLinkage,
Init,
Name,
&CGM.getModule());
GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
}
/*
struct _objc_property {
const char * const name;
const char * const attributes;
};
struct _objc_property_list {
uint32_t entsize; // sizeof (struct _objc_property)
uint32_t prop_count;
struct _objc_property[prop_count];
};
*/
llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
const Decl *Container,
ObjCPropertyDecl * const *begin,
ObjCPropertyDecl * const *end) {
std::vector<llvm::Constant*> Properties, Prop(2);
for (; begin != end; ++begin) {
const ObjCPropertyDecl *PD = *begin;
Prop[0] = GetPropertyName(PD->getIdentifier());
Prop[1] = GetPropertyTypeString(PD, Container);
Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
Prop));
}
// Return null for empty list.
if (Properties.empty())
return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
unsigned PropertySize =
CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
std::vector<llvm::Constant*> Values(3);
Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
Properties.size());
Values[2] = llvm::ConstantArray::get(AT, Properties);
llvm::Constant *Init = llvm::ConstantStruct::get(Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(Init->getType(), false,
llvm::GlobalValue::InternalLinkage,
Init,
Name,
&CGM.getModule());
// No special section on property lists?
UsedGlobals.push_back(GV);
return llvm::ConstantExpr::getBitCast(GV,
ObjCTypes.PropertyListPtrTy);
}
/*
struct objc_method_description_list {
int count;
struct objc_method_description list[];
};
*/
llvm::Constant *
CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
std::vector<llvm::Constant*> Desc(2);
Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
ObjCTypes.SelectorPtrTy);
Desc[1] = GetMethodVarType(MD);
return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
Desc);
}
llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
const char *Section,
const ConstantVector &Methods) {
// Return null for empty list.
if (Methods.empty())
return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
std::vector<llvm::Constant*> Values(2);
Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
Methods.size());
Values[1] = llvm::ConstantArray::get(AT, Methods);
llvm::Constant *Init = llvm::ConstantStruct::get(Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(Init->getType(), false,
llvm::GlobalValue::InternalLinkage,
Init, Name, &CGM.getModule());
GV->setSection(Section);
UsedGlobals.push_back(GV);
return llvm::ConstantExpr::getBitCast(GV,
ObjCTypes.MethodDescriptionListPtrTy);
}
/*
struct _objc_category {
char *category_name;
char *class_name;
struct _objc_method_list *instance_methods;
struct _objc_method_list *class_methods;
struct _objc_protocol_list *protocols;
uint32_t size; // <rdar://4585769>
struct _objc_property_list *instance_properties;
};
*/
void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
// FIXME: This is poor design, the OCD should have a pointer to the
// category decl. Additionally, note that Category can be null for
// the @implementation w/o an @interface case. Sema should just
// create one for us as it does for @implementation so everyone else
// can live life under a clear blue sky.
const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
const ObjCCategoryDecl *Category =
Interface->FindCategoryDeclaration(OCD->getIdentifier());
std::string ExtName(std::string(Interface->getName()) +
"_" +
OCD->getName());
std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
e = OCD->instmeth_end(); i != e; ++i) {
// Instance methods should always be defined.
InstanceMethods.push_back(GetMethodConstant(*i));
}
for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
e = OCD->classmeth_end(); i != e; ++i) {
// Class methods should always be defined.
ClassMethods.push_back(GetMethodConstant(*i));
}
std::vector<llvm::Constant*> Values(7);
Values[0] = GetClassName(OCD->getIdentifier());
Values[1] = GetClassName(Interface->getIdentifier());
Values[2] =
EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
ExtName,
"__OBJC,__cat_inst_meth,regular,no_dead_strip",
InstanceMethods);
Values[3] =
EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
"__OBJC,__cat_class_meth,regular,no_dead_strip",
ClassMethods);
if (Category) {
Values[4] =
EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
Category->protocol_begin(),
Category->protocol_end());
} else {
Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
}
Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
// If there is no category @interface then there can be no properties.
if (Category) {
Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
OCD,
Category->classprop_begin(),
Category->classprop_end());
} else {
Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
}
llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
llvm::GlobalValue::InternalLinkage,
Init,
std::string("\01L_OBJC_CATEGORY_")+ExtName,
&CGM.getModule());
GV->setSection("__OBJC,__category,regular,no_dead_strip");
UsedGlobals.push_back(GV);
DefinedCategories.push_back(GV);
}
// FIXME: Get from somewhere?
enum ClassFlags {
eClassFlags_Factory = 0x00001,
eClassFlags_Meta = 0x00002,
// <rdr://5142207>
eClassFlags_HasCXXStructors = 0x02000,
eClassFlags_Hidden = 0x20000,
eClassFlags_ABI2_Hidden = 0x00010,
eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
};
// <rdr://5142207&4705298&4843145>
static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
// FIXME: Support -fvisibility
switch (attr->getVisibility()) {
default:
assert(0 && "Unknown visibility");
return false;
case VisibilityAttr::DefaultVisibility:
case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
return false;
case VisibilityAttr::HiddenVisibility:
return true;
}
} else {
return false; // FIXME: Support -fvisibility
}
}
/*
struct _objc_class {
Class isa;
Class super_class;
const char *name;
long version;
long info;
long instance_size;
struct _objc_ivar_list *ivars;
struct _objc_method_list *methods;
struct _objc_cache *cache;
struct _objc_protocol_list *protocols;
// Objective-C 1.0 extensions (<rdr://4585769>)
const char *ivar_layout;
struct _objc_class_ext *ext;
};
See EmitClassExtension();
*/
void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
DefinedSymbols.insert(ID->getIdentifier());
const char *ClassName = ID->getName();
// FIXME: Gross
ObjCInterfaceDecl *Interface =
const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
llvm::Constant *Protocols =
EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
Interface->protocol_begin(),
Interface->protocol_end());
const llvm::Type *InterfaceTy =
CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
unsigned Flags = eClassFlags_Factory;
unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
// FIXME: Set CXX-structors flag.
if (IsClassHidden(ID->getClassInterface()))
Flags |= eClassFlags_Hidden;
std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
e = ID->instmeth_end(); i != e; ++i) {
// Instance methods should always be defined.
InstanceMethods.push_back(GetMethodConstant(*i));
}
for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
e = ID->classmeth_end(); i != e; ++i) {
// Class methods should always be defined.
ClassMethods.push_back(GetMethodConstant(*i));
}
for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
e = ID->propimpl_end(); i != e; ++i) {
ObjCPropertyImplDecl *PID = *i;
if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
ObjCPropertyDecl *PD = PID->getPropertyDecl();
if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
if (llvm::Constant *C = GetMethodConstant(MD))
InstanceMethods.push_back(C);
if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
if (llvm::Constant *C = GetMethodConstant(MD))
InstanceMethods.push_back(C);
}
}
std::vector<llvm::Constant*> Values(12);
Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
// Record a reference to the super class.
LazySymbols.insert(Super->getIdentifier());
Values[ 1] =
llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
ObjCTypes.ClassPtrTy);
} else {
Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
}
Values[ 2] = GetClassName(ID->getIdentifier());
// Version is always 0.
Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Values[ 7] =
EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
"__OBJC,__inst_meth,regular,no_dead_strip",
InstanceMethods);
// cache is always NULL.
Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Values[ 9] = Protocols;
// FIXME: Set ivar_layout
Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Values[11] = EmitClassExtension(ID);
llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
llvm::GlobalValue::InternalLinkage,
Init,
std::string("\01L_OBJC_CLASS_")+ClassName,
&CGM.getModule());
GV->setSection("__OBJC,__class,regular,no_dead_strip");
UsedGlobals.push_back(GV);
// FIXME: Why?
GV->setAlignment(32);
DefinedClasses.push_back(GV);
}
llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
llvm::Constant *Protocols,
const llvm::Type *InterfaceTy,
const ConstantVector &Methods) {
const char *ClassName = ID->getName();
unsigned Flags = eClassFlags_Meta;
unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
if (IsClassHidden(ID->getClassInterface()))
Flags |= eClassFlags_Hidden;
std::vector<llvm::Constant*> Values(12);
// The isa for the metaclass is the root of the hierarchy.
const ObjCInterfaceDecl *Root = ID->getClassInterface();
while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
Root = Super;
Values[ 0] =
llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
ObjCTypes.ClassPtrTy);
// The super class for the metaclass is emitted as the name of the
// super class. The runtime fixes this up to point to the
// *metaclass* for the super class.
if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
Values[ 1] =
llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
ObjCTypes.ClassPtrTy);
} else {
Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
}
Values[ 2] = GetClassName(ID->getIdentifier());
// Version is always 0.
Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Values[ 7] =
EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
"__OBJC,__inst_meth,regular,no_dead_strip",
Methods);
// cache is always NULL.
Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Values[ 9] = Protocols;
// ivar_layout for metaclass is always NULL.
Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
// The class extension is always unused for metaclasses.
Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Values);
std::string Name("\01L_OBJC_METACLASS_");
Name += ClassName;
// Check for a forward reference.
llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
if (GV) {
assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
"Forward metaclass reference has incorrect type.");
GV->setLinkage(llvm::GlobalValue::InternalLinkage);
GV->setInitializer(Init);
} else {
GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
llvm::GlobalValue::InternalLinkage,
Init, Name,
&CGM.getModule());
}
GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
UsedGlobals.push_back(GV);
// FIXME: Why?
GV->setAlignment(32);
return GV;
}
llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
std::string Name("\01L_OBJC_METACLASS_");
Name += ID->getName();
// FIXME: Should we look these up somewhere other than the
// module. Its a bit silly since we only generate these while
// processing an implementation, so exactly one pointer would work
// if know when we entered/exitted an implementation block.
// Check for an existing forward reference.
if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
"Forward metaclass reference has incorrect type.");
return GV;
} else {
// Generate as an external reference to keep a consistent
// module. This will be patched up when we emit the metaclass.
return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
llvm::GlobalValue::ExternalLinkage,
0,
Name,
&CGM.getModule());
}
}
/*
struct objc_class_ext {
uint32_t size;
const char *weak_ivar_layout;
struct _objc_property_list *properties;
};
*/
llvm::Constant *
CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
uint64_t Size =
CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
std::vector<llvm::Constant*> Values(3);
Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
// FIXME: Output weak_ivar_layout string.
Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
ID->getName(),
ID,
ID->getClassInterface()->classprop_begin(),
ID->getClassInterface()->classprop_end());
// Return null if no extension bits are used.
if (Values[1]->isNullValue() && Values[2]->isNullValue())
return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
llvm::Constant *Init =
llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
llvm::GlobalValue::InternalLinkage,
Init,
(std::string("\01L_OBJC_CLASSEXT_") +
ID->getName()),
&CGM.getModule());
// No special section, but goes in llvm.used
UsedGlobals.push_back(GV);
return GV;
}
/*
struct objc_ivar {
char *ivar_name;
char *ivar_type;
int ivar_offset;
};
struct objc_ivar_list {
int ivar_count;
struct objc_ivar list[count];
};
*/
llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
bool ForClass,
const llvm::Type *InterfaceTy) {
std::vector<llvm::Constant*> Ivars, Ivar(3);
// When emitting the root class GCC emits ivar entries for the
// actual class structure. It is not clear if we need to follow this
// behavior; for now lets try and get away with not doing it. If so,
// the cleanest solution would be to make up an ObjCInterfaceDecl
// for the class.
if (ForClass)
return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
const llvm::StructLayout *Layout =
CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
for (ObjCInterfaceDecl::ivar_iterator
i = ID->getClassInterface()->ivar_begin(),
e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
ObjCIvarDecl *V = *i;
unsigned Offset =
Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
std::string TypeStr;
llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Ivar[0] = GetMethodVarName(V->getIdentifier());
CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr,
EncodingRecordTypes,
true);
Ivar[1] = GetMethodVarType(TypeStr);
Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy,
Ivar));
}
// Return null for empty list.
if (Ivars.empty())
return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
std::vector<llvm::Constant*> Values(2);
Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
Ivars.size());
Values[1] = llvm::ConstantArray::get(AT, Ivars);
llvm::Constant *Init = llvm::ConstantStruct::get(Values);
const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
"\01L_OBJC_INSTANCE_VARIABLES_");
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(Init->getType(), false,
llvm::GlobalValue::InternalLinkage,
Init,
std::string(Prefix) + ID->getName(),
&CGM.getModule());
if (ForClass) {
GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
// FIXME: Why is this only here?
GV->setAlignment(32);
} else {
GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
}
UsedGlobals.push_back(GV);
return llvm::ConstantExpr::getBitCast(GV,
ObjCTypes.IvarListPtrTy);
}
/*
struct objc_method {
SEL method_name;
char *method_types;
void *method;
};
struct objc_method_list {
struct objc_method_list *obsolete;
int count;
struct objc_method methods_list[count];
};
*/
/// GetMethodConstant - Return a struct objc_method constant for the
/// given method if it has been defined. The result is null if the
/// method has not been defined. The return value has type MethodPtrTy.
llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
// FIXME: Use DenseMap::lookup
llvm::Function *Fn = MethodDefinitions[MD];
if (!Fn)
return 0;
std::vector<llvm::Constant*> Method(3);
Method[0] =
llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
ObjCTypes.SelectorPtrTy);
Method[1] = GetMethodVarType(MD);
Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
}
llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
const char *Section,
const ConstantVector &Methods) {
// Return null for empty list.
if (Methods.empty())
return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
std::vector<llvm::Constant*> Values(3);
Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Methods.size());
Values[2] = llvm::ConstantArray::get(AT, Methods);
llvm::Constant *Init = llvm::ConstantStruct::get(Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(Init->getType(), false,
llvm::GlobalValue::InternalLinkage,
Init,
Name,
&CGM.getModule());
GV->setSection(Section);
UsedGlobals.push_back(GV);
return llvm::ConstantExpr::getBitCast(GV,
ObjCTypes.MethodListPtrTy);
}
llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
std::string Name;
GetNameForMethod(OMD, Name);
const llvm::FunctionType *MethodTy =
CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
llvm::Function *Method =
llvm::Function::Create(MethodTy,
llvm::GlobalValue::InternalLinkage,
Name,
&CGM.getModule());
MethodDefinitions.insert(std::make_pair(OMD, Method));
return Method;
}
llvm::Function *CGObjCMac::ModuleInitFunction() {
// Abuse this interface function as a place to finalize.
FinishModule();
return NULL;
}
llvm::Function *CGObjCMac::GetPropertyGetFunction() {
return ObjCTypes.GetPropertyFn;
}
llvm::Function *CGObjCMac::GetPropertySetFunction() {
return ObjCTypes.SetPropertyFn;
}
llvm::Function *CGObjCMac::EnumerationMutationFunction()
{
return ObjCTypes.EnumerationMutationFn;
}
/*
Objective-C setjmp-longjmp (sjlj) Exception Handling
--
The basic framework for a @try-catch-finally is as follows:
{
objc_exception_data d;
id _rethrow = null;
objc_exception_try_enter(&d);
if (!setjmp(d.jmp_buf)) {
... try body ...
} else {
// exception path
id _caught = objc_exception_extract(&d);
// enter new try scope for handlers
if (!setjmp(d.jmp_buf)) {
... match exception and execute catch blocks ...
// fell off end, rethrow.
_rethrow = _caught;
... jump-through-finally to finally_rethrow ...
} else {
// exception in catch block
_rethrow = objc_exception_extract(&d);
... jump-through-finally_no_exit to finally_rethrow ...
}
}
... jump-through-finally to finally_end ...
finally:
// match either the initial try_enter or the catch try_enter,
// depending on the path followed.
objc_exception_try_exit(&d);
finally_no_exit:
... finally block ....
... dispatch to finally destination ...
finally_rethrow:
objc_exception_throw(_rethrow);
finally_end:
}
This framework differs slightly from the one gcc uses, in that gcc
uses _rethrow to determine if objc_exception_try_exit should be called
and if the object should be rethrown. This breaks in the face of
throwing nil and introduces unnecessary branches.
We specialize this framework for a few particular circumstances:
- If there are no catch blocks, then we avoid emitting the second
exception handling context.
- If there is a catch-all catch block (i.e. @catch(...) or @catch(id
e)) we avoid emitting the code to rethrow an uncaught exception.
- FIXME: If there is no @finally block we can do a few more
simplifications.
Rethrows and Jumps-Through-Finally
--
Support for implicit rethrows and jumping through the finally block is
handled by storing the current exception-handling context in
ObjCEHStack.
In order to implement proper @finally semantics, we support one basic
mechanism for jumping through the finally block to an arbitrary
destination. Constructs which generate exits from a @try or @catch
block use this mechanism to implement the proper semantics by chaining
jumps, as necessary.
This mechanism works like the one used for indirect goto: we
arbitrarily assign an ID to each destination and store the ID for the
destination in a variable prior to entering the finally block. At the
end of the finally block we simply create a switch to the proper
destination.
*/
void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
const ObjCAtTryStmt &S) {
// Create various blocks we refer to for handling @finally.
llvm::BasicBlock *FinallyBlock = llvm::BasicBlock::Create("finally");
llvm::BasicBlock *FinallyNoExit = llvm::BasicBlock::Create("finally.noexit");
llvm::BasicBlock *FinallyRethrow = llvm::BasicBlock::Create("finally.throw");
llvm::BasicBlock *FinallyEnd = llvm::BasicBlock::Create("finally.end");
llvm::Value *DestCode =
CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
// Generate jump code. Done here so we can directly add things to
// the switch instruction.
llvm::BasicBlock *FinallyJump = llvm::BasicBlock::Create("finally.jump");
llvm::SwitchInst *FinallySwitch =
llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
FinallyEnd, 10, FinallyJump);
// Push an EH context entry, used for handling rethrows and jumps
// through finally.
CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
FinallySwitch, DestCode);
CGF.ObjCEHStack.push_back(&EHEntry);
// Allocate memory for the exception data and rethrow pointer.
llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
"exceptiondata.ptr");
llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy, "_rethrow");
// Enter a new try block and call setjmp.
CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
"jmpbufarray");
JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
JmpBufPtr, "result");
llvm::BasicBlock *TryBlock = llvm::BasicBlock::Create("try");
llvm::BasicBlock *TryHandler = llvm::BasicBlock::Create("try.handler");
CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
TryHandler, TryBlock);
// Emit the @try block.
CGF.EmitBlock(TryBlock);
CGF.EmitStmt(S.getTryBody());
CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
// Emit the "exception in @try" block.
CGF.EmitBlock(TryHandler);
// Retrieve the exception object. We may emit multiple blocks but
// nothing can cross this so the value is already in SSA form.
llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
ExceptionData,
"caught");
EHEntry.Exception = Caught;
if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
// Enter a new exception try block (in case a @catch block throws
// an exception).
CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
JmpBufPtr, "result");
llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
llvm::BasicBlock *CatchBlock = llvm::BasicBlock::Create("catch");
llvm::BasicBlock *CatchHandler = llvm::BasicBlock::Create("catch.handler");
CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
CGF.EmitBlock(CatchBlock);
// Handle catch list. As a special case we check if everything is
// matched and avoid generating code for falling off the end if
// so.
bool AllMatched = false;
for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
llvm::BasicBlock *NextCatchBlock = llvm::BasicBlock::Create("catch");
const DeclStmt *CatchParam =
cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
const VarDecl *VD = 0;
const PointerType *PT = 0;
// catch(...) always matches.
if (!CatchParam) {
AllMatched = true;
} else {
VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
PT = VD->getType()->getAsPointerType();
// catch(id e) always matches.
// FIXME: For the time being we also match id<X>; this should
// be rejected by Sema instead.
if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
VD->getType()->isObjCQualifiedIdType())
AllMatched = true;
}
if (AllMatched) {
if (CatchParam) {
CGF.EmitStmt(CatchParam);
CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
}
CGF.EmitStmt(CatchStmt->getCatchBody());
CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
break;
}
assert(PT && "Unexpected non-pointer type in @catch");
QualType T = PT->getPointeeType();
const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
assert(ObjCType && "Catch parameter must have Objective-C type!");
// Check if the @catch block matches the exception object.
llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
Class, Caught, "match");
llvm::BasicBlock *MatchedBlock = llvm::BasicBlock::Create("matched");
CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
MatchedBlock, NextCatchBlock);
// Emit the @catch block.
CGF.EmitBlock(MatchedBlock);
CGF.EmitStmt(CatchParam);
llvm::Value *Tmp =
CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
"tmp");
CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
CGF.EmitStmt(CatchStmt->getCatchBody());
CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
CGF.EmitBlock(NextCatchBlock);
}
if (!AllMatched) {
// None of the handlers caught the exception, so store it to be
// rethrown at the end of the @finally block.
CGF.Builder.CreateStore(Caught, RethrowPtr);
CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
}
// Emit the exception handler for the @catch blocks.
CGF.EmitBlock(CatchHandler);
CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
ExceptionData),
RethrowPtr);
CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
} else {
CGF.Builder.CreateStore(Caught, RethrowPtr);
CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
}
// Pop the exception-handling stack entry. It is important to do
// this now, because the code in the @finally block is not in this
// context.
CGF.ObjCEHStack.pop_back();
// Emit the @finally block.
CGF.EmitBlock(FinallyBlock);
CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
CGF.EmitBlock(FinallyNoExit);
if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
CGF.EmitStmt(FinallyStmt->getFinallyBody());
CGF.EmitBlock(FinallyJump);
CGF.EmitBlock(FinallyRethrow);
CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
CGF.Builder.CreateLoad(RethrowPtr));
CGF.Builder.CreateUnreachable();
CGF.EmitBlock(FinallyEnd);
}
void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
const ObjCAtThrowStmt &S) {
llvm::Value *ExceptionAsObject;
if (const Expr *ThrowExpr = S.getThrowExpr()) {
llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
ExceptionAsObject =
CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
} else {
assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
"Unexpected rethrow outside @catch block.");
ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
}
CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
CGF.Builder.CreateUnreachable();
CGF.EmitBlock(llvm::BasicBlock::Create("bb"));
}
void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
llvm::BasicBlock *Dst,
bool ExecuteTryExit) {
llvm::BasicBlock *Src = Builder.GetInsertBlock();
if (isDummyBlock(Src))
return;
// Find the destination code for this block. We always use 0 for the
// fallthrough block (default destination).
llvm::SwitchInst *SI = E->FinallySwitch;
llvm::ConstantInt *ID;
if (Dst == SI->getDefaultDest()) {
ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
} else {
ID = SI->findCaseDest(Dst);
if (!ID) {
// No code found, get a new unique one by just using the number
// of switch successors.
ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
SI->addCase(ID, Dst);
}
}
// Set the destination code and branch.
Builder.CreateStore(ID, E->DestCode);
Builder.CreateBr(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
}
/* *** Private Interface *** */
/// EmitImageInfo - Emit the image info marker used to encode some module
/// level information.
///
/// See: <rdr://4810609&4810587&4810587>
/// struct IMAGE_INFO {
/// unsigned version;
/// unsigned flags;
/// };
enum ImageInfoFlags {
eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
eImageInfo_GarbageCollected = (1 << 1),
eImageInfo_GCOnly = (1 << 2)
};
void CGObjCMac::EmitImageInfo() {
unsigned version = 0; // Version is unused?
unsigned flags = 0;
// FIXME: Fix and continue?
if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
flags |= eImageInfo_GarbageCollected;
if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
flags |= eImageInfo_GCOnly;
// Emitted as int[2];
llvm::Constant *values[2] = {
llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
};
llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(AT, true,
llvm::GlobalValue::InternalLinkage,
llvm::ConstantArray::get(AT, values, 2),
"\01L_OBJC_IMAGE_INFO",
&CGM.getModule());
if (ObjCABI == 1) {
GV->setSection("__OBJC, __image_info,regular");
} else {
GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
}
UsedGlobals.push_back(GV);
}
// struct objc_module {
// unsigned long version;
// unsigned long size;
// const char *name;
// Symtab symtab;
// };
// FIXME: Get from somewhere
static const int ModuleVersion = 7;
void CGObjCMac::EmitModuleInfo() {
uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
std::vector<llvm::Constant*> Values(4);
Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
// This used to be the filename, now it is unused. <rdr://4327263>
Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Values[3] = EmitModuleSymbols();
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
llvm::GlobalValue::InternalLinkage,
llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
Values),
"\01L_OBJC_MODULES",
&CGM.getModule());
GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
UsedGlobals.push_back(GV);
}
llvm::Constant *CGObjCMac::EmitModuleSymbols() {
unsigned NumClasses = DefinedClasses.size();
unsigned NumCategories = DefinedCategories.size();
// Return null if no symbols were defined.
if (!NumClasses && !NumCategories)
return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
std::vector<llvm::Constant*> Values(5);
Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
// The runtime expects exactly the list of defined classes followed
// by the list of defined categories, in a single array.
std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
for (unsigned i=0; i<NumClasses; i++)
Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
ObjCTypes.Int8PtrTy);
for (unsigned i=0; i<NumCategories; i++)
Symbols[NumClasses + i] =
llvm::ConstantExpr::getBitCast(DefinedCategories[i],
ObjCTypes.Int8PtrTy);
Values[4] =
llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
NumClasses + NumCategories),
Symbols);
llvm::Constant *Init = llvm::ConstantStruct::get(Values);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(Init->getType(), false,
llvm::GlobalValue::InternalLinkage,
Init,
"\01L_OBJC_SYMBOLS",
&CGM.getModule());
GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
UsedGlobals.push_back(GV);
return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
}
llvm::Value *CGObjCMac::EmitClassRef(llvm::IRBuilder<> &Builder,
const ObjCInterfaceDecl *ID) {
LazySymbols.insert(ID->getIdentifier());
llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
if (!Entry) {
llvm::Constant *Casted =
llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
ObjCTypes.ClassPtrTy);
Entry =
new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
llvm::GlobalValue::InternalLinkage,
Casted, "\01L_OBJC_CLASS_REFERENCES_",
&CGM.getModule());
Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
UsedGlobals.push_back(Entry);
}
return Builder.CreateLoad(Entry, false, "tmp");
}
llvm::Value *CGObjCMac::EmitSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
if (!Entry) {
llvm::Constant *Casted =
llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
ObjCTypes.SelectorPtrTy);
Entry =
new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
llvm::GlobalValue::InternalLinkage,
Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
&CGM.getModule());
Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
UsedGlobals.push_back(Entry);
}
return Builder.CreateLoad(Entry, false, "tmp");
}
llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
llvm::GlobalVariable *&Entry = ClassNames[Ident];
if (!Entry) {
llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Entry =
new llvm::GlobalVariable(C->getType(), false,
llvm::GlobalValue::InternalLinkage,
C, "\01L_OBJC_CLASS_NAME_",
&CGM.getModule());
Entry->setSection("__TEXT,__cstring,cstring_literals");
UsedGlobals.push_back(Entry);
}
return getConstantGEP(Entry, 0, 0);
}
llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
if (!Entry) {
llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
Entry =
new llvm::GlobalVariable(C->getType(), false,
llvm::GlobalValue::InternalLinkage,
C, "\01L_OBJC_METH_VAR_NAME_",
&CGM.getModule());
Entry->setSection("__TEXT,__cstring,cstring_literals");
UsedGlobals.push_back(Entry);
}
return getConstantGEP(Entry, 0, 0);
}
// FIXME: Merge into a single cstring creation function.
llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
}
// FIXME: Merge into a single cstring creation function.
llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
return GetMethodVarName(&CGM.getContext().Idents.get(Name));
}
llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
if (!Entry) {
llvm::Constant *C = llvm::ConstantArray::get(Name);
Entry =
new llvm::GlobalVariable(C->getType(), false,
llvm::GlobalValue::InternalLinkage,
C, "\01L_OBJC_METH_VAR_TYPE_",
&CGM.getModule());
Entry->setSection("__TEXT,__cstring,cstring_literals");
UsedGlobals.push_back(Entry);
}
return getConstantGEP(Entry, 0, 0);
}
// FIXME: Merge into a single cstring creation function.
llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
std::string TypeStr;
CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
TypeStr);
return GetMethodVarType(TypeStr);
}
// FIXME: Merge into a single cstring creation function.
llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
llvm::GlobalVariable *&Entry = PropertyNames[Ident];
if (!Entry) {
llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Entry =
new llvm::GlobalVariable(C->getType(), false,
llvm::GlobalValue::InternalLinkage,
C, "\01L_OBJC_PROP_NAME_ATTR_",
&CGM.getModule());
Entry->setSection("__TEXT,__cstring,cstring_literals");
UsedGlobals.push_back(Entry);
}
return getConstantGEP(Entry, 0, 0);
}
// FIXME: Merge into a single cstring creation function.
// FIXME: This Decl should be more precise.
llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
const Decl *Container) {
std::string TypeStr;
CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
}
void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
std::string &NameOut) {
// FIXME: Find the mangling GCC uses.
std::stringstream s;
s << (D->isInstance() ? "-" : "+");
s << "[";
s << D->getClassInterface()->getName();
s << " ";
s << D->getSelector().getName();
s << "]";
NameOut = s.str();
}
void CGObjCMac::FinishModule() {
EmitModuleInfo();
std::vector<llvm::Constant*> Used;
for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
e = UsedGlobals.end(); i != e; ++i) {
Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
}
llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
llvm::GlobalValue *GV =
new llvm::GlobalVariable(AT, false,
llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(AT, Used),
"llvm.used",
&CGM.getModule());
GV->setSection("llvm.metadata");
// Add assembler directives to add lazy undefined symbol references
// for classes which are referenced but not defined. This is
// important for correct linker interaction.
// FIXME: Uh, this isn't particularly portable.
std::stringstream s;
for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
e = LazySymbols.end(); i != e; ++i) {
s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
}
for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
e = DefinedSymbols.end(); i != e; ++i) {
s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
<< "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
}
CGM.getModule().appendModuleInlineAsm(s.str());
}
/* *** */
ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
: CGM(cgm)
{
CodeGen::CodeGenTypes &Types = CGM.getTypes();
ASTContext &Ctx = CGM.getContext();
ShortTy = Types.ConvertType(Ctx.ShortTy);
IntTy = Types.ConvertType(Ctx.IntTy);
LongTy = Types.ConvertType(Ctx.LongTy);
Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
// FIXME: It would be nice to unify this with the opaque type, so
// that the IR comes out a bit cleaner.
const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
MethodDescriptionTy =
llvm::StructType::get(SelectorPtrTy,
Int8PtrTy,
NULL);
CGM.getModule().addTypeName("struct._objc_method_description",
MethodDescriptionTy);
MethodDescriptionListTy =
llvm::StructType::get(IntTy,
llvm::ArrayType::get(MethodDescriptionTy, 0),
NULL);
CGM.getModule().addTypeName("struct._objc_method_description_list",
MethodDescriptionListTy);
MethodDescriptionListPtrTy =
llvm::PointerType::getUnqual(MethodDescriptionListTy);
PropertyTy = llvm::StructType::get(Int8PtrTy,
Int8PtrTy,
NULL);
CGM.getModule().addTypeName("struct._objc_property",
PropertyTy);
PropertyListTy = llvm::StructType::get(IntTy,
IntTy,
llvm::ArrayType::get(PropertyTy, 0),
NULL);
CGM.getModule().addTypeName("struct._objc_property_list",
PropertyListTy);
PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
// Protocol description structures
ProtocolExtensionTy =
llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
llvm::PointerType::getUnqual(MethodDescriptionListTy),
llvm::PointerType::getUnqual(MethodDescriptionListTy),
PropertyListPtrTy,
NULL);
CGM.getModule().addTypeName("struct._objc_protocol_extension",
ProtocolExtensionTy);
ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
// Handle recursive construction of Protocl and ProtocolList types
llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
LongTy,
llvm::ArrayType::get(ProtocolTyHolder, 0),
NULL);
cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Int8PtrTy,
llvm::PointerType::getUnqual(ProtocolListTyHolder),
MethodDescriptionListPtrTy,
MethodDescriptionListPtrTy,
NULL);
cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
CGM.getModule().addTypeName("struct._objc_protocol_list",
ProtocolListTy);
ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
// Class description structures
IvarTy = llvm::StructType::get(Int8PtrTy,
Int8PtrTy,
IntTy,
NULL);
CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
IvarListTy = llvm::OpaqueType::get();
CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
MethodTy = llvm::StructType::get(SelectorPtrTy,
Int8PtrTy,
Int8PtrTy,
NULL);
CGM.getModule().addTypeName("struct._objc_method", MethodTy);
MethodListTy = llvm::OpaqueType::get();
CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
CacheTy = llvm::OpaqueType::get();
CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
ClassExtensionTy =
llvm::StructType::get(IntTy,
Int8PtrTy,
PropertyListPtrTy,
NULL);
CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
llvm::PointerType::getUnqual(ClassTyHolder),
Int8PtrTy,
LongTy,
LongTy,
LongTy,
IvarListPtrTy,
MethodListPtrTy,
CachePtrTy,
ProtocolListPtrTy,
Int8PtrTy,
ClassExtensionPtrTy,
NULL);
cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
CGM.getModule().addTypeName("struct._objc_class", ClassTy);
ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
CategoryTy = llvm::StructType::get(Int8PtrTy,
Int8PtrTy,
MethodListPtrTy,
MethodListPtrTy,
ProtocolListPtrTy,
IntTy,
PropertyListPtrTy,
NULL);
CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
// I'm not sure I like this. The implicit coordination is a bit
// gross. We should solve this in a reasonable fashion because this
// is a pretty common task (match some runtime data structure with
// an LLVM data structure).
// FIXME: This is leaked.
// FIXME: Merge with rewriter code?
RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
SourceLocation(),
&Ctx.Idents.get("_objc_super"));
FieldDecl *FieldDecls[2];
FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
Ctx.getObjCIdType());
FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
Ctx.getObjCClassType());
RD->defineBody(Ctx, FieldDecls, 2);
SuperCTy = Ctx.getTagDeclType(RD);
SuperPtrCTy = Ctx.getPointerType(SuperCTy);
SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
// Global metadata structures
SymtabTy = llvm::StructType::get(LongTy,
SelectorPtrTy,
ShortTy,
ShortTy,
llvm::ArrayType::get(Int8PtrTy, 0),
NULL);
CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
ModuleTy =
llvm::StructType::get(LongTy,
LongTy,
Int8PtrTy,
SymtabPtrTy,
NULL);
CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
// Message send functions.
std::vector<const llvm::Type*> Params;
Params.push_back(ObjectPtrTy);
Params.push_back(SelectorPtrTy);
MessageSendFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
Params,
true),
"objc_msgSend");
Params.clear();
Params.push_back(Int8PtrTy);
Params.push_back(ObjectPtrTy);
Params.push_back(SelectorPtrTy);
MessageSendStretFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
Params,
true),
"objc_msgSend_stret");
Params.clear();
Params.push_back(ObjectPtrTy);
Params.push_back(SelectorPtrTy);
// FIXME: This should be long double on x86_64?
MessageSendFpretFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
Params,
true),
"objc_msgSend_fpret");
Params.clear();
Params.push_back(SuperPtrTy);
Params.push_back(SelectorPtrTy);
MessageSendSuperFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
Params,
true),
"objc_msgSendSuper");
Params.clear();
Params.push_back(Int8PtrTy);
Params.push_back(SuperPtrTy);
Params.push_back(SelectorPtrTy);
MessageSendSuperStretFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
Params,
true),
"objc_msgSendSuper_stret");
// There is no objc_msgSendSuper_fpret? How can that work?
MessageSendSuperFpretFn = MessageSendSuperFn;
// Property manipulation functions.
Params.clear();
Params.push_back(ObjectPtrTy);
Params.push_back(SelectorPtrTy);
Params.push_back(LongTy);
Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
GetPropertyFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
Params,
false),
"objc_getProperty");
Params.clear();
Params.push_back(ObjectPtrTy);
Params.push_back(SelectorPtrTy);
Params.push_back(LongTy);
Params.push_back(ObjectPtrTy);
Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
SetPropertyFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
Params,
false),
"objc_setProperty");
// Enumeration mutation.
Params.clear();
Params.push_back(ObjectPtrTy);
EnumerationMutationFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
Params,
false),
"objc_enumerationMutation");
// FIXME: This is the size of the setjmp buffer and should be
// target specific. 18 is what's used on 32-bit X86.
uint64_t SetJmpBufferSize = 18;
// Exceptions
const llvm::Type *StackPtrTy =
llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
ExceptionDataTy =
llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
SetJmpBufferSize),
StackPtrTy, NULL);
CGM.getModule().addTypeName("struct._objc_exception_data",
ExceptionDataTy);
Params.clear();
Params.push_back(ObjectPtrTy);
ExceptionThrowFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
Params,
false),
"objc_exception_throw");
Params.clear();
Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
ExceptionTryEnterFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
Params,
false),
"objc_exception_try_enter");
ExceptionTryExitFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
Params,
false),
"objc_exception_try_exit");
ExceptionExtractFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
Params,
false),
"objc_exception_extract");
Params.clear();
Params.push_back(ClassPtrTy);
Params.push_back(ObjectPtrTy);
ExceptionMatchFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
Params,
false),
"objc_exception_match");
Params.clear();
Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
SetJmpFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
Params,
false),
"_setjmp");
}
ObjCTypesHelper::~ObjCTypesHelper() {
}
/* *** */
CodeGen::CGObjCRuntime *
CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
return new CGObjCMac(CGM);
}
|