blob: db1f6b16d786e9957d2d0073f0b507434ff341e6 [file] [log] [blame]
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbar1be1df32008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbar1be1df32008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar75de89f2009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar35b777f2008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000033
Daniel Dunbarfe131f02008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanian48543f52009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000042
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000043public:
Fariborz Jahanianad51ca02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +000046
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +000058
Daniel Dunbar0ed60b02008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +000063
Daniel Dunbar15245e52008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar87062ff2008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +000068
Fariborz Jahaniand0374812009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahanian781f2732009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattneraea1aee2009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +000088
Chris Lattneraea1aee2009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattneraea1aee2009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner293c1d32009-04-17 22:12:36 +000095 llvm::Constant *getGcAssignWeakFn() {
96 // id objc_assign_weak (id, id *)
97 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
98 Args.push_back(ObjectPtrTy->getPointerTo());
99 llvm::FunctionType *FTy =
100 llvm::FunctionType::get(ObjectPtrTy, Args, false);
101 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
102 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlsson1cf75362009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlsson1cf75362009-02-16 22:59:18 +0000115
Daniel Dunbar34416d62009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattner23e24652009-04-06 16:53:45 +0000117 llvm::Constant *getSyncEnterFn() {
118 // void objc_sync_enter (id)
119 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
120 llvm::FunctionType *FTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
122 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
123 }
Daniel Dunbar34416d62009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar34416d62009-02-24 01:43:46 +0000127
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbar15245e52008-08-23 04:28:29 +0000131
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000132/// ObjCTypesHelper - Helper class that encapsulates lazy
133/// construction of varies types used during ObjC generation.
134class ObjCTypesHelper : public ObjCCommonTypesHelper {
135private:
136
Chris Lattneraea1aee2009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000148
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000149 /// ProtocolTy - LLVM type for struct objc_protocol.
150 const llvm::StructType *ProtocolTy;
151 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
152 const llvm::Type *ProtocolPtrTy;
153 /// ProtocolExtensionTy - LLVM type for struct
154 /// objc_protocol_extension.
155 const llvm::StructType *ProtocolExtensionTy;
156 /// ProtocolExtensionTy - LLVM type for struct
157 /// objc_protocol_extension *.
158 const llvm::Type *ProtocolExtensionPtrTy;
159 /// MethodDescriptionTy - LLVM type for struct
160 /// objc_method_description.
161 const llvm::StructType *MethodDescriptionTy;
162 /// MethodDescriptionListTy - LLVM type for struct
163 /// objc_method_description_list.
164 const llvm::StructType *MethodDescriptionListTy;
165 /// MethodDescriptionListPtrTy - LLVM type for struct
166 /// objc_method_description_list *.
167 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000168 /// ProtocolListTy - LLVM type for struct objc_property_list.
169 const llvm::Type *ProtocolListTy;
170 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
171 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000174 /// ClassTy - LLVM type for struct objc_class.
175 const llvm::StructType *ClassTy;
176 /// ClassPtrTy - LLVM type for struct objc_class *.
177 const llvm::Type *ClassPtrTy;
178 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
179 const llvm::StructType *ClassExtensionTy;
180 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
181 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000182 // IvarTy - LLVM type for struct objc_ivar.
183 const llvm::StructType *IvarTy;
184 /// IvarListTy - LLVM type for struct objc_ivar_list.
185 const llvm::Type *IvarListTy;
186 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
187 const llvm::Type *IvarListPtrTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000188 /// MethodListTy - LLVM type for struct objc_method_list.
189 const llvm::Type *MethodListTy;
190 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
191 const llvm::Type *MethodListPtrTy;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattnerdd978702008-11-15 21:26:17 +0000210
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000214
215
Chris Lattneraea1aee2009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattneraea1aee2009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattneraea1aee2009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000227};
228
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000232public:
Chris Lattneraea1aee2009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000238 // MethodListnfABITy - LLVM for struct _method_list_t
239 const llvm::StructType *MethodListnfABITy;
240
241 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
242 const llvm::Type *MethodListnfABIPtrTy;
243
244 // ProtocolnfABITy = LLVM for struct _protocol_t
245 const llvm::StructType *ProtocolnfABITy;
246
Daniel Dunbar1f42bb02009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000250 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
251 const llvm::StructType *ProtocolListnfABITy;
252
253 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
254 const llvm::Type *ProtocolListnfABIPtrTy;
255
256 // ClassnfABITy - LLVM for struct _class_t
257 const llvm::StructType *ClassnfABITy;
258
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000262 // IvarnfABITy - LLVM for struct _ivar_t
263 const llvm::StructType *IvarnfABITy;
264
265 // IvarListnfABITy - LLVM for struct _ivar_list_t
266 const llvm::StructType *IvarListnfABITy;
267
268 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
269 const llvm::Type *IvarListnfABIPtrTy;
270
271 // ClassRonfABITy - LLVM for struct _class_ro_t
272 const llvm::StructType *ClassRonfABITy;
273
274 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
275 const llvm::Type *ImpnfABITy;
276
277 // CategorynfABITy - LLVM for struct _category_t
278 const llvm::StructType *CategorynfABITy;
279
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000280 // New types for nonfragile abi messaging.
281
282 // MessageRefTy - LLVM for:
283 // struct _message_ref_t {
284 // IMP messenger;
285 // SEL name;
286 // };
287 const llvm::StructType *MessageRefTy;
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000295
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000299 // SuperMessageRefTy - LLVM for:
300 // struct _super_message_ref_t {
301 // SUPER_IMP messenger;
302 // SEL name;
303 // };
304 const llvm::StructType *SuperMessageRefTy;
305
306 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
307 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattner23e24652009-04-06 16:53:45 +0000311 llvm::Value *getEHPersonalityPtr() {
312 llvm::Constant *Personality =
313 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
314 std::vector<const llvm::Type*>(),
315 true),
316 "__objc_personality_v0");
317 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
318 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000319
Chris Lattneraea1aee2009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000324
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahanian37931062009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +0000333 public:
Fariborz Jahanian37931062009-03-10 16:22:08 +0000334 unsigned int ivar_bytepos;
335 unsigned int ivar_size;
336 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
337 };
338
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000339 class SKIP_SCAN {
340 public:
341 unsigned int skip;
342 unsigned int scan;
343 SKIP_SCAN() : skip(0), scan(0) {}
344 };
345
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000350
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000351 // gc ivar layout bitmap calculation helper caches.
352 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
353 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
354 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian37931062009-03-10 16:22:08 +0000355
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000356 /// LazySymbols - Symbols to generate a lazy reference for. See
357 /// DefinedSymbols and FinishModule().
358 std::set<IdentifierInfo*> LazySymbols;
359
360 /// DefinedSymbols - External symbols which are defined by this
361 /// module. The symbols in this list and LazySymbols are used to add
362 /// special linker symbols which ensure that Objective-C modules are
363 /// linked properly.
364 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000365
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000368
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000371
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000372 /// MethodVarTypes - uniqued method type signatures. We have to use
373 /// a StringMap here because have no other unique reference.
374 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000375
Daniel Dunbar12996f52008-08-26 21:51:14 +0000376 /// MethodDefinitions - map of methods which have been defined in
377 /// this translation unit.
378 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000379
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000382
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000385
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000388
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000389 /// Protocols - Protocols for which an objc_protocol structure has
390 /// been emitted. Forward declarations are handled by creating an
391 /// empty structure whose initializer is filled in when/if defined.
392 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000393
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000394 /// DefinedProtocols - Protocols which have actually been
395 /// defined. We should not need this, see FIXME in GenerateProtocol.
396 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000397
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000400
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000403
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000407
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 const ObjCContainerDecl *CD,
412 std::string &NameOut);
413
414 /// GetMethodVarName - Return a unique constant for the given
415 /// selector's name. The return value has type char *.
416 llvm::Constant *GetMethodVarName(Selector Sel);
417 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
418 llvm::Constant *GetMethodVarName(const std::string &Name);
419
420 /// GetMethodVarType - Return a unique constant for the given
421 /// selector's name. The return value has type char *.
422
423 // FIXME: This is a horrible name.
424 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar356f0742009-04-20 06:54:31 +0000425 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +0000426
427 /// GetPropertyName - Return a unique constant for the given
428 /// name. The return value has type char *.
429 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
430
431 // FIXME: This can be dropped once string functions are unified.
432 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
433 const Decl *Container);
434
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000435 /// GetClassName - Return a unique constant for the given selector's
436 /// name. The return value has type char *.
437 llvm::Constant *GetClassName(IdentifierInfo *Ident);
438
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +0000439 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
440 /// interface declaration.
441 const llvm::StructLayout *GetInterfaceDeclStructLayout(
442 const ObjCInterfaceDecl *ID) const;
443
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000449
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000456
Fariborz Jahanian7345eba2009-03-05 19:17:31 +0000457 /// GetIvarLayoutName - Returns a unique constant for the given
458 /// ivar layout bitmap.
459 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
460 const ObjCCommonTypesHelper &ObjCTypes);
461
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +0000462 /// EmitPropertyList - Emit the given property list. The return
463 /// value has type PropertyListPtrTy.
464 llvm::Constant *EmitPropertyList(const std::string &Name,
465 const Decl *Container,
466 const ObjCContainerDecl *OCD,
467 const ObjCCommonTypesHelper &ObjCTypes);
468
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000469 /// GetProtocolRef - Return a reference to the internal protocol
470 /// description, creating an empty one if it has not been
471 /// defined. The return value has type ProtocolPtrTy.
472 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +0000473
474 /// GetIvarBaseOffset - returns ivars byte offset.
475 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +0000476 const FieldDecl *Field);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000477
Chris Lattnerd391dab2009-03-31 08:33:16 +0000478 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000479 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
480 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +0000481 const FieldDecl *Field);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000482
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000483 /// CreateMetadataVar - Create a global variable with internal
484 /// linkage for use by the Objective-C runtime.
485 ///
486 /// This is a convenience wrapper which not only creates the
487 /// variable, but also sets the section and alignment and adds the
488 /// global to the UsedGlobals list.
Daniel Dunbareddddd22009-03-09 20:50:13 +0000489 ///
490 /// \param Name - The variable name.
491 /// \param Init - The variable initializer; this is also used to
492 /// define the type of the variable.
493 /// \param Section - The section the variable should go into, or 0.
494 /// \param Align - The alignment for the variable, or 0.
495 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbar6b343692009-04-14 17:42:51 +0000496 /// "llvm.used".
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000497 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
498 llvm::Constant *Init,
499 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +0000500 unsigned Align,
501 bool AddToUsed);
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000502
Daniel Dunbar356f0742009-04-20 06:54:31 +0000503 /// GetNamedIvarList - Return the list of ivars in the interface
504 /// itself (not including super classes and not including unnamed
505 /// bitfields).
506 ///
507 /// For the non-fragile ABI, this also includes synthesized property
508 /// ivars.
509 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
510 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
511
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000512public:
513 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
514 { }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000515
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000516 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000517
518 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
519 const ObjCContainerDecl *CD=0);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000520
521 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
522
523 /// GetOrEmitProtocol - Get the protocol object for the given
524 /// declaration, emitting it if necessary. The return value has type
525 /// ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
527
528 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
529 /// object for the given declaration, emitting it if needed. These
530 /// forward references will be filled in with empty bodies if no
531 /// definition is seen. The return value has type ProtocolPtrTy.
532 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000533};
534
535class CGObjCMac : public CGObjCCommonMac {
536private:
537 ObjCTypesHelper ObjCTypes;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000538 /// EmitImageInfo - Emit the image info marker used to encode some module
539 /// level information.
540 void EmitImageInfo();
541
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000542 /// EmitModuleInfo - Another marker encoding module level
543 /// information.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000544 void EmitModuleInfo();
545
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000546 /// EmitModuleSymols - Emit module symbols, the list of defined
547 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000548 llvm::Constant *EmitModuleSymbols();
549
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000550 /// FinishModule - Write out global data structures at the end of
551 /// processing a translation unit.
552 void FinishModule();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000553
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000554 /// EmitClassExtension - Generate the class extension structure used
555 /// to store the weak ivar layout and properties. The return value
556 /// has type ClassExtensionPtrTy.
557 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
558
559 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
560 /// for the given class.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000561 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000562 const ObjCInterfaceDecl *ID);
563
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000564 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000565 QualType ResultType,
566 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000567 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000568 QualType Arg0Ty,
569 bool IsSuper,
570 const CallArgList &CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000571
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000572 /// EmitIvarList - Emit the ivar list for the given
573 /// implementation. If ForClass is true the list of class ivars
574 /// (i.e. metaclass ivars) is emitted, otherwise the list of
575 /// interface ivars will be emitted. The return value has type
576 /// IvarListPtrTy.
577 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +0000578 bool ForClass);
579
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000580 /// EmitMetaClass - Emit a forward reference to the class structure
581 /// for the metaclass of the given interface. The return value has
582 /// type ClassPtrTy.
583 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
584
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000585 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000586 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000587 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
588 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +0000589 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000590 const ConstantVector &Methods);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000591
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000592 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000593
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000594 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000595
596 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000597 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000598 llvm::Constant *EmitMethodList(const std::string &Name,
599 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000600 const ConstantVector &Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000601
602 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000603 /// method declarations.
604 /// - TypeName: The name for the type containing the methods.
605 /// - IsProtocol: True iff these methods are for a protocol.
606 /// - ClassMethds: True iff these are class methods.
607 /// - Required: When true, only "required" methods are
608 /// listed. Similarly, when false only "optional" methods are
609 /// listed. For classes this should always be true.
610 /// - begin, end: The method list to output.
611 ///
612 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000613 llvm::Constant *EmitMethodDescList(const std::string &Name,
614 const char *Section,
615 const ConstantVector &Methods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000616
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000617 /// GetOrEmitProtocol - Get the protocol object for the given
618 /// declaration, emitting it if necessary. The return value has type
619 /// ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000621
622 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
623 /// object for the given declaration, emitting it if needed. These
624 /// forward references will be filled in with empty bodies if no
625 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000626 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000627
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000628 /// EmitProtocolExtension - Generate the protocol extension
629 /// structure used to store optional instance and class methods, and
630 /// protocol properties. The return value has type
631 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000632 llvm::Constant *
633 EmitProtocolExtension(const ObjCProtocolDecl *PD,
634 const ConstantVector &OptInstanceMethods,
635 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000636
637 /// EmitProtocolList - Generate the list of referenced
638 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000639 llvm::Constant *EmitProtocolList(const std::string &Name,
640 ObjCProtocolDecl::protocol_iterator begin,
641 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000642
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000643 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
644 /// for the given selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000645 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000646
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000647 public:
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000648 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000649
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000650 virtual llvm::Function *ModuleInitFunction();
651
Daniel Dunbara04840b2008-08-23 03:46:30 +0000652 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000653 QualType ResultType,
654 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000655 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000656 bool IsClassMessage,
657 const CallArgList &CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000658
Daniel Dunbara04840b2008-08-23 03:46:30 +0000659 virtual CodeGen::RValue
660 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000661 QualType ResultType,
662 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000663 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000664 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000665 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000666 bool IsClassMessage,
667 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +0000668
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000669 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000670 const ObjCInterfaceDecl *ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000671
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000672 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000673
Daniel Dunbarac93e472008-08-15 22:20:32 +0000674 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000675
Daniel Dunbarac93e472008-08-15 22:20:32 +0000676 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000677
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000678 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000679 const ObjCProtocolDecl *PD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000680
Chris Lattneraea1aee2009-03-22 21:03:39 +0000681 virtual llvm::Constant *GetPropertyGetFunction();
682 virtual llvm::Constant *GetPropertySetFunction();
683 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +0000684
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +0000685 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
686 const Stmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +0000687 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
688 const ObjCAtThrowStmt &S);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000689 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +0000690 llvm::Value *AddrWeakObj);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000691 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000693 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
694 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianf310b592008-11-20 19:23:36 +0000695 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
696 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000697 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
698 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian4337afe2009-02-02 20:02:29 +0000699
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000700 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
701 QualType ObjectTy,
702 llvm::Value *BaseValue,
703 const ObjCIvarDecl *Ivar,
704 const FieldDecl *Field,
705 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000706 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
707 ObjCInterfaceDecl *Interface,
708 const ObjCIvarDecl *Ivar);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000709};
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000710
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000711class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000712private:
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000713 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000714 llvm::GlobalVariable* ObjCEmptyCacheVar;
715 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000716
Daniel Dunbar3c190812009-04-18 08:51:00 +0000717 /// SuperClassReferences - uniqued super class references.
718 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
719
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000720 /// MetaClassReferences - uniqued meta class references.
721 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000722
723 /// EHTypeReferences - uniqued class ehtype references.
724 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000725
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000726 /// FinishNonFragileABIModule - Write out global data structures at the end of
727 /// processing a translation unit.
728 void FinishNonFragileABIModule();
Daniel Dunbarc2129532009-04-08 04:21:03 +0000729
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000730 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
731 unsigned InstanceStart,
732 unsigned InstanceSize,
733 const ObjCImplementationDecl *ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +0000734 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
735 llvm::Constant *IsAGV,
736 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +0000737 llvm::Constant *ClassRoGV,
738 bool HiddenVisibility);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000739
740 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
741
Fariborz Jahanian151747b2009-01-30 00:46:37 +0000742 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
743
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000744 /// EmitMethodList - Emit the method list for the given
745 /// implementation. The return value has type MethodListnfABITy.
746 llvm::Constant *EmitMethodList(const std::string &Name,
747 const char *Section,
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +0000748 const ConstantVector &Methods);
749 /// EmitIvarList - Emit the ivar list for the given
750 /// implementation. If ForClass is true the list of class ivars
751 /// (i.e. metaclass ivars) is emitted, otherwise the list of
752 /// interface ivars will be emitted. The return value has type
753 /// IvarListnfABIPtrTy.
754 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000755
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000756 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +0000757 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +0000758 unsigned long int offset);
759
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000760 /// GetOrEmitProtocol - Get the protocol object for the given
761 /// declaration, emitting it if necessary. The return value has type
762 /// ProtocolPtrTy.
763 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
764
765 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
766 /// object for the given declaration, emitting it if needed. These
767 /// forward references will be filled in with empty bodies if no
768 /// definition is seen. The return value has type ProtocolPtrTy.
769 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
770
771 /// EmitProtocolList - Generate the list of referenced
772 /// protocols. The return value has type ProtocolListPtrTy.
773 llvm::Constant *EmitProtocolList(const std::string &Name,
774 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000775 ObjCProtocolDecl::protocol_iterator end);
776
777 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
778 QualType ResultType,
779 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000780 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000781 QualType Arg0Ty,
782 bool IsSuper,
783 const CallArgList &CallArgs);
Daniel Dunbarabbda222009-03-01 04:40:10 +0000784
785 /// GetClassGlobal - Return the global variable for the Objective-C
786 /// class of the given name.
Fariborz Jahanianab438842009-04-14 18:41:56 +0000787 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
788
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000789 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar3c190812009-04-18 08:51:00 +0000790 /// for the given class reference.
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000791 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +0000792 const ObjCInterfaceDecl *ID);
793
794 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
795 /// for the given super class reference.
796 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
797 const ObjCInterfaceDecl *ID);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000798
799 /// EmitMetaClassRef - Return a Value * of the address of _class_t
800 /// meta-data
801 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
802 const ObjCInterfaceDecl *ID);
803
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000804 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
805 /// the given ivar.
806 ///
Daniel Dunbar07d204a2009-04-19 00:31:15 +0000807 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +0000808 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000809 const ObjCIvarDecl *Ivar);
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000810
Fariborz Jahanianebb82c62009-02-11 20:51:17 +0000811 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
812 /// for the given selector.
813 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000814
Daniel Dunbarc2129532009-04-08 04:21:03 +0000815 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000816 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbarc2129532009-04-08 04:21:03 +0000817 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
818 bool ForDefinition);
Daniel Dunbara2d275d2009-04-07 05:48:37 +0000819
820 const char *getMetaclassSymbolPrefix() const {
821 return "OBJC_METACLASS_$_";
822 }
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000823
Daniel Dunbara2d275d2009-04-07 05:48:37 +0000824 const char *getClassSymbolPrefix() const {
825 return "OBJC_CLASS_$_";
826 }
827
Daniel Dunbarecb5d402009-04-19 23:41:48 +0000828 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
829 uint32_t &InstanceStart,
830 uint32_t &InstanceSize);
831
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000832public:
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000833 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000834 // FIXME. All stubs for now!
835 virtual llvm::Function *ModuleInitFunction();
836
837 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
838 QualType ResultType,
839 Selector Sel,
840 llvm::Value *Receiver,
841 bool IsClassMessage,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000842 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000843
844 virtual CodeGen::RValue
845 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
846 QualType ResultType,
847 Selector Sel,
848 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000849 bool isCategoryImpl,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000850 llvm::Value *Receiver,
851 bool IsClassMessage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000852 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000853
854 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000855 const ObjCInterfaceDecl *ID);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000856
857 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanianebb82c62009-02-11 20:51:17 +0000858 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000859
Fariborz Jahanianfe49a092009-01-26 18:32:24 +0000860 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000861
862 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000863 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +0000864 const ObjCProtocolDecl *PD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000865
Chris Lattneraea1aee2009-03-22 21:03:39 +0000866 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000867 return ObjCTypes.GetPropertyFn;
868 }
Chris Lattneraea1aee2009-03-22 21:03:39 +0000869 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000870 return ObjCTypes.SetPropertyFn;
871 }
Chris Lattneraea1aee2009-03-22 21:03:39 +0000872 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar978d2be2009-02-16 18:48:45 +0000873 return ObjCTypes.EnumerationMutationFn;
874 }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000875
876 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000877 const Stmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000878 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlsson1cf75362009-02-16 22:59:18 +0000879 const ObjCAtThrowStmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000880 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000881 llvm::Value *AddrWeakObj);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000882 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000883 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000884 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000885 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000886 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000887 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000888 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000889 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000890 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
891 QualType ObjectTy,
892 llvm::Value *BaseValue,
893 const ObjCIvarDecl *Ivar,
894 const FieldDecl *Field,
895 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000896 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
897 ObjCInterfaceDecl *Interface,
898 const ObjCIvarDecl *Ivar);
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000899};
900
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000901} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000902
903/* *** Helper Functions *** */
904
905/// getConstantGEP() - Help routine to construct simple GEPs.
906static llvm::Constant *getConstantGEP(llvm::Constant *C,
907 unsigned idx0,
908 unsigned idx1) {
909 llvm::Value *Idxs[] = {
910 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
911 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
912 };
913 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
914}
915
Daniel Dunbarc2129532009-04-08 04:21:03 +0000916/// hasObjCExceptionAttribute - Return true if this class or any super
917/// class has the __objc_exception__ attribute.
918static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbar78582862009-04-13 21:08:27 +0000919 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbarc2129532009-04-08 04:21:03 +0000920 return true;
921 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
922 return hasObjCExceptionAttribute(Super);
923 return false;
924}
925
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000926/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000927
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000928CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
929 ObjCTypes(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000930{
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000931 ObjCABI = 1;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000932 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000933}
934
Daniel Dunbar434627a2008-08-16 00:25:02 +0000935/// GetClass - Return a reference to the class for the given interface
936/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000937llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000938 const ObjCInterfaceDecl *ID) {
939 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000940}
941
942/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000943llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000944 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000945}
946
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000947/// Generate a constant CFString object.
948/*
949 struct __builtin_CFString {
950 const int *isa; // point to __CFConstantStringClassReference
951 int flags;
952 const char *str;
953 long length;
954 };
955*/
956
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000957llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000958 const ObjCStringLiteral *SL) {
Steve Naroff9a744e52009-04-01 13:55:36 +0000959 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000960}
961
962/// Generates a message send where the super is the receiver. This is
963/// a message send to self with special delivery semantics indicating
964/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000965CodeGen::RValue
966CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000967 QualType ResultType,
968 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000969 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000970 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000971 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000972 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000973 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +0000974 // Create and init a super structure; this is a (receiver, class)
975 // pair we will pass to objc_msgSendSuper.
976 llvm::Value *ObjCSuper =
977 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
978 llvm::Value *ReceiverAsObject =
979 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
980 CGF.Builder.CreateStore(ReceiverAsObject,
981 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +0000982
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000983 // If this is a class message the metaclass is passed as the target.
984 llvm::Value *Target;
985 if (IsClassMessage) {
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000986 if (isCategoryImpl) {
987 // Message sent to 'super' in a class method defined in a category
988 // implementation requires an odd treatment.
989 // If we are in a class method, we must retrieve the
990 // _metaclass_ for the current class, pointed at by
991 // the class's "isa" pointer. The following assumes that
992 // isa" is the first ivar in a class (which it must be).
993 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
994 Target = CGF.Builder.CreateStructGEP(Target, 0);
995 Target = CGF.Builder.CreateLoad(Target);
996 }
997 else {
998 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
999 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1000 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1001 Target = Super;
1002 }
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001003 } else {
1004 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1005 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001006 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1007 // and ObjCTypes types.
1008 const llvm::Type *ClassTy =
1009 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001010 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001011 CGF.Builder.CreateStore(Target,
1012 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1013
Daniel Dunbardd851282008-08-30 05:35:15 +00001014 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001015 ObjCSuper, ObjCTypes.SuperPtrCTy,
1016 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001017}
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001018
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001019/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001020CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001021 QualType ResultType,
1022 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001023 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001024 bool IsClassMessage,
1025 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001026 llvm::Value *Arg0 =
1027 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +00001028 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001029 Arg0, CGF.getContext().getObjCIdType(),
1030 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001031}
1032
1033CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001034 QualType ResultType,
1035 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001036 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001037 QualType Arg0Ty,
1038 bool IsSuper,
1039 const CallArgList &CallArgs) {
1040 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001041 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1042 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1043 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001044 CGF.getContext().getObjCSelType()));
1045 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +00001046
Daniel Dunbar34bda882009-02-02 23:23:47 +00001047 CodeGenTypes &Types = CGM.getTypes();
1048 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1049 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001050
1051 llvm::Constant *Fn;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001052 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001053 Fn = ObjCTypes.getSendStretFn(IsSuper);
1054 } else if (ResultType->isFloatingType()) {
1055 // FIXME: Sadly, this is wrong. This actually depends on the
1056 // architecture. This happens to be right for x86-32 though.
1057 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1058 } else {
1059 Fn = ObjCTypes.getSendFn(IsSuper);
1060 }
Daniel Dunbara9976a22008-09-10 07:00:50 +00001061 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001062 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001063}
1064
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001065llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001066 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +00001067 // FIXME: I don't understand why gcc generates this, or where it is
1068 // resolved. Investigate. Its also wasteful to look this up over and
1069 // over.
1070 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1071
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001072 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1073 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001074}
1075
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001076void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001077 // FIXME: We shouldn't need this, the protocol decl should contain
1078 // enough information to tell us whether this was a declaration or a
1079 // definition.
1080 DefinedProtocols.insert(PD->getIdentifier());
1081
1082 // If we have generated a forward reference to this protocol, emit
1083 // it now. Otherwise do nothing, the protocol objects are lazily
1084 // emitted.
1085 if (Protocols.count(PD->getIdentifier()))
1086 GetOrEmitProtocol(PD);
1087}
1088
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001089llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001090 if (DefinedProtocols.count(PD->getIdentifier()))
1091 return GetOrEmitProtocol(PD);
1092 return GetOrEmitProtocolRef(PD);
1093}
1094
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001095/*
1096 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1097 struct _objc_protocol {
1098 struct _objc_protocol_extension *isa;
1099 char *protocol_name;
1100 struct _objc_protocol_list *protocol_list;
1101 struct _objc__method_prototype_list *instance_methods;
1102 struct _objc__method_prototype_list *class_methods
1103 };
1104
1105 See EmitProtocolExtension().
1106*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001107llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1108 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1109
1110 // Early exit if a defining object has already been generated.
1111 if (Entry && Entry->hasInitializer())
1112 return Entry;
1113
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001114 // FIXME: I don't understand why gcc generates this, or where it is
1115 // resolved. Investigate. Its also wasteful to look this up over and
1116 // over.
1117 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1118
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001119 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001120
1121 // Construct method lists.
1122 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1123 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001124 for (ObjCProtocolDecl::instmeth_iterator
1125 i = PD->instmeth_begin(CGM.getContext()),
1126 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001127 ObjCMethodDecl *MD = *i;
1128 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1129 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1130 OptInstanceMethods.push_back(C);
1131 } else {
1132 InstanceMethods.push_back(C);
1133 }
1134 }
1135
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001136 for (ObjCProtocolDecl::classmeth_iterator
1137 i = PD->classmeth_begin(CGM.getContext()),
1138 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001139 ObjCMethodDecl *MD = *i;
1140 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1141 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1142 OptClassMethods.push_back(C);
1143 } else {
1144 ClassMethods.push_back(C);
1145 }
1146 }
1147
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001148 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001149 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001150 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001151 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001152 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001153 PD->protocol_begin(),
1154 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001155 Values[3] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001156 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1157 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001158 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1159 InstanceMethods);
1160 Values[4] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001161 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1162 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001163 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1164 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001165 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1166 Values);
1167
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001168 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001169 // Already created, fix the linkage and update the initializer.
1170 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001171 Entry->setInitializer(Init);
1172 } else {
1173 Entry =
1174 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1175 llvm::GlobalValue::InternalLinkage,
1176 Init,
1177 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1178 &CGM.getModule());
1179 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001180 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001181 UsedGlobals.push_back(Entry);
1182 // FIXME: Is this necessary? Why only for protocol?
1183 Entry->setAlignment(4);
1184 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001185
1186 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001187}
1188
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001189llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001190 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1191
1192 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001193 // We use the initializer as a marker of whether this is a forward
1194 // reference or not. At module finalization we add the empty
1195 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001196 Entry =
1197 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001198 llvm::GlobalValue::ExternalLinkage,
1199 0,
Chris Lattner271d4c22008-11-24 05:29:24 +00001200 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001201 &CGM.getModule());
1202 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001203 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001204 UsedGlobals.push_back(Entry);
1205 // FIXME: Is this necessary? Why only for protocol?
1206 Entry->setAlignment(4);
1207 }
1208
1209 return Entry;
1210}
1211
1212/*
1213 struct _objc_protocol_extension {
1214 uint32_t size;
1215 struct objc_method_description_list *optional_instance_methods;
1216 struct objc_method_description_list *optional_class_methods;
1217 struct objc_property_list *instance_properties;
1218 };
1219*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001220llvm::Constant *
1221CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1222 const ConstantVector &OptInstanceMethods,
1223 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001224 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001225 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001226 std::vector<llvm::Constant*> Values(4);
1227 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001228 Values[1] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001229 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1230 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001231 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1232 OptInstanceMethods);
1233 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001234 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1235 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001236 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1237 OptClassMethods);
Chris Lattner271d4c22008-11-24 05:29:24 +00001238 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1239 PD->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001240 0, PD, ObjCTypes);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001241
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001242 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001243 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1244 Values[3]->isNullValue())
1245 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1246
1247 llvm::Constant *Init =
1248 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001249
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001250 // No special section, but goes in llvm.used
1251 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1252 Init,
1253 0, 0, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001254}
1255
1256/*
1257 struct objc_protocol_list {
1258 struct objc_protocol_list *next;
1259 long count;
1260 Protocol *list[];
1261 };
1262*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001263llvm::Constant *
1264CGObjCMac::EmitProtocolList(const std::string &Name,
1265 ObjCProtocolDecl::protocol_iterator begin,
1266 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001267 std::vector<llvm::Constant*> ProtocolRefs;
1268
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001269 for (; begin != end; ++begin)
1270 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001271
1272 // Just return null for empty protocol lists
1273 if (ProtocolRefs.empty())
1274 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1275
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001276 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001277 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1278
1279 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001280 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001281 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1282 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1283 Values[2] =
1284 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1285 ProtocolRefs.size()),
1286 ProtocolRefs);
1287
1288 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1289 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001290 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001291 4, false);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001292 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1293}
1294
1295/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001296 struct _objc_property {
1297 const char * const name;
1298 const char * const attributes;
1299 };
1300
1301 struct _objc_property_list {
1302 uint32_t entsize; // sizeof (struct _objc_property)
1303 uint32_t prop_count;
1304 struct _objc_property[prop_count];
1305 };
1306*/
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001307llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1308 const Decl *Container,
1309 const ObjCContainerDecl *OCD,
1310 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001311 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001312 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1313 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroffdcf1e842009-01-11 12:47:58 +00001314 const ObjCPropertyDecl *PD = *I;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001315 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001316 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001317 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1318 Prop));
1319 }
1320
1321 // Return null for empty list.
1322 if (Properties.empty())
1323 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1324
1325 unsigned PropertySize =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001326 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001327 std::vector<llvm::Constant*> Values(3);
1328 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1329 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1330 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1331 Properties.size());
1332 Values[2] = llvm::ConstantArray::get(AT, Properties);
1333 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1334
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001335 llvm::GlobalVariable *GV =
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001336 CreateMetadataVar(Name, Init,
1337 (ObjCABI == 2) ? "__DATA, __objc_const" :
1338 "__OBJC,__property,regular,no_dead_strip",
1339 (ObjCABI == 2) ? 8 : 4,
1340 true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001341 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001342}
1343
1344/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001345 struct objc_method_description_list {
1346 int count;
1347 struct objc_method_description list[];
1348 };
1349*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001350llvm::Constant *
1351CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1352 std::vector<llvm::Constant*> Desc(2);
1353 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1354 ObjCTypes.SelectorPtrTy);
1355 Desc[1] = GetMethodVarType(MD);
1356 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1357 Desc);
1358}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001359
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001360llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1361 const char *Section,
1362 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001363 // Return null for empty list.
1364 if (Methods.empty())
1365 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1366
1367 std::vector<llvm::Constant*> Values(2);
1368 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1369 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1370 Methods.size());
1371 Values[1] = llvm::ConstantArray::get(AT, Methods);
1372 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1373
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001374 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001375 return llvm::ConstantExpr::getBitCast(GV,
1376 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001377}
1378
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001379/*
1380 struct _objc_category {
1381 char *category_name;
1382 char *class_name;
1383 struct _objc_method_list *instance_methods;
1384 struct _objc_method_list *class_methods;
1385 struct _objc_protocol_list *protocols;
1386 uint32_t size; // <rdar://4585769>
1387 struct _objc_property_list *instance_properties;
1388 };
1389 */
Daniel Dunbarac93e472008-08-15 22:20:32 +00001390void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbard8439f22009-01-12 21:08:18 +00001391 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001392
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001393 // FIXME: This is poor design, the OCD should have a pointer to the
1394 // category decl. Additionally, note that Category can be null for
1395 // the @implementation w/o an @interface case. Sema should just
1396 // create one for us as it does for @implementation so everyone else
1397 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001398 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001399 const ObjCCategoryDecl *Category =
1400 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattner271d4c22008-11-24 05:29:24 +00001401 std::string ExtName(Interface->getNameAsString() + "_" +
1402 OCD->getNameAsString());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001403
Daniel Dunbar12996f52008-08-26 21:51:14 +00001404 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1405 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1406 e = OCD->instmeth_end(); i != e; ++i) {
1407 // Instance methods should always be defined.
1408 InstanceMethods.push_back(GetMethodConstant(*i));
1409 }
1410 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1411 e = OCD->classmeth_end(); i != e; ++i) {
1412 // Class methods should always be defined.
1413 ClassMethods.push_back(GetMethodConstant(*i));
1414 }
1415
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001416 std::vector<llvm::Constant*> Values(7);
1417 Values[0] = GetClassName(OCD->getIdentifier());
1418 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001419 Values[2] =
1420 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1421 ExtName,
1422 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001423 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001424 Values[3] =
1425 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001426 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001427 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001428 if (Category) {
1429 Values[4] =
1430 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1431 Category->protocol_begin(),
1432 Category->protocol_end());
1433 } else {
1434 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1435 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001436 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001437
1438 // If there is no category @interface then there can be no properties.
1439 if (Category) {
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001440 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001441 OCD, Category, ObjCTypes);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001442 } else {
1443 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1444 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001445
1446 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1447 Values);
1448
1449 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001450 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1451 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001452 4, true);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001453 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001454}
1455
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001456// FIXME: Get from somewhere?
1457enum ClassFlags {
1458 eClassFlags_Factory = 0x00001,
1459 eClassFlags_Meta = 0x00002,
1460 // <rdr://5142207>
1461 eClassFlags_HasCXXStructors = 0x02000,
1462 eClassFlags_Hidden = 0x20000,
1463 eClassFlags_ABI2_Hidden = 0x00010,
1464 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1465};
1466
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001467/*
1468 struct _objc_class {
1469 Class isa;
1470 Class super_class;
1471 const char *name;
1472 long version;
1473 long info;
1474 long instance_size;
1475 struct _objc_ivar_list *ivars;
1476 struct _objc_method_list *methods;
1477 struct _objc_cache *cache;
1478 struct _objc_protocol_list *protocols;
1479 // Objective-C 1.0 extensions (<rdr://4585769>)
1480 const char *ivar_layout;
1481 struct _objc_class_ext *ext;
1482 };
1483
1484 See EmitClassExtension();
1485 */
1486void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001487 DefinedSymbols.insert(ID->getIdentifier());
1488
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001489 std::string ClassName = ID->getNameAsString();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001490 // FIXME: Gross
1491 ObjCInterfaceDecl *Interface =
1492 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001493 llvm::Constant *Protocols =
Chris Lattner271d4c22008-11-24 05:29:24 +00001494 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001495 Interface->protocol_begin(),
1496 Interface->protocol_end());
Chris Lattner9fe470d2009-04-19 06:02:28 +00001497 const llvm::Type *InterfaceTy;
1498 if (Interface->isForwardDecl())
1499 InterfaceTy = llvm::StructType::get(NULL, NULL);
1500 else
1501 InterfaceTy =
Chris Lattner46ee0f32009-04-01 06:23:52 +00001502 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001503 unsigned Flags = eClassFlags_Factory;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001504 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001505
1506 // FIXME: Set CXX-structors flag.
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001507 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001508 Flags |= eClassFlags_Hidden;
1509
Daniel Dunbar12996f52008-08-26 21:51:14 +00001510 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1511 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1512 e = ID->instmeth_end(); i != e; ++i) {
1513 // Instance methods should always be defined.
1514 InstanceMethods.push_back(GetMethodConstant(*i));
1515 }
1516 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1517 e = ID->classmeth_end(); i != e; ++i) {
1518 // Class methods should always be defined.
1519 ClassMethods.push_back(GetMethodConstant(*i));
1520 }
1521
1522 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1523 e = ID->propimpl_end(); i != e; ++i) {
1524 ObjCPropertyImplDecl *PID = *i;
1525
1526 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1527 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1528
1529 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1530 if (llvm::Constant *C = GetMethodConstant(MD))
1531 InstanceMethods.push_back(C);
1532 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1533 if (llvm::Constant *C = GetMethodConstant(MD))
1534 InstanceMethods.push_back(C);
1535 }
1536 }
1537
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001538 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001539 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001540 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001541 // Record a reference to the super class.
1542 LazySymbols.insert(Super->getIdentifier());
1543
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001544 Values[ 1] =
1545 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1546 ObjCTypes.ClassPtrTy);
1547 } else {
1548 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1549 }
1550 Values[ 2] = GetClassName(ID->getIdentifier());
1551 // Version is always 0.
1552 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1553 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1554 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001555 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001556 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001557 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001558 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001559 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001560 // cache is always NULL.
1561 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1562 Values[ 9] = Protocols;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001563 // FIXME: Set ivar_layout
Fariborz Jahanian738ee712009-03-25 22:36:49 +00001564 // Values[10] = BuildIvarLayout(ID, true);
1565 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001566 Values[11] = EmitClassExtension(ID);
1567 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1568 Values);
1569
1570 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001571 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1572 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001573 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001574 DefinedClasses.push_back(GV);
1575}
1576
1577llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1578 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001579 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001580 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001581 unsigned Flags = eClassFlags_Meta;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001582 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001583
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001584 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001585 Flags |= eClassFlags_Hidden;
1586
1587 std::vector<llvm::Constant*> Values(12);
1588 // The isa for the metaclass is the root of the hierarchy.
1589 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1590 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1591 Root = Super;
1592 Values[ 0] =
1593 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1594 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001595 // The super class for the metaclass is emitted as the name of the
1596 // super class. The runtime fixes this up to point to the
1597 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001598 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1599 Values[ 1] =
1600 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1601 ObjCTypes.ClassPtrTy);
1602 } else {
1603 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1604 }
1605 Values[ 2] = GetClassName(ID->getIdentifier());
1606 // Version is always 0.
1607 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1608 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1609 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001610 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001611 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001612 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001613 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001614 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001615 // cache is always NULL.
1616 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1617 Values[ 9] = Protocols;
1618 // ivar_layout for metaclass is always NULL.
1619 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1620 // The class extension is always unused for metaclasses.
1621 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1622 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1623 Values);
1624
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001625 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001626 Name += ID->getNameAsCString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001627
1628 // Check for a forward reference.
1629 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1630 if (GV) {
1631 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1632 "Forward metaclass reference has incorrect type.");
1633 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1634 GV->setInitializer(Init);
1635 } else {
1636 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1637 llvm::GlobalValue::InternalLinkage,
1638 Init, Name,
1639 &CGM.getModule());
1640 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001641 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001642 GV->setAlignment(4);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001643 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001644
1645 return GV;
1646}
1647
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001648llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattner271d4c22008-11-24 05:29:24 +00001649 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001650
1651 // FIXME: Should we look these up somewhere other than the
1652 // module. Its a bit silly since we only generate these while
1653 // processing an implementation, so exactly one pointer would work
1654 // if know when we entered/exitted an implementation block.
1655
1656 // Check for an existing forward reference.
Fariborz Jahanian5fe09f72009-01-07 20:11:22 +00001657 // Previously, metaclass with internal linkage may have been defined.
1658 // pass 'true' as 2nd argument so it is returned.
1659 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001660 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1661 "Forward metaclass reference has incorrect type.");
1662 return GV;
1663 } else {
1664 // Generate as an external reference to keep a consistent
1665 // module. This will be patched up when we emit the metaclass.
1666 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1667 llvm::GlobalValue::ExternalLinkage,
1668 0,
1669 Name,
1670 &CGM.getModule());
1671 }
1672}
1673
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001674/*
1675 struct objc_class_ext {
1676 uint32_t size;
1677 const char *weak_ivar_layout;
1678 struct _objc_property_list *properties;
1679 };
1680*/
1681llvm::Constant *
1682CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1683 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001684 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001685
1686 std::vector<llvm::Constant*> Values(3);
1687 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001688 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00001689 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00001690 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001691 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001692 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001693
1694 // Return null if no extension bits are used.
1695 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1696 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1697
1698 llvm::Constant *Init =
1699 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001700 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001701 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1702 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001703}
1704
Fariborz Jahanianc314a492009-01-17 19:36:33 +00001705/// countInheritedIvars - count number of ivars in class and its super class(s)
1706///
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001707static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1708 ASTContext &Context) {
Fariborz Jahanianc314a492009-01-17 19:36:33 +00001709 int count = 0;
1710 if (!OI)
1711 return 0;
1712 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1713 if (SuperClass)
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001714 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianc314a492009-01-17 19:36:33 +00001715 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1716 E = OI->ivar_end(); I != E; ++I)
1717 ++count;
Fariborz Jahanianfbf44642009-03-31 18:11:23 +00001718 // look into properties.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001719 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1720 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanianfbf44642009-03-31 18:11:23 +00001721 if ((*I)->getPropertyIvarDecl())
1722 ++count;
1723 }
Fariborz Jahanianc314a492009-01-17 19:36:33 +00001724 return count;
1725}
1726
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001727/// getInterfaceDeclForIvar - Get the interface declaration node where
1728/// this ivar is declared in.
1729/// FIXME. Ideally, this info should be in the ivar node. But currently
1730/// it is not and prevailing wisdom is that ASTs should not have more
1731/// info than is absolutely needed, even though this info reflects the
1732/// source language.
1733///
1734static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1735 const ObjCInterfaceDecl *OI,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001736 const ObjCIvarDecl *IVD,
1737 ASTContext &Context) {
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001738 if (!OI)
1739 return 0;
1740 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1741 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1742 E = OI->ivar_end(); I != E; ++I)
1743 if ((*I)->getIdentifier() == IVD->getIdentifier())
1744 return OI;
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00001745 // look into properties.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001746 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1747 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00001748 ObjCPropertyDecl *PDecl = (*I);
1749 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1750 if (IV->getIdentifier() == IVD->getIdentifier())
1751 return OI;
1752 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001753 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001754}
1755
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001756/*
1757 struct objc_ivar {
1758 char *ivar_name;
1759 char *ivar_type;
1760 int ivar_offset;
1761 };
1762
1763 struct objc_ivar_list {
1764 int ivar_count;
1765 struct objc_ivar list[count];
1766 };
1767 */
1768llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001769 bool ForClass) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001770 std::vector<llvm::Constant*> Ivars, Ivar(3);
1771
1772 // When emitting the root class GCC emits ivar entries for the
1773 // actual class structure. It is not clear if we need to follow this
1774 // behavior; for now lets try and get away with not doing it. If so,
1775 // the cleanest solution would be to make up an ObjCInterfaceDecl
1776 // for the class.
1777 if (ForClass)
1778 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001779
1780 ObjCInterfaceDecl *OID =
1781 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00001782 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001783
Daniel Dunbar356f0742009-04-20 06:54:31 +00001784 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1785 GetNamedIvarList(OID, OIvars);
1786
1787 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1788 ObjCIvarDecl *IVD = OIvars[i];
1789 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00001790 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Daniel Dunbar356f0742009-04-20 06:54:31 +00001791 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel593a07a2009-03-04 18:21:39 +00001792 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001793 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001794 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001795 }
1796
1797 // Return null for empty list.
1798 if (Ivars.empty())
1799 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1800
1801 std::vector<llvm::Constant*> Values(2);
1802 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1803 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1804 Ivars.size());
1805 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1806 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1807
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001808 llvm::GlobalVariable *GV;
1809 if (ForClass)
1810 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar56756c32009-03-09 22:18:41 +00001811 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1812 4, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001813 else
1814 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1815 + ID->getNameAsString(),
1816 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001817 4, true);
1818 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001819}
1820
1821/*
1822 struct objc_method {
1823 SEL method_name;
1824 char *method_types;
1825 void *method;
1826 };
1827
1828 struct objc_method_list {
1829 struct objc_method_list *obsolete;
1830 int count;
1831 struct objc_method methods_list[count];
1832 };
1833*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00001834
1835/// GetMethodConstant - Return a struct objc_method constant for the
1836/// given method if it has been defined. The result is null if the
1837/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001838llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001839 // FIXME: Use DenseMap::lookup
1840 llvm::Function *Fn = MethodDefinitions[MD];
1841 if (!Fn)
1842 return 0;
1843
1844 std::vector<llvm::Constant*> Method(3);
1845 Method[0] =
1846 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1847 ObjCTypes.SelectorPtrTy);
1848 Method[1] = GetMethodVarType(MD);
1849 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1850 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1851}
1852
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001853llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1854 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001855 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001856 // Return null for empty list.
1857 if (Methods.empty())
1858 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1859
1860 std::vector<llvm::Constant*> Values(3);
1861 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1862 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1863 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1864 Methods.size());
1865 Values[2] = llvm::ConstantArray::get(AT, Methods);
1866 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1867
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001868 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001869 return llvm::ConstantExpr::getBitCast(GV,
1870 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00001871}
1872
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001873llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001874 const ObjCContainerDecl *CD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00001875 std::string Name;
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00001876 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarace33292008-08-16 03:19:19 +00001877
Daniel Dunbar34bda882009-02-02 23:23:47 +00001878 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001879 const llvm::FunctionType *MethodTy =
Daniel Dunbar34bda882009-02-02 23:23:47 +00001880 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarace33292008-08-16 03:19:19 +00001881 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001882 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00001883 llvm::GlobalValue::InternalLinkage,
1884 Name,
1885 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00001886 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00001887
Daniel Dunbarace33292008-08-16 03:19:19 +00001888 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001889}
1890
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00001891uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +00001892 const FieldDecl *Field) {
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00001893 if (!Field->isBitField())
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001894 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1895
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00001896 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001897 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1898 // FIXME: The "field no" for bitfields is something completely
1899 // different; it is the offset in multiples of the base type size!
1900 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1901 const llvm::Type *Ty =
1902 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1903 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1904 return (Offset + BFI.Begin) / 8;
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00001905}
1906
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001907/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001908uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1909 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +00001910 const FieldDecl *Field) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001911 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnerd391dab2009-03-31 08:33:16 +00001912 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1913 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001914}
1915
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001916llvm::GlobalVariable *
1917CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1918 llvm::Constant *Init,
1919 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +00001920 unsigned Align,
1921 bool AddToUsed) {
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001922 const llvm::Type *Ty = Init->getType();
1923 llvm::GlobalVariable *GV =
1924 new llvm::GlobalVariable(Ty, false,
1925 llvm::GlobalValue::InternalLinkage,
1926 Init,
1927 Name,
1928 &CGM.getModule());
1929 if (Section)
1930 GV->setSection(Section);
Daniel Dunbareddddd22009-03-09 20:50:13 +00001931 if (Align)
1932 GV->setAlignment(Align);
1933 if (AddToUsed)
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001934 UsedGlobals.push_back(GV);
1935 return GV;
1936}
1937
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001938llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001939 // Abuse this interface function as a place to finalize.
1940 FinishModule();
1941
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001942 return NULL;
1943}
1944
Chris Lattneraea1aee2009-03-22 21:03:39 +00001945llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbarf7103722008-09-24 03:38:44 +00001946 return ObjCTypes.GetPropertyFn;
1947}
1948
Chris Lattneraea1aee2009-03-22 21:03:39 +00001949llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbarf7103722008-09-24 03:38:44 +00001950 return ObjCTypes.SetPropertyFn;
1951}
1952
Chris Lattneraea1aee2009-03-22 21:03:39 +00001953llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson58d16242008-08-31 04:05:03 +00001954 return ObjCTypes.EnumerationMutationFn;
1955}
1956
Daniel Dunbar83544842008-09-28 01:03:14 +00001957/*
1958
1959Objective-C setjmp-longjmp (sjlj) Exception Handling
1960--
1961
1962The basic framework for a @try-catch-finally is as follows:
1963{
1964 objc_exception_data d;
1965 id _rethrow = null;
Anders Carlsson8559de12009-02-07 21:26:04 +00001966 bool _call_try_exit = true;
1967
Daniel Dunbar83544842008-09-28 01:03:14 +00001968 objc_exception_try_enter(&d);
1969 if (!setjmp(d.jmp_buf)) {
1970 ... try body ...
1971 } else {
1972 // exception path
1973 id _caught = objc_exception_extract(&d);
1974
1975 // enter new try scope for handlers
1976 if (!setjmp(d.jmp_buf)) {
1977 ... match exception and execute catch blocks ...
1978
1979 // fell off end, rethrow.
1980 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001981 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001982 } else {
1983 // exception in catch block
1984 _rethrow = objc_exception_extract(&d);
Anders Carlsson8559de12009-02-07 21:26:04 +00001985 _call_try_exit = false;
1986 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001987 }
1988 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001989 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001990
1991finally:
Anders Carlsson8559de12009-02-07 21:26:04 +00001992 if (_call_try_exit)
1993 objc_exception_try_exit(&d);
1994
Daniel Dunbar83544842008-09-28 01:03:14 +00001995 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001996 ... dispatch to finally destination ...
1997
1998finally_rethrow:
1999 objc_exception_throw(_rethrow);
2000
2001finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00002002}
2003
2004This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002005uses _rethrow to determine if objc_exception_try_exit should be called
2006and if the object should be rethrown. This breaks in the face of
2007throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00002008
2009We specialize this framework for a few particular circumstances:
2010
2011 - If there are no catch blocks, then we avoid emitting the second
2012 exception handling context.
2013
2014 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2015 e)) we avoid emitting the code to rethrow an uncaught exception.
2016
2017 - FIXME: If there is no @finally block we can do a few more
2018 simplifications.
2019
2020Rethrows and Jumps-Through-Finally
2021--
2022
2023Support for implicit rethrows and jumping through the finally block is
2024handled by storing the current exception-handling context in
2025ObjCEHStack.
2026
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002027In order to implement proper @finally semantics, we support one basic
2028mechanism for jumping through the finally block to an arbitrary
2029destination. Constructs which generate exits from a @try or @catch
2030block use this mechanism to implement the proper semantics by chaining
2031jumps, as necessary.
2032
2033This mechanism works like the one used for indirect goto: we
2034arbitrarily assign an ID to each destination and store the ID for the
2035destination in a variable prior to entering the finally block. At the
2036end of the finally block we simply create a switch to the proper
2037destination.
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002038
2039Code gen for @synchronized(expr) stmt;
2040Effectively generating code for:
2041objc_sync_enter(expr);
2042@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar83544842008-09-28 01:03:14 +00002043*/
2044
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002045void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2046 const Stmt &S) {
2047 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002048 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00002049 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson8559de12009-02-07 21:26:04 +00002050 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar72f96552008-11-11 02:29:29 +00002051 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2052 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2053 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar34416d62009-02-24 01:43:46 +00002054
2055 // For @synchronized, call objc_sync_enter(sync.expr). The
2056 // evaluation of the expression must occur before we enter the
2057 // @synchronized. We can safely avoid a temp here because jumps into
2058 // @synchronized are illegal & this will dominate uses.
2059 llvm::Value *SyncArg = 0;
2060 if (!isTry) {
2061 SyncArg =
2062 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2063 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00002064 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar34416d62009-02-24 01:43:46 +00002065 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002066
2067 // Push an EH context entry, used for handling rethrows and jumps
2068 // through finally.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002069 CGF.PushCleanupBlock(FinallyBlock);
2070
Anders Carlssonecd81832009-02-07 21:37:21 +00002071 CGF.ObjCEHValueStack.push_back(0);
2072
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002073 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00002074 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2075 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002076 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2077 "_rethrow");
Anders Carlsson8559de12009-02-07 21:26:04 +00002078 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2079 "_call_try_exit");
2080 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2081
Anders Carlssonfca6c292008-09-09 17:59:25 +00002082 // Enter a new try block and call setjmp.
2083 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2084 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2085 "jmpbufarray");
2086 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2087 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2088 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002089
Daniel Dunbar72f96552008-11-11 02:29:29 +00002090 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2091 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002092 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002093 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002094
2095 // Emit the @try block.
2096 CGF.EmitBlock(TryBlock);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002097 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2098 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002099 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002100
2101 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002102 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002103
2104 // Retrieve the exception object. We may emit multiple blocks but
2105 // nothing can cross this so the value is already in SSA form.
2106 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2107 ExceptionData,
2108 "caught");
Anders Carlssonecd81832009-02-07 21:37:21 +00002109 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002110 if (!isTry)
2111 {
2112 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002113 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002114 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002115 }
2116 else if (const ObjCAtCatchStmt* CatchStmt =
2117 cast<ObjCAtTryStmt>(S).getCatchStmts())
2118 {
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002119 // Enter a new exception try block (in case a @catch block throws
2120 // an exception).
Anders Carlssonfca6c292008-09-09 17:59:25 +00002121 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002122
Anders Carlssonfca6c292008-09-09 17:59:25 +00002123 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2124 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002125 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002126
Daniel Dunbar72f96552008-11-11 02:29:29 +00002127 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2128 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002129 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002130
2131 CGF.EmitBlock(CatchBlock);
2132
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002133 // Handle catch list. As a special case we check if everything is
2134 // matched and avoid generating code for falling off the end if
2135 // so.
2136 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002137 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00002138 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002139
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002140 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002141 const PointerType *PT = 0;
2142
Anders Carlssonfca6c292008-09-09 17:59:25 +00002143 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002144 if (!CatchParam) {
2145 AllMatched = true;
2146 } else {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002147 PT = CatchParam->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002148
Daniel Dunbard04c9352008-09-27 22:21:14 +00002149 // catch(id e) always matches.
2150 // FIXME: For the time being we also match id<X>; this should
2151 // be rejected by Sema instead.
Steve Naroff17c03822009-02-12 17:52:19 +00002152 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002153 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002154 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002155 }
2156
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002157 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00002158 if (CatchParam) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002159 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002160 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002161 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002162 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00002163
Anders Carlsson75d86732008-09-11 09:15:33 +00002164 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002165 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002166 break;
2167 }
2168
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002169 assert(PT && "Unexpected non-pointer type in @catch");
2170 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00002171 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002172 assert(ObjCType && "Catch parameter must have Objective-C type!");
2173
2174 // Check if the @catch block matches the exception object.
2175 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2176
Anders Carlssonfca6c292008-09-09 17:59:25 +00002177 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2178 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002179
Daniel Dunbar72f96552008-11-11 02:29:29 +00002180 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002181
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002182 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002183 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002184
2185 // Emit the @catch block.
2186 CGF.EmitBlock(MatchedBlock);
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002187 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002188 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00002189
2190 llvm::Value *Tmp =
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002191 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar83544842008-09-28 01:03:14 +00002192 "tmp");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002193 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002194
2195 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002196 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002197
2198 CGF.EmitBlock(NextCatchBlock);
2199 }
2200
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002201 if (!AllMatched) {
2202 // None of the handlers caught the exception, so store it to be
2203 // rethrown at the end of the @finally block.
2204 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002205 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002206 }
2207
2208 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002209 CGF.EmitBlock(CatchHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002210 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2211 ExceptionData),
2212 RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002213 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002214 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002215 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00002216 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002217 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002218 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002219 }
2220
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002221 // Pop the exception-handling stack entry. It is important to do
2222 // this now, because the code in the @finally block is not in this
2223 // context.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002224 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2225
Anders Carlssonecd81832009-02-07 21:37:21 +00002226 CGF.ObjCEHValueStack.pop_back();
2227
Anders Carlssonfca6c292008-09-09 17:59:25 +00002228 // Emit the @finally block.
2229 CGF.EmitBlock(FinallyBlock);
Anders Carlsson8559de12009-02-07 21:26:04 +00002230 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2231
2232 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2233
2234 CGF.EmitBlock(FinallyExit);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002235 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002236
2237 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002238 if (isTry) {
2239 if (const ObjCAtFinallyStmt* FinallyStmt =
2240 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2241 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar34416d62009-02-24 01:43:46 +00002242 } else {
2243 // Emit objc_sync_exit(expr); as finally's sole statement for
2244 // @synchronized.
2245 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanian3895d922008-11-21 19:21:53 +00002246 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00002247
Anders Carlsson00ffb962009-02-09 20:38:58 +00002248 // Emit the switch block
2249 if (Info.SwitchBlock)
2250 CGF.EmitBlock(Info.SwitchBlock);
2251 if (Info.EndBlock)
2252 CGF.EmitBlock(Info.EndBlock);
2253
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002254 CGF.EmitBlock(FinallyRethrow);
2255 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2256 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002257 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002258
2259 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00002260}
2261
2262void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002263 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00002264 llvm::Value *ExceptionAsObject;
2265
2266 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2267 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2268 ExceptionAsObject =
2269 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2270 } else {
Anders Carlssonecd81832009-02-07 21:37:21 +00002271 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00002272 "Unexpected rethrow outside @catch block.");
Anders Carlssonecd81832009-02-07 21:37:21 +00002273 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson05d7be72008-09-09 16:16:55 +00002274 }
2275
2276 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002277 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002278
2279 // Clear the insertion point to indicate we are in unreachable code.
2280 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00002281}
2282
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002283/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002284/// object: objc_read_weak (id *src)
2285///
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002286llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002287 llvm::Value *AddrWeakObj)
2288{
Eli Friedmanf8466232009-03-07 03:57:15 +00002289 const llvm::Type* DestTy =
2290 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002291 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002292 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002293 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00002294 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002295 return read_weak;
2296}
2297
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002298/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2299/// objc_assign_weak (id src, id *dst)
2300///
2301void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2302 llvm::Value *src, llvm::Value *dst)
2303{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002304 const llvm::Type * SrcTy = src->getType();
2305 if (!isa<llvm::PointerType>(SrcTy)) {
2306 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2307 assert(Size <= 8 && "does not support size > 8");
2308 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2309 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002310 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2311 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002312 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2313 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00002314 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002315 src, dst, "weakassign");
2316 return;
2317}
2318
Fariborz Jahanian17958902008-11-19 00:59:10 +00002319/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2320/// objc_assign_global (id src, id *dst)
2321///
2322void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2323 llvm::Value *src, llvm::Value *dst)
2324{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002325 const llvm::Type * SrcTy = src->getType();
2326 if (!isa<llvm::PointerType>(SrcTy)) {
2327 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2328 assert(Size <= 8 && "does not support size > 8");
2329 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2330 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002331 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2332 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002333 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2334 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00002335 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2336 src, dst, "globalassign");
2337 return;
2338}
2339
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002340/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2341/// objc_assign_ivar (id src, id *dst)
2342///
2343void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2344 llvm::Value *src, llvm::Value *dst)
2345{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002346 const llvm::Type * SrcTy = src->getType();
2347 if (!isa<llvm::PointerType>(SrcTy)) {
2348 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2349 assert(Size <= 8 && "does not support size > 8");
2350 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2351 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002352 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2353 }
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002354 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2355 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2356 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2357 src, dst, "assignivar");
2358 return;
2359}
2360
Fariborz Jahanian17958902008-11-19 00:59:10 +00002361/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2362/// objc_assign_strongCast (id src, id *dst)
2363///
2364void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2365 llvm::Value *src, llvm::Value *dst)
2366{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002367 const llvm::Type * SrcTy = src->getType();
2368 if (!isa<llvm::PointerType>(SrcTy)) {
2369 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2370 assert(Size <= 8 && "does not support size > 8");
2371 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2372 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002373 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2374 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002375 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2376 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00002377 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2378 src, dst, "weakassign");
2379 return;
2380}
2381
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002382/// EmitObjCValueForIvar - Code Gen for ivar reference.
2383///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002384LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2385 QualType ObjectTy,
2386 llvm::Value *BaseValue,
2387 const ObjCIvarDecl *Ivar,
2388 const FieldDecl *Field,
2389 unsigned CVRQualifiers) {
2390 if (Ivar->isBitField())
2391 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2392 CVRQualifiers);
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002393 // TODO: Add a special case for isa (index 0)
2394 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2395 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002396 LValue LV = LValue::MakeAddr(V,
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00002397 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2398 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002399 LValue::SetObjCIvar(LV, true);
2400 return LV;
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002401}
2402
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002403llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2404 ObjCInterfaceDecl *Interface,
2405 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002406 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbarf0587c62009-04-20 00:37:55 +00002407 const FieldDecl *Field =
2408 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00002409 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002410 return llvm::ConstantInt::get(
2411 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2412 Offset);
2413}
2414
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002415/* *** Private Interface *** */
2416
2417/// EmitImageInfo - Emit the image info marker used to encode some module
2418/// level information.
2419///
2420/// See: <rdr://4810609&4810587&4810587>
2421/// struct IMAGE_INFO {
2422/// unsigned version;
2423/// unsigned flags;
2424/// };
2425enum ImageInfoFlags {
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002426 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2427 // this implies.
2428 eImageInfo_GarbageCollected = (1 << 1),
2429 eImageInfo_GCOnly = (1 << 2),
2430 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2431
2432 // A flag indicating that the module has no instances of an
2433 // @synthesize of a superclass variable. <rdar://problem/6803242>
2434 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002435};
2436
2437void CGObjCMac::EmitImageInfo() {
2438 unsigned version = 0; // Version is unused?
2439 unsigned flags = 0;
2440
2441 // FIXME: Fix and continue?
2442 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2443 flags |= eImageInfo_GarbageCollected;
2444 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2445 flags |= eImageInfo_GCOnly;
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002446
2447 // We never allow @synthesize of a superclass property.
2448 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002449
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002450 // Emitted as int[2];
2451 llvm::Constant *values[2] = {
2452 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2453 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2454 };
2455 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002456
2457 const char *Section;
2458 if (ObjCABI == 1)
2459 Section = "__OBJC, __image_info,regular";
2460 else
2461 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002462 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002463 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2464 llvm::ConstantArray::get(AT, values, 2),
2465 Section,
2466 0,
2467 true);
2468 GV->setConstant(true);
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002469}
2470
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002471
2472// struct objc_module {
2473// unsigned long version;
2474// unsigned long size;
2475// const char *name;
2476// Symtab symtab;
2477// };
2478
2479// FIXME: Get from somewhere
2480static const int ModuleVersion = 7;
2481
2482void CGObjCMac::EmitModuleInfo() {
Daniel Dunbard8439f22009-01-12 21:08:18 +00002483 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002484
2485 std::vector<llvm::Constant*> Values(4);
2486 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2487 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00002488 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002489 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002490 Values[3] = EmitModuleSymbols();
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002491 CreateMetadataVar("\01L_OBJC_MODULES",
2492 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2493 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00002494 4, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002495}
2496
2497llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002498 unsigned NumClasses = DefinedClasses.size();
2499 unsigned NumCategories = DefinedCategories.size();
2500
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002501 // Return null if no symbols were defined.
2502 if (!NumClasses && !NumCategories)
2503 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2504
2505 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002506 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2507 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2508 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2509 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2510
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002511 // The runtime expects exactly the list of defined classes followed
2512 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002513 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002514 for (unsigned i=0; i<NumClasses; i++)
2515 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2516 ObjCTypes.Int8PtrTy);
2517 for (unsigned i=0; i<NumCategories; i++)
2518 Symbols[NumClasses + i] =
2519 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2520 ObjCTypes.Int8PtrTy);
2521
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002522 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002523 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002524 NumClasses + NumCategories),
2525 Symbols);
2526
2527 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2528
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002529 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002530 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2531 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002532 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002533 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2534}
2535
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002536llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002537 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002538 LazySymbols.insert(ID->getIdentifier());
2539
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002540 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2541
2542 if (!Entry) {
2543 llvm::Constant *Casted =
2544 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2545 ObjCTypes.ClassPtrTy);
2546 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002547 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2548 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002549 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002550 }
2551
2552 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002553}
2554
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002555llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002556 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2557
2558 if (!Entry) {
2559 llvm::Constant *Casted =
2560 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2561 ObjCTypes.SelectorPtrTy);
2562 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002563 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2564 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002565 4, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002566 }
2567
2568 return Builder.CreateLoad(Entry, false, "tmp");
2569}
2570
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00002571llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002572 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002573
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002574 if (!Entry)
2575 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2576 llvm::ConstantArray::get(Ident->getName()),
2577 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002578 1, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002579
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002580 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002581}
2582
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002583/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2584/// interface declaration.
2585const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2586 const ObjCInterfaceDecl *OID) const {
Chris Lattner9fe470d2009-04-19 06:02:28 +00002587 const llvm::Type *InterfaceTy;
2588
Daniel Dunbarecb5d402009-04-19 23:41:48 +00002589 // FIXME: When does this happen? It seems pretty bad to do this...
Chris Lattner9fe470d2009-04-19 06:02:28 +00002590 if (OID->isForwardDecl()) {
2591 InterfaceTy = llvm::StructType::get(NULL, NULL);
2592 } else {
2593 QualType T = CGM.getContext().getObjCInterfaceType(
2594 const_cast<ObjCInterfaceDecl*>(OID));
2595 InterfaceTy = CGM.getTypes().ConvertType(T);
2596 }
2597
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002598 const llvm::StructLayout *Layout =
2599 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2600 return Layout;
2601}
2602
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00002603/// GetIvarLayoutName - Returns a unique constant for the given
2604/// ivar layout bitmap.
2605llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2606 const ObjCCommonTypesHelper &ObjCTypes) {
2607 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2608}
2609
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002610void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2611 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +00002612 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002613 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002614 unsigned int BytePos, bool ForStrongLayout,
2615 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002616 bool IsUnion = (RD && RD->isUnion());
2617 uint64_t MaxUnionIvarSize = 0;
2618 uint64_t MaxSkippedUnionIvarSize = 0;
2619 FieldDecl *MaxField = 0;
2620 FieldDecl *MaxSkippedField = 0;
Chris Lattner9329cf52009-03-31 08:48:01 +00002621 unsigned base = 0;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002622 if (RecFields.empty())
2623 return;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002624 if (IsUnion)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002625 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattner9329cf52009-03-31 08:48:01 +00002626 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2627 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2628
2629 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2630
2631 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002632 FieldDecl *Field = RecFields[i];
2633 // Skip over unnamed or bitfields
2634 if (!Field->getIdentifier() || Field->isBitField())
2635 continue;
2636 QualType FQT = Field->getType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002637 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002638 if (FQT->isUnionType())
2639 HasUnion = true;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002640 else
2641 assert(FQT->isRecordType() &&
2642 "only union/record is supported for ivar layout bitmap");
2643
Fariborz Jahanian37931062009-03-10 16:22:08 +00002644 const RecordType *RT = FQT->getAsRecordType();
2645 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarecb5d402009-04-19 23:41:48 +00002646 // FIXME - Find a more efficient way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002647 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2648 RD->field_end(CGM.getContext()));
Fariborz Jahanian37931062009-03-10 16:22:08 +00002649 // FIXME - Is Layout correct?
Chris Lattner9329cf52009-03-31 08:48:01 +00002650 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002651 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian37931062009-03-10 16:22:08 +00002652 ForStrongLayout, Index, SkIndex,
2653 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002654 TmpRecFields.clear();
Fariborz Jahanian37931062009-03-10 16:22:08 +00002655 continue;
2656 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002657
2658 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002659 const ConstantArrayType *CArray =
2660 dyn_cast_or_null<ConstantArrayType>(Array);
2661 assert(CArray && "only array with know element size is supported");
2662 FQT = CArray->getElementType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002663 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2664 const ConstantArrayType *CArray =
2665 dyn_cast_or_null<ConstantArrayType>(Array);
2666 FQT = CArray->getElementType();
2667 }
2668
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002669 assert(!FQT->isUnionType() &&
2670 "layout for array of unions not supported");
2671 if (FQT->isRecordType()) {
2672 uint64_t ElCount = CArray->getSize().getZExtValue();
2673 int OldIndex = Index;
2674 int OldSkIndex = SkIndex;
2675
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002676 // FIXME - Use a common routine with the above!
2677 const RecordType *RT = FQT->getAsRecordType();
2678 const RecordDecl *RD = RT->getDecl();
2679 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002680 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2681 RD->field_end(CGM.getContext()));
Chris Lattner9329cf52009-03-31 08:48:01 +00002682
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002683 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002684 TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002685 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002686 ForStrongLayout, Index, SkIndex,
2687 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002688 TmpRecFields.clear();
2689
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002690 // Replicate layout information for each array element. Note that
2691 // one element is already done.
2692 uint64_t ElIx = 1;
2693 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2694 ElIx < ElCount; ElIx++) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002695 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002696 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2697 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002698 GC_IVAR gcivar;
2699 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2700 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2701 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002702 }
2703
Chris Lattner9329cf52009-03-31 08:48:01 +00002704 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002705 GC_IVAR skivar;
2706 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2707 skivar.ivar_size = SkipIvars[i].ivar_size;
2708 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002709 }
2710 }
2711 continue;
2712 }
Fariborz Jahanian37931062009-03-10 16:22:08 +00002713 }
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002714 // At this point, we are done with Record/Union and array there of.
2715 // For other arrays we are down to its element type.
2716 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2717 do {
2718 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2719 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2720 break;
2721 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002722 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002723 GCAttr = QualType::Strong;
2724 break;
2725 }
2726 else if (const PointerType *PT = FQT->getAsPointerType()) {
2727 FQT = PT->getPointeeType();
2728 }
2729 else {
2730 break;
2731 }
2732 } while (true);
Chris Lattner9329cf52009-03-31 08:48:01 +00002733
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002734 if ((ForStrongLayout && GCAttr == QualType::Strong)
2735 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2736 if (IsUnion)
2737 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002738 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2739 / WordSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002740 if (UnionIvarSize > MaxUnionIvarSize)
2741 {
2742 MaxUnionIvarSize = UnionIvarSize;
2743 MaxField = Field;
2744 }
2745 }
2746 else
2747 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002748 GC_IVAR gcivar;
2749 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2750 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2751 WordSizeInBits;
2752 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002753 }
2754 }
2755 else if ((ForStrongLayout &&
2756 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2757 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2758 if (IsUnion)
2759 {
2760 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2761 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2762 {
2763 MaxSkippedUnionIvarSize = UnionIvarSize;
2764 MaxSkippedField = Field;
2765 }
2766 }
2767 else
2768 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002769 GC_IVAR skivar;
2770 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2771 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2772 WordSizeInBits;
2773 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002774 }
2775 }
2776 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002777 if (MaxField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002778 GC_IVAR gcivar;
2779 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2780 gcivar.ivar_size = MaxUnionIvarSize;
2781 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002782 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002783
2784 if (MaxSkippedField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002785 GC_IVAR skivar;
2786 skivar.ivar_bytepos = BytePos +
2787 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2788 skivar.ivar_size = MaxSkippedUnionIvarSize;
2789 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002790 }
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002791}
2792
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002793static int
Chris Lattner9329cf52009-03-31 08:48:01 +00002794IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002795{
2796 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2797 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2798
2799 if (sa < sb)
2800 return -1;
2801 if (sa > sb)
2802 return 1;
2803 return 0;
2804}
2805
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002806/// BuildIvarLayout - Builds ivar layout bitmap for the class
2807/// implementation for the __strong or __weak case.
2808/// The layout map displays which words in ivar list must be skipped
2809/// and which must be scanned by GC (see below). String is built of bytes.
2810/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2811/// of words to skip and right nibble is count of words to scan. So, each
2812/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2813/// represented by a 0x00 byte which also ends the string.
2814/// 1. when ForStrongLayout is true, following ivars are scanned:
2815/// - id, Class
2816/// - object *
2817/// - __strong anything
2818///
2819/// 2. When ForStrongLayout is false, following ivars are scanned:
2820/// - __weak anything
2821///
Fariborz Jahanian37931062009-03-10 16:22:08 +00002822llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002823 const ObjCImplementationDecl *OMD,
2824 bool ForStrongLayout) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002825 int Index = -1;
2826 int SkIndex = -1;
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002827 bool hasUnion = false;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002828 int SkipScan;
2829 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002830 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2831 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2832 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002833
Chris Lattner9329cf52009-03-31 08:48:01 +00002834 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002835 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002836 CGM.getContext().CollectObjCIvars(OI, RecFields);
2837 if (RecFields.empty())
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002838 return llvm::Constant::getNullValue(PtrTy);
Chris Lattner9329cf52009-03-31 08:48:01 +00002839
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002840 SkipIvars.clear();
2841 IvarsInfo.clear();
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002842
2843 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattner9329cf52009-03-31 08:48:01 +00002844 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2845 Index, SkIndex, hasUnion);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002846 if (Index == -1)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002847 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002848
2849 // Sort on byte position in case we encounterred a union nested in
2850 // the ivar list.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002851 if (hasUnion && !IvarsInfo.empty())
2852 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2853 if (hasUnion && !SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002854 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2855
2856 // Build the string of skip/scan nibbles
2857 SkipScan = -1;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002858 SkipScanIvars.clear();
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002859 unsigned int WordSize =
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002860 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002861 if (IvarsInfo[0].ivar_bytepos == 0) {
2862 WordsToSkip = 0;
2863 WordsToScan = IvarsInfo[0].ivar_size;
2864 }
2865 else {
2866 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2867 WordsToScan = IvarsInfo[0].ivar_size;
2868 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002869 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002870 {
2871 unsigned int TailPrevGCObjC =
2872 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2873 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2874 {
2875 // consecutive 'scanned' object pointers.
2876 WordsToScan += IvarsInfo[i].ivar_size;
2877 }
2878 else
2879 {
2880 // Skip over 'gc'able object pointer which lay over each other.
2881 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2882 continue;
2883 // Must skip over 1 or more words. We save current skip/scan values
2884 // and start a new pair.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002885 SKIP_SCAN SkScan;
2886 SkScan.skip = WordsToSkip;
2887 SkScan.scan = WordsToScan;
2888 SkipScanIvars.push_back(SkScan); ++SkipScan;
2889
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002890 // Skip the hole.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002891 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2892 SkScan.scan = 0;
2893 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002894 WordsToSkip = 0;
2895 WordsToScan = IvarsInfo[i].ivar_size;
2896 }
2897 }
2898 if (WordsToScan > 0)
2899 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002900 SKIP_SCAN SkScan;
2901 SkScan.skip = WordsToSkip;
2902 SkScan.scan = WordsToScan;
2903 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002904 }
2905
2906 bool BytesSkipped = false;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002907 if (!SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002908 {
2909 int LastByteSkipped =
2910 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2911 int LastByteScanned =
2912 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2913 BytesSkipped = (LastByteSkipped > LastByteScanned);
2914 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2915 if (BytesSkipped)
2916 {
2917 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002918 SKIP_SCAN SkScan;
2919 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2920 SkScan.scan = 0;
2921 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002922 }
2923 }
2924 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2925 // as 0xMN.
2926 for (int i = 0; i <= SkipScan; i++)
2927 {
2928 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2929 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2930 // 0xM0 followed by 0x0N detected.
2931 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2932 for (int j = i+1; j < SkipScan; j++)
2933 SkipScanIvars[j] = SkipScanIvars[j+1];
2934 --SkipScan;
2935 }
2936 }
2937
2938 // Generate the string.
2939 std::string BitMap;
2940 for (int i = 0; i <= SkipScan; i++)
2941 {
2942 unsigned char byte;
2943 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2944 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2945 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2946 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2947
2948 if (skip_small > 0 || skip_big > 0)
2949 BytesSkipped = true;
2950 // first skip big.
2951 for (unsigned int ix = 0; ix < skip_big; ix++)
2952 BitMap += (unsigned char)(0xf0);
2953
2954 // next (skip small, scan)
2955 if (skip_small)
2956 {
2957 byte = skip_small << 4;
2958 if (scan_big > 0)
2959 {
2960 byte |= 0xf;
2961 --scan_big;
2962 }
2963 else if (scan_small)
2964 {
2965 byte |= scan_small;
2966 scan_small = 0;
2967 }
2968 BitMap += byte;
2969 }
2970 // next scan big
2971 for (unsigned int ix = 0; ix < scan_big; ix++)
2972 BitMap += (unsigned char)(0x0f);
2973 // last scan small
2974 if (scan_small)
2975 {
2976 byte = scan_small;
2977 BitMap += byte;
2978 }
2979 }
2980 // null terminate string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002981 unsigned char zero = 0;
2982 BitMap += zero;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002983 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2984 // final layout.
2985 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002986 return llvm::Constant::getNullValue(PtrTy);
2987 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2988 llvm::ConstantArray::get(BitMap.c_str()),
2989 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002990 1, true);
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002991 // FIXME. Need a commomand-line option for this eventually.
2992 if (ForStrongLayout)
2993 printf("\nstrong ivar layout: ");
2994 else
2995 printf("\nweak ivar layout: ");
2996 const unsigned char *s = (unsigned char*)BitMap.c_str();
2997 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniana73e9f82009-03-26 19:10:36 +00002998 if (!(s[i] & 0xf0))
2999 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3000 else
3001 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian738ee712009-03-25 22:36:49 +00003002 printf("\n");
3003
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003004 return getConstantGEP(Entry, 0, 0);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003005}
3006
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003007llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003008 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3009
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003010 // FIXME: Avoid std::string copying.
3011 if (!Entry)
3012 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3013 llvm::ConstantArray::get(Sel.getAsString()),
3014 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003015 1, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003016
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003017 return getConstantGEP(Entry, 0, 0);
3018}
3019
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003020// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003021llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003022 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3023}
3024
3025// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003026llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003027 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3028}
3029
Daniel Dunbar356f0742009-04-20 06:54:31 +00003030llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel593a07a2009-03-04 18:21:39 +00003031 std::string TypeStr;
3032 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3033
3034 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003035
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003036 if (!Entry)
3037 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3038 llvm::ConstantArray::get(TypeStr),
3039 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003040 1, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003041
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003042 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003043}
3044
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003045llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003046 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00003047 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3048 TypeStr);
Devang Patel593a07a2009-03-04 18:21:39 +00003049
3050 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3051
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003052 if (!Entry)
3053 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3054 llvm::ConstantArray::get(TypeStr),
3055 "__TEXT,__cstring,cstring_literals",
3056 1, true);
Devang Patel593a07a2009-03-04 18:21:39 +00003057
3058 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003059}
3060
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003061// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003062llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003063 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3064
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003065 if (!Entry)
3066 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3067 llvm::ConstantArray::get(Ident->getName()),
3068 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003069 1, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003070
3071 return getConstantGEP(Entry, 0, 0);
3072}
3073
3074// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003075// FIXME: This Decl should be more precise.
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003076llvm::Constant *
3077 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3078 const Decl *Container) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003079 std::string TypeStr;
3080 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003081 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3082}
3083
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003084void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3085 const ObjCContainerDecl *CD,
3086 std::string &NameOut) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00003087 NameOut = '\01';
3088 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner3a8f2942008-11-24 03:33:13 +00003089 NameOut += '[';
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00003090 assert (CD && "Missing container decl in GetNameForMethod");
3091 NameOut += CD->getNameAsString();
Fariborz Jahanian6e4b7372009-04-16 18:34:20 +00003092 if (const ObjCCategoryImplDecl *CID =
3093 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3094 NameOut += '(';
3095 NameOut += CID->getNameAsString();
3096 NameOut+= ')';
3097 }
Chris Lattner3a8f2942008-11-24 03:33:13 +00003098 NameOut += ' ';
3099 NameOut += D->getSelector().getAsString();
3100 NameOut += ']';
Daniel Dunbarace33292008-08-16 03:19:19 +00003101}
3102
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003103void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003104 EmitModuleInfo();
3105
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003106 // Emit the dummy bodies for any protocols which were referenced but
3107 // never defined.
3108 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3109 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3110 if (i->second->hasInitializer())
3111 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003112
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003113 std::vector<llvm::Constant*> Values(5);
3114 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3115 Values[1] = GetClassName(i->first);
3116 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3117 Values[3] = Values[4] =
3118 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3119 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3120 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3121 Values));
3122 }
3123
3124 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003125 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003126 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003127 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003128 }
3129
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003130 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003131 llvm::GlobalValue *GV =
3132 new llvm::GlobalVariable(AT, false,
3133 llvm::GlobalValue::AppendingLinkage,
3134 llvm::ConstantArray::get(AT, Used),
3135 "llvm.used",
3136 &CGM.getModule());
3137
3138 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003139
3140 // Add assembler directives to add lazy undefined symbol references
3141 // for classes which are referenced but not defined. This is
3142 // important for correct linker interaction.
3143
3144 // FIXME: Uh, this isn't particularly portable.
3145 std::stringstream s;
Anders Carlsson63f98352008-12-10 02:21:04 +00003146
3147 if (!CGM.getModule().getModuleInlineAsm().empty())
3148 s << "\n";
3149
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003150 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3151 e = LazySymbols.end(); i != e; ++i) {
3152 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3153 }
3154 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3155 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003156 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003157 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3158 }
Anders Carlsson63f98352008-12-10 02:21:04 +00003159
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003160 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003161}
3162
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003163CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003164 : CGObjCCommonMac(cgm),
3165 ObjCTypes(cgm)
3166{
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003167 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003168 ObjCABI = 2;
3169}
3170
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003171/* *** */
3172
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003173ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3174: CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003175{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003176 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3177 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003178
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003179 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003180 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003181 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00003182 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003183 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3184
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003185 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003186 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003187 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003188
3189 // FIXME: It would be nice to unify this with the opaque type, so
3190 // that the IR comes out a bit cleaner.
3191 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3192 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003193
3194 // I'm not sure I like this. The implicit coordination is a bit
3195 // gross. We should solve this in a reasonable fashion because this
3196 // is a pretty common task (match some runtime data structure with
3197 // an LLVM data structure).
3198
3199 // FIXME: This is leaked.
3200 // FIXME: Merge with rewriter code?
3201
3202 // struct _objc_super {
3203 // id self;
3204 // Class cls;
3205 // }
3206 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3207 SourceLocation(),
3208 &Ctx.Idents.get("_objc_super"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003209 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3210 Ctx.getObjCIdType(), 0, false));
3211 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3212 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003213 RD->completeDefinition(Ctx);
3214
3215 SuperCTy = Ctx.getTagDeclType(RD);
3216 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3217
3218 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003219 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3220
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003221 // struct _prop_t {
3222 // char *name;
3223 // char *attributes;
3224 // }
3225 PropertyTy = llvm::StructType::get(Int8PtrTy,
3226 Int8PtrTy,
3227 NULL);
3228 CGM.getModule().addTypeName("struct._prop_t",
3229 PropertyTy);
3230
3231 // struct _prop_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003232 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003233 // uint32_t count_of_properties;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003234 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003235 // }
3236 PropertyListTy = llvm::StructType::get(IntTy,
3237 IntTy,
3238 llvm::ArrayType::get(PropertyTy, 0),
3239 NULL);
3240 CGM.getModule().addTypeName("struct._prop_list_t",
3241 PropertyListTy);
3242 // struct _prop_list_t *
3243 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3244
3245 // struct _objc_method {
3246 // SEL _cmd;
3247 // char *method_type;
3248 // char *_imp;
3249 // }
3250 MethodTy = llvm::StructType::get(SelectorPtrTy,
3251 Int8PtrTy,
3252 Int8PtrTy,
3253 NULL);
3254 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003255
3256 // struct _objc_cache *
3257 CacheTy = llvm::OpaqueType::get();
3258 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3259 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003260
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003261 // Property manipulation functions.
Daniel Dunbardac29922009-02-04 00:44:42 +00003262
3263 QualType IdType = Ctx.getObjCIdType();
3264 QualType SelType = Ctx.getObjCSelType();
3265 llvm::SmallVector<QualType,16> Params;
3266 const llvm::FunctionType *FTy;
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003267
3268 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbardac29922009-02-04 00:44:42 +00003269 Params.push_back(IdType);
3270 Params.push_back(SelType);
3271 Params.push_back(Ctx.LongTy);
3272 Params.push_back(Ctx.BoolTy);
3273 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3274 false);
3275 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003276
3277 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3278 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003279 Params.push_back(IdType);
3280 Params.push_back(SelType);
3281 Params.push_back(Ctx.LongTy);
3282 Params.push_back(IdType);
3283 Params.push_back(Ctx.BoolTy);
3284 Params.push_back(Ctx.BoolTy);
3285 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3286 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3287
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003288 // Enumeration mutation.
Daniel Dunbardac29922009-02-04 00:44:42 +00003289
3290 // void objc_enumerationMutation (id)
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003291 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003292 Params.push_back(IdType);
3293 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3294 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3295 "objc_enumerationMutation");
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003296
3297 // gc's API
3298 // id objc_read_weak (id *)
3299 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003300 Params.push_back(Ctx.getPointerType(IdType));
3301 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3302 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3303
Chris Lattner293c1d32009-04-17 22:12:36 +00003304 // id objc_assign_global (id, id *)
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003305 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003306 Params.push_back(IdType);
3307 Params.push_back(Ctx.getPointerType(IdType));
3308
3309 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbardac29922009-02-04 00:44:42 +00003310 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3311 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3312 GcAssignStrongCastFn =
3313 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlsson1cf75362009-02-16 22:59:18 +00003314
3315 // void objc_exception_throw(id)
3316 Params.clear();
3317 Params.push_back(IdType);
3318
3319 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlsson1cf75362009-02-16 22:59:18 +00003320 ExceptionThrowFn =
3321 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar34416d62009-02-24 01:43:46 +00003322
3323 // synchronized APIs
Daniel Dunbar34416d62009-02-24 01:43:46 +00003324 // void objc_sync_exit (id)
3325 Params.clear();
3326 Params.push_back(IdType);
3327
3328 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar34416d62009-02-24 01:43:46 +00003329 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003330}
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003331
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003332ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3333 : ObjCCommonTypesHelper(cgm)
3334{
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003335 // struct _objc_method_description {
3336 // SEL name;
3337 // char *types;
3338 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003339 MethodDescriptionTy =
3340 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003341 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003342 NULL);
3343 CGM.getModule().addTypeName("struct._objc_method_description",
3344 MethodDescriptionTy);
3345
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003346 // struct _objc_method_description_list {
3347 // int count;
3348 // struct _objc_method_description[1];
3349 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003350 MethodDescriptionListTy =
3351 llvm::StructType::get(IntTy,
3352 llvm::ArrayType::get(MethodDescriptionTy, 0),
3353 NULL);
3354 CGM.getModule().addTypeName("struct._objc_method_description_list",
3355 MethodDescriptionListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003356
3357 // struct _objc_method_description_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003358 MethodDescriptionListPtrTy =
3359 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3360
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003361 // Protocol description structures
3362
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003363 // struct _objc_protocol_extension {
3364 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3365 // struct _objc_method_description_list *optional_instance_methods;
3366 // struct _objc_method_description_list *optional_class_methods;
3367 // struct _objc_property_list *instance_properties;
3368 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003369 ProtocolExtensionTy =
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003370 llvm::StructType::get(IntTy,
3371 MethodDescriptionListPtrTy,
3372 MethodDescriptionListPtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003373 PropertyListPtrTy,
3374 NULL);
3375 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3376 ProtocolExtensionTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003377
3378 // struct _objc_protocol_extension *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003379 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3380
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003381 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003382
3383 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3384 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3385
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003386 const llvm::Type *T =
3387 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3388 LongTy,
3389 llvm::ArrayType::get(ProtocolTyHolder, 0),
3390 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003391 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3392
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003393 // struct _objc_protocol {
3394 // struct _objc_protocol_extension *isa;
3395 // char *protocol_name;
3396 // struct _objc_protocol **_objc_protocol_list;
3397 // struct _objc_method_description_list *instance_methods;
3398 // struct _objc_method_description_list *class_methods;
3399 // }
3400 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003401 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003402 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3403 MethodDescriptionListPtrTy,
3404 MethodDescriptionListPtrTy,
3405 NULL);
3406 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3407
3408 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3409 CGM.getModule().addTypeName("struct._objc_protocol_list",
3410 ProtocolListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003411 // struct _objc_protocol_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003412 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3413
3414 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003415 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003416 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003417
3418 // Class description structures
3419
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003420 // struct _objc_ivar {
3421 // char *ivar_name;
3422 // char *ivar_type;
3423 // int ivar_offset;
3424 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003425 IvarTy = llvm::StructType::get(Int8PtrTy,
3426 Int8PtrTy,
3427 IntTy,
3428 NULL);
3429 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3430
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003431 // struct _objc_ivar_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003432 IvarListTy = llvm::OpaqueType::get();
3433 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3434 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3435
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003436 // struct _objc_method_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003437 MethodListTy = llvm::OpaqueType::get();
3438 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3439 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3440
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003441 // struct _objc_class_extension *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003442 ClassExtensionTy =
3443 llvm::StructType::get(IntTy,
3444 Int8PtrTy,
3445 PropertyListPtrTy,
3446 NULL);
3447 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3448 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3449
3450 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3451
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003452 // struct _objc_class {
3453 // Class isa;
3454 // Class super_class;
3455 // char *name;
3456 // long version;
3457 // long info;
3458 // long instance_size;
3459 // struct _objc_ivar_list *ivars;
3460 // struct _objc_method_list *methods;
3461 // struct _objc_cache *cache;
3462 // struct _objc_protocol_list *protocols;
3463 // char *ivar_layout;
3464 // struct _objc_class_ext *ext;
3465 // };
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003466 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3467 llvm::PointerType::getUnqual(ClassTyHolder),
3468 Int8PtrTy,
3469 LongTy,
3470 LongTy,
3471 LongTy,
3472 IvarListPtrTy,
3473 MethodListPtrTy,
3474 CachePtrTy,
3475 ProtocolListPtrTy,
3476 Int8PtrTy,
3477 ClassExtensionPtrTy,
3478 NULL);
3479 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3480
3481 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3482 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3483 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3484
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003485 // struct _objc_category {
3486 // char *category_name;
3487 // char *class_name;
3488 // struct _objc_method_list *instance_method;
3489 // struct _objc_method_list *class_method;
3490 // uint32_t size; // sizeof(struct _objc_category)
3491 // struct _objc_property_list *instance_properties;// category's @property
3492 // }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003493 CategoryTy = llvm::StructType::get(Int8PtrTy,
3494 Int8PtrTy,
3495 MethodListPtrTy,
3496 MethodListPtrTy,
3497 ProtocolListPtrTy,
3498 IntTy,
3499 PropertyListPtrTy,
3500 NULL);
3501 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3502
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003503 // Global metadata structures
3504
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003505 // struct _objc_symtab {
3506 // long sel_ref_cnt;
3507 // SEL *refs;
3508 // short cls_def_cnt;
3509 // short cat_def_cnt;
3510 // char *defs[cls_def_cnt + cat_def_cnt];
3511 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003512 SymtabTy = llvm::StructType::get(LongTy,
3513 SelectorPtrTy,
3514 ShortTy,
3515 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003516 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003517 NULL);
3518 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3519 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3520
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003521 // struct _objc_module {
3522 // long version;
3523 // long size; // sizeof(struct _objc_module)
3524 // char *name;
3525 // struct _objc_symtab* symtab;
3526 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003527 ModuleTy =
3528 llvm::StructType::get(LongTy,
3529 LongTy,
3530 Int8PtrTy,
3531 SymtabPtrTy,
3532 NULL);
3533 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003534
Daniel Dunbarf7103722008-09-24 03:38:44 +00003535 // Message send functions.
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003536
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003537 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003538 std::vector<const llvm::Type*> Params;
3539 Params.push_back(ObjectPtrTy);
3540 Params.push_back(SelectorPtrTy);
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003541 MessageSendFn =
3542 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3543 Params,
3544 true),
3545 "objc_msgSend");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003546
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003547 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003548 Params.clear();
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003549 Params.push_back(ObjectPtrTy);
3550 Params.push_back(SelectorPtrTy);
3551 MessageSendStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003552 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3553 Params,
3554 true),
3555 "objc_msgSend_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003556
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003557 //
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003558 Params.clear();
3559 Params.push_back(ObjectPtrTy);
3560 Params.push_back(SelectorPtrTy);
3561 // FIXME: This should be long double on x86_64?
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003562 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003563 MessageSendFpretFn =
3564 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3565 Params,
3566 true),
3567 "objc_msgSend_fpret");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003568
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003569 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003570 Params.clear();
3571 Params.push_back(SuperPtrTy);
3572 Params.push_back(SelectorPtrTy);
3573 MessageSendSuperFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003574 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3575 Params,
3576 true),
3577 "objc_msgSendSuper");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003578
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003579 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3580 // SEL op, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003581 Params.clear();
3582 Params.push_back(Int8PtrTy);
3583 Params.push_back(SuperPtrTy);
3584 Params.push_back(SelectorPtrTy);
3585 MessageSendSuperStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003586 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3587 Params,
3588 true),
3589 "objc_msgSendSuper_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003590
3591 // There is no objc_msgSendSuper_fpret? How can that work?
3592 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson58d16242008-08-31 04:05:03 +00003593
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003594 // FIXME: This is the size of the setjmp buffer and should be
3595 // target specific. 18 is what's used on 32-bit X86.
3596 uint64_t SetJmpBufferSize = 18;
3597
3598 // Exceptions
3599 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00003600 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003601
3602 ExceptionDataTy =
3603 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3604 SetJmpBufferSize),
3605 StackPtrTy, NULL);
3606 CGM.getModule().addTypeName("struct._objc_exception_data",
3607 ExceptionDataTy);
3608
3609 Params.clear();
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003610 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3611 ExceptionTryEnterFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003612 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3613 Params,
3614 false),
3615 "objc_exception_try_enter");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003616 ExceptionTryExitFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003617 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3618 Params,
3619 false),
3620 "objc_exception_try_exit");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003621 ExceptionExtractFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003622 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3623 Params,
3624 false),
3625 "objc_exception_extract");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003626
3627 Params.clear();
3628 Params.push_back(ClassPtrTy);
3629 Params.push_back(ObjectPtrTy);
3630 ExceptionMatchFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003631 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3632 Params,
3633 false),
3634 "objc_exception_match");
Chris Lattnerdd978702008-11-15 21:26:17 +00003635
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003636 Params.clear();
3637 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3638 SetJmpFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003639 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3640 Params,
3641 false),
3642 "_setjmp");
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003643
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003644}
3645
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003646ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003647: ObjCCommonTypesHelper(cgm)
3648{
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003649 // struct _method_list_t {
3650 // uint32_t entsize; // sizeof(struct _objc_method)
3651 // uint32_t method_count;
3652 // struct _objc_method method_list[method_count];
3653 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003654 MethodListnfABITy = llvm::StructType::get(IntTy,
3655 IntTy,
3656 llvm::ArrayType::get(MethodTy, 0),
3657 NULL);
3658 CGM.getModule().addTypeName("struct.__method_list_t",
3659 MethodListnfABITy);
3660 // struct method_list_t *
3661 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003662
3663 // struct _protocol_t {
3664 // id isa; // NULL
3665 // const char * const protocol_name;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003666 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003667 // const struct method_list_t * const instance_methods;
3668 // const struct method_list_t * const class_methods;
3669 // const struct method_list_t *optionalInstanceMethods;
3670 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003671 // const struct _prop_list_t * properties;
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003672 // const uint32_t size; // sizeof(struct _protocol_t)
3673 // const uint32_t flags; // = 0
3674 // }
3675
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003676 // Holder for struct _protocol_list_t *
3677 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3678
3679 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3680 Int8PtrTy,
3681 llvm::PointerType::getUnqual(
3682 ProtocolListTyHolder),
3683 MethodListnfABIPtrTy,
3684 MethodListnfABIPtrTy,
3685 MethodListnfABIPtrTy,
3686 MethodListnfABIPtrTy,
3687 PropertyListPtrTy,
3688 IntTy,
3689 IntTy,
3690 NULL);
3691 CGM.getModule().addTypeName("struct._protocol_t",
3692 ProtocolnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003693
3694 // struct _protocol_t*
3695 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003696
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00003697 // struct _protocol_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003698 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003699 // struct _protocol_t *[protocol_count];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003700 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003701 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3702 llvm::ArrayType::get(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003703 ProtocolnfABIPtrTy, 0),
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003704 NULL);
3705 CGM.getModule().addTypeName("struct._objc_protocol_list",
3706 ProtocolListnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003707 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3708 ProtocolListnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003709
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003710 // struct _objc_protocol_list*
3711 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003712
3713 // struct _ivar_t {
3714 // unsigned long int *offset; // pointer to ivar offset location
3715 // char *name;
3716 // char *type;
3717 // uint32_t alignment;
3718 // uint32_t size;
3719 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003720 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3721 Int8PtrTy,
3722 Int8PtrTy,
3723 IntTy,
3724 IntTy,
3725 NULL);
3726 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3727
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003728 // struct _ivar_list_t {
3729 // uint32 entsize; // sizeof(struct _ivar_t)
3730 // uint32 count;
3731 // struct _iver_t list[count];
3732 // }
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00003733 IvarListnfABITy = llvm::StructType::get(IntTy,
3734 IntTy,
3735 llvm::ArrayType::get(
3736 IvarnfABITy, 0),
3737 NULL);
3738 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3739
3740 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003741
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003742 // struct _class_ro_t {
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003743 // uint32_t const flags;
3744 // uint32_t const instanceStart;
3745 // uint32_t const instanceSize;
3746 // uint32_t const reserved; // only when building for 64bit targets
3747 // const uint8_t * const ivarLayout;
3748 // const char *const name;
3749 // const struct _method_list_t * const baseMethods;
3750 // const struct _objc_protocol_list *const baseProtocols;
3751 // const struct _ivar_list_t *const ivars;
3752 // const uint8_t * const weakIvarLayout;
3753 // const struct _prop_list_t * const properties;
3754 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003755
3756 // FIXME. Add 'reserved' field in 64bit abi mode!
3757 ClassRonfABITy = llvm::StructType::get(IntTy,
3758 IntTy,
3759 IntTy,
3760 Int8PtrTy,
3761 Int8PtrTy,
3762 MethodListnfABIPtrTy,
3763 ProtocolListnfABIPtrTy,
3764 IvarListnfABIPtrTy,
3765 Int8PtrTy,
3766 PropertyListPtrTy,
3767 NULL);
3768 CGM.getModule().addTypeName("struct._class_ro_t",
3769 ClassRonfABITy);
3770
3771 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3772 std::vector<const llvm::Type*> Params;
3773 Params.push_back(ObjectPtrTy);
3774 Params.push_back(SelectorPtrTy);
3775 ImpnfABITy = llvm::PointerType::getUnqual(
3776 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3777
3778 // struct _class_t {
3779 // struct _class_t *isa;
3780 // struct _class_t * const superclass;
3781 // void *cache;
3782 // IMP *vtable;
3783 // struct class_ro_t *ro;
3784 // }
3785
3786 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3787 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3788 llvm::PointerType::getUnqual(ClassTyHolder),
3789 CachePtrTy,
3790 llvm::PointerType::getUnqual(ImpnfABITy),
3791 llvm::PointerType::getUnqual(
3792 ClassRonfABITy),
3793 NULL);
3794 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3795
3796 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3797 ClassnfABITy);
3798
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003799 // LLVM for struct _class_t *
3800 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3801
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003802 // struct _category_t {
3803 // const char * const name;
3804 // struct _class_t *const cls;
3805 // const struct _method_list_t * const instance_methods;
3806 // const struct _method_list_t * const class_methods;
3807 // const struct _protocol_list_t * const protocols;
3808 // const struct _prop_list_t * const properties;
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003809 // }
3810 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003811 ClassnfABIPtrTy,
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003812 MethodListnfABIPtrTy,
3813 MethodListnfABIPtrTy,
3814 ProtocolListnfABIPtrTy,
3815 PropertyListPtrTy,
3816 NULL);
3817 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003818
3819 // New types for nonfragile abi messaging.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003820 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3821 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003822
3823 // MessageRefTy - LLVM for:
3824 // struct _message_ref_t {
3825 // IMP messenger;
3826 // SEL name;
3827 // };
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003828
3829 // First the clang type for struct _message_ref_t
3830 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3831 SourceLocation(),
3832 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003833 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3834 Ctx.VoidPtrTy, 0, false));
3835 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3836 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003837 RD->completeDefinition(Ctx);
3838
3839 MessageRefCTy = Ctx.getTagDeclType(RD);
3840 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3841 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003842
3843 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3844 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3845
3846 // SuperMessageRefTy - LLVM for:
3847 // struct _super_message_ref_t {
3848 // SUPER_IMP messenger;
3849 // SEL name;
3850 // };
3851 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3852 SelectorPtrTy,
3853 NULL);
3854 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3855
3856 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3857 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3858
3859 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3860 Params.clear();
3861 Params.push_back(ObjectPtrTy);
3862 Params.push_back(MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00003863 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3864 Params,
3865 true);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003866 MessageSendFixupFn =
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00003867 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003868 "objc_msgSend_fixup");
3869
3870 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3871 MessageSendFpretFixupFn =
3872 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3873 Params,
3874 true),
3875 "objc_msgSend_fpret_fixup");
3876
3877 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3878 MessageSendStretFixupFn =
3879 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3880 Params,
3881 true),
3882 "objc_msgSend_stret_fixup");
3883
3884 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3885 MessageSendIdFixupFn =
3886 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3887 Params,
3888 true),
3889 "objc_msgSendId_fixup");
3890
3891
3892 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3893 MessageSendIdStretFixupFn =
3894 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3895 Params,
3896 true),
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003897 "objc_msgSendId_stret_fixup");
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003898
3899 // id objc_msgSendSuper2_fixup (struct objc_super *,
3900 // struct _super_message_ref_t*, ...)
3901 Params.clear();
3902 Params.push_back(SuperPtrTy);
3903 Params.push_back(SuperMessageRefPtrTy);
3904 MessageSendSuper2FixupFn =
3905 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3906 Params,
3907 true),
3908 "objc_msgSendSuper2_fixup");
3909
3910
3911 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3912 // struct _super_message_ref_t*, ...)
3913 MessageSendSuper2StretFixupFn =
3914 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3915 Params,
3916 true),
3917 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00003918
3919 Params.clear();
Daniel Dunbar75de89f2009-02-24 07:47:38 +00003920 Params.push_back(Int8PtrTy);
3921 UnwindResumeOrRethrowFn =
3922 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3923 Params,
3924 false),
3925 "_Unwind_Resume_or_Rethrow");
Daniel Dunbar9c285e72009-03-01 04:46:24 +00003926 ObjCBeginCatchFn =
3927 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3928 Params,
3929 false),
3930 "objc_begin_catch");
3931
3932 Params.clear();
3933 ObjCEndCatchFn =
3934 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3935 Params,
3936 false),
3937 "objc_end_catch");
3938
3939 // struct objc_typeinfo {
3940 // const void** vtable; // objc_ehtype_vtable + 2
3941 // const char* name; // c++ typeinfo string
3942 // Class cls;
3943 // };
3944 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3945 Int8PtrTy,
3946 ClassnfABIPtrTy,
3947 NULL);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00003948 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00003949 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003950}
3951
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003952llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3953 FinishNonFragileABIModule();
3954
3955 return NULL;
3956}
3957
3958void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3959 // nonfragile abi has no module definition.
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00003960
3961 // Build list of all implemented classe addresses in array
3962 // L_OBJC_LABEL_CLASS_$.
3963 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3964 // list of 'nonlazy' implementations (defined as those with a +load{}
3965 // method!!).
3966 unsigned NumClasses = DefinedClasses.size();
3967 if (NumClasses) {
3968 std::vector<llvm::Constant*> Symbols(NumClasses);
3969 for (unsigned i=0; i<NumClasses; i++)
3970 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3971 ObjCTypes.Int8PtrTy);
3972 llvm::Constant* Init =
3973 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3974 NumClasses),
3975 Symbols);
3976
3977 llvm::GlobalVariable *GV =
3978 new llvm::GlobalVariable(Init->getType(), false,
3979 llvm::GlobalValue::InternalLinkage,
3980 Init,
3981 "\01L_OBJC_LABEL_CLASS_$",
3982 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00003983 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00003984 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3985 UsedGlobals.push_back(GV);
3986 }
3987
3988 // Build list of all implemented category addresses in array
3989 // L_OBJC_LABEL_CATEGORY_$.
3990 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3991 // list of 'nonlazy' category implementations (defined as those with a +load{}
3992 // method!!).
3993 unsigned NumCategory = DefinedCategories.size();
3994 if (NumCategory) {
3995 std::vector<llvm::Constant*> Symbols(NumCategory);
3996 for (unsigned i=0; i<NumCategory; i++)
3997 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3998 ObjCTypes.Int8PtrTy);
3999 llvm::Constant* Init =
4000 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4001 NumCategory),
4002 Symbols);
4003
4004 llvm::GlobalVariable *GV =
4005 new llvm::GlobalVariable(Init->getType(), false,
4006 llvm::GlobalValue::InternalLinkage,
4007 Init,
4008 "\01L_OBJC_LABEL_CATEGORY_$",
4009 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00004010 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004011 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4012 UsedGlobals.push_back(GV);
4013 }
4014
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004015 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4016 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4017 std::vector<llvm::Constant*> Values(2);
4018 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004019 unsigned int flags = 0;
Fariborz Jahanian27f58962009-02-24 23:34:44 +00004020 // FIXME: Fix and continue?
4021 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4022 flags |= eImageInfo_GarbageCollected;
4023 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4024 flags |= eImageInfo_GCOnly;
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004025 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004026 llvm::Constant* Init = llvm::ConstantArray::get(
4027 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4028 Values);
4029 llvm::GlobalVariable *IMGV =
4030 new llvm::GlobalVariable(Init->getType(), false,
4031 llvm::GlobalValue::InternalLinkage,
4032 Init,
4033 "\01L_OBJC_IMAGE_INFO",
4034 &CGM.getModule());
4035 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4036 UsedGlobals.push_back(IMGV);
4037
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004038 std::vector<llvm::Constant*> Used;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004039
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004040 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4041 e = UsedGlobals.end(); i != e; ++i) {
4042 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4043 }
Fariborz Jahanianab438842009-04-14 18:41:56 +00004044
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004045 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4046 llvm::GlobalValue *GV =
4047 new llvm::GlobalVariable(AT, false,
4048 llvm::GlobalValue::AppendingLinkage,
4049 llvm::ConstantArray::get(AT, Used),
4050 "llvm.used",
4051 &CGM.getModule());
4052
4053 GV->setSection("llvm.metadata");
4054
4055}
4056
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004057// Metadata flags
4058enum MetaDataDlags {
4059 CLS = 0x0,
4060 CLS_META = 0x1,
4061 CLS_ROOT = 0x2,
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004062 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004063 CLS_EXCEPTION = 0x20
4064};
4065/// BuildClassRoTInitializer - generate meta-data for:
4066/// struct _class_ro_t {
4067/// uint32_t const flags;
4068/// uint32_t const instanceStart;
4069/// uint32_t const instanceSize;
4070/// uint32_t const reserved; // only when building for 64bit targets
4071/// const uint8_t * const ivarLayout;
4072/// const char *const name;
4073/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004074/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004075/// const struct _ivar_list_t *const ivars;
4076/// const uint8_t * const weakIvarLayout;
4077/// const struct _prop_list_t * const properties;
4078/// }
4079///
4080llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4081 unsigned flags,
4082 unsigned InstanceStart,
4083 unsigned InstanceSize,
4084 const ObjCImplementationDecl *ID) {
4085 std::string ClassName = ID->getNameAsString();
4086 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4087 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4088 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4089 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4090 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004091 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00004092 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004093 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004094 // const struct _method_list_t * const baseMethods;
4095 std::vector<llvm::Constant*> Methods;
4096 std::string MethodListName("\01l_OBJC_$_");
4097 if (flags & CLS_META) {
4098 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4099 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4100 e = ID->classmeth_end(); i != e; ++i) {
4101 // Class methods should always be defined.
4102 Methods.push_back(GetMethodConstant(*i));
4103 }
4104 } else {
4105 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4106 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4107 e = ID->instmeth_end(); i != e; ++i) {
4108 // Instance methods should always be defined.
4109 Methods.push_back(GetMethodConstant(*i));
4110 }
Fariborz Jahanian78355ec2009-01-28 22:46:49 +00004111 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4112 e = ID->propimpl_end(); i != e; ++i) {
4113 ObjCPropertyImplDecl *PID = *i;
4114
4115 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4116 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4117
4118 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4119 if (llvm::Constant *C = GetMethodConstant(MD))
4120 Methods.push_back(C);
4121 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4122 if (llvm::Constant *C = GetMethodConstant(MD))
4123 Methods.push_back(C);
4124 }
4125 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004126 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004127 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004128 "__DATA, __objc_const", Methods);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004129
4130 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4131 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4132 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4133 + OID->getNameAsString(),
4134 OID->protocol_begin(),
4135 OID->protocol_end());
4136
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004137 if (flags & CLS_META)
4138 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4139 else
4140 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004141 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00004142 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004143 if (flags & CLS_META)
4144 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4145 else
4146 Values[ 9] =
4147 EmitPropertyList(
4148 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4149 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004150 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4151 Values);
4152 llvm::GlobalVariable *CLASS_RO_GV =
4153 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4154 llvm::GlobalValue::InternalLinkage,
4155 Init,
4156 (flags & CLS_META) ?
4157 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4158 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4159 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004160 CLASS_RO_GV->setAlignment(
4161 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004162 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004163 return CLASS_RO_GV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004164
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004165}
4166
4167/// BuildClassMetaData - This routine defines that to-level meta-data
4168/// for the given ClassName for:
4169/// struct _class_t {
4170/// struct _class_t *isa;
4171/// struct _class_t * const superclass;
4172/// void *cache;
4173/// IMP *vtable;
4174/// struct class_ro_t *ro;
4175/// }
4176///
Fariborz Jahanian06726462009-01-24 21:21:53 +00004177llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4178 std::string &ClassName,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004179 llvm::Constant *IsAGV,
4180 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004181 llvm::Constant *ClassRoGV,
4182 bool HiddenVisibility) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004183 std::vector<llvm::Constant*> Values(5);
4184 Values[0] = IsAGV;
Fariborz Jahanian06726462009-01-24 21:21:53 +00004185 Values[1] = SuperClassGV
4186 ? SuperClassGV
4187 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004188 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4189 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4190 Values[4] = ClassRoGV; // &CLASS_RO_GV
4191 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4192 Values);
Daniel Dunbarabbda222009-03-01 04:40:10 +00004193 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4194 GV->setInitializer(Init);
Fariborz Jahanian7c891592009-01-31 01:07:39 +00004195 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004196 GV->setAlignment(
4197 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004198 if (HiddenVisibility)
4199 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004200 return GV;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004201}
4202
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004203void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4204 uint32_t &InstanceStart,
4205 uint32_t &InstanceSize) {
4206 // FIXME. Share this with the one in EmitIvarList.
4207 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4208
Daniel Dunbarde585722009-04-20 07:18:49 +00004209 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4210 CGM.getContext());
4211 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4212 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4213 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4214 while (countSuperClassIvars-- > 0) {
4215 lastField = firstField;
4216 ++firstField;
4217 }
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004218
4219 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4220 ifield = firstField; ifield != e; ++ifield)
4221 lastField = ifield;
4222
4223 InstanceStart = InstanceSize = 0;
4224 if (lastField != RD->field_end(CGM.getContext())) {
4225 FieldDecl *Field = *lastField;
4226 const llvm::Type *FieldTy =
4227 CGM.getTypes().ConvertTypeForMem(Field->getType());
4228 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4229 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4230 if (firstField == RD->field_end(CGM.getContext()))
4231 InstanceStart = InstanceSize;
4232 else {
4233 Field = *firstField;
4234 InstanceStart = GetIvarBaseOffset(Layout, Field);
4235 }
4236 }
4237}
4238
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004239void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4240 std::string ClassName = ID->getNameAsString();
4241 if (!ObjCEmptyCacheVar) {
4242 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004243 ObjCTypes.CacheTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004244 false,
4245 llvm::GlobalValue::ExternalLinkage,
4246 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004247 "_objc_empty_cache",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004248 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004249
4250 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004251 ObjCTypes.ImpnfABITy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004252 false,
4253 llvm::GlobalValue::ExternalLinkage,
4254 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004255 "_objc_empty_vtable",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004256 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004257 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004258 assert(ID->getClassInterface() &&
4259 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004260 // FIXME: Is this correct (That meta class size is never computed)?
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004261 uint32_t InstanceStart =
4262 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4263 uint32_t InstanceSize = InstanceStart;
4264 uint32_t flags = CLS_META;
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004265 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4266 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004267
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004268 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004269
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004270 bool classIsHidden =
4271 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004272 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004273 flags |= OBJC2_CLS_HIDDEN;
4274 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004275 // class is root
4276 flags |= CLS_ROOT;
Daniel Dunbarabbda222009-03-01 04:40:10 +00004277 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanianab438842009-04-14 18:41:56 +00004278 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004279 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004280 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004281 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4282 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4283 Root = Super;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004284 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004285 // work on super class metadata symbol.
4286 std::string SuperClassName =
4287 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanianab438842009-04-14 18:41:56 +00004288 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004289 }
4290 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4291 InstanceStart,
4292 InstanceSize,ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004293 std::string TClassName = ObjCMetaClassName + ClassName;
4294 llvm::GlobalVariable *MetaTClass =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004295 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4296 classIsHidden);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004297
Fariborz Jahanian06726462009-01-24 21:21:53 +00004298 // Metadata for the class
4299 flags = CLS;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004300 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004301 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbarc2129532009-04-08 04:21:03 +00004302
4303 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4304 flags |= CLS_EXCEPTION;
4305
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004306 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004307 flags |= CLS_ROOT;
4308 SuperClassGV = 0;
Chris Lattner9fe470d2009-04-19 06:02:28 +00004309 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004310 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004311 std::string RootClassName =
Fariborz Jahanian06726462009-01-24 21:21:53 +00004312 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbarabbda222009-03-01 04:40:10 +00004313 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004314 }
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004315 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004316 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianddd2fdd2009-01-24 23:43:01 +00004317 InstanceStart,
4318 InstanceSize,
4319 ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004320
4321 TClassName = ObjCClassName + ClassName;
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004322 llvm::GlobalVariable *ClassMD =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004323 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4324 classIsHidden);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004325 DefinedClasses.push_back(ClassMD);
Daniel Dunbarc2129532009-04-08 04:21:03 +00004326
4327 // Force the definition of the EHType if necessary.
4328 if (flags & CLS_EXCEPTION)
4329 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004330}
4331
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004332/// GenerateProtocolRef - This routine is called to generate code for
4333/// a protocol reference expression; as in:
4334/// @code
4335/// @protocol(Proto1);
4336/// @endcode
4337/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4338/// which will hold address of the protocol meta-data.
4339///
4340llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4341 const ObjCProtocolDecl *PD) {
4342
Fariborz Jahaniand3243322009-04-10 18:47:34 +00004343 // This routine is called for @protocol only. So, we must build definition
4344 // of protocol's meta-data (not a reference to it!)
4345 //
4346 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004347 ObjCTypes.ExternalProtocolPtrTy);
4348
4349 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4350 ProtocolName += PD->getNameAsCString();
4351
4352 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4353 if (PTGV)
4354 return Builder.CreateLoad(PTGV, false, "tmp");
4355 PTGV = new llvm::GlobalVariable(
4356 Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00004357 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004358 Init,
4359 ProtocolName,
4360 &CGM.getModule());
4361 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4362 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4363 UsedGlobals.push_back(PTGV);
4364 return Builder.CreateLoad(PTGV, false, "tmp");
4365}
4366
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004367/// GenerateCategory - Build metadata for a category implementation.
4368/// struct _category_t {
4369/// const char * const name;
4370/// struct _class_t *const cls;
4371/// const struct _method_list_t * const instance_methods;
4372/// const struct _method_list_t * const class_methods;
4373/// const struct _protocol_list_t * const protocols;
4374/// const struct _prop_list_t * const properties;
4375/// }
4376///
4377void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4378{
4379 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004380 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4381 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004382 "_$_" + OCD->getNameAsString());
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004383 std::string ExtClassName(getClassSymbolPrefix() +
4384 Interface->getNameAsString());
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004385
4386 std::vector<llvm::Constant*> Values(6);
4387 Values[0] = GetClassName(OCD->getIdentifier());
4388 // meta-class entry symbol
Daniel Dunbarabbda222009-03-01 04:40:10 +00004389 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004390 Values[1] = ClassGV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004391 std::vector<llvm::Constant*> Methods;
4392 std::string MethodListName(Prefix);
4393 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4394 "_$_" + OCD->getNameAsString();
4395
4396 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4397 e = OCD->instmeth_end(); i != e; ++i) {
4398 // Instance methods should always be defined.
4399 Methods.push_back(GetMethodConstant(*i));
4400 }
4401
4402 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004403 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004404 Methods);
4405
4406 MethodListName = Prefix;
4407 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4408 OCD->getNameAsString();
4409 Methods.clear();
4410 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4411 e = OCD->classmeth_end(); i != e; ++i) {
4412 // Class methods should always be defined.
4413 Methods.push_back(GetMethodConstant(*i));
4414 }
4415
4416 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004417 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004418 Methods);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004419 const ObjCCategoryDecl *Category =
4420 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian8c7904b2009-02-13 17:52:22 +00004421 if (Category) {
4422 std::string ExtName(Interface->getNameAsString() + "_$_" +
4423 OCD->getNameAsString());
4424 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4425 + Interface->getNameAsString() + "_$_"
4426 + Category->getNameAsString(),
4427 Category->protocol_begin(),
4428 Category->protocol_end());
4429 Values[5] =
4430 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4431 OCD, Category, ObjCTypes);
4432 }
4433 else {
4434 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4435 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4436 }
4437
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004438 llvm::Constant *Init =
4439 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4440 Values);
4441 llvm::GlobalVariable *GCATV
4442 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4443 false,
4444 llvm::GlobalValue::InternalLinkage,
4445 Init,
4446 ExtCatName,
4447 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004448 GCATV->setAlignment(
4449 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004450 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004451 UsedGlobals.push_back(GCATV);
4452 DefinedCategories.push_back(GCATV);
4453}
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004454
4455/// GetMethodConstant - Return a struct objc_method constant for the
4456/// given method if it has been defined. The result is null if the
4457/// method has not been defined. The return value has type MethodPtrTy.
4458llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4459 const ObjCMethodDecl *MD) {
4460 // FIXME: Use DenseMap::lookup
4461 llvm::Function *Fn = MethodDefinitions[MD];
4462 if (!Fn)
4463 return 0;
4464
4465 std::vector<llvm::Constant*> Method(3);
4466 Method[0] =
4467 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4468 ObjCTypes.SelectorPtrTy);
4469 Method[1] = GetMethodVarType(MD);
4470 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4471 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4472}
4473
4474/// EmitMethodList - Build meta-data for method declarations
4475/// struct _method_list_t {
4476/// uint32_t entsize; // sizeof(struct _objc_method)
4477/// uint32_t method_count;
4478/// struct _objc_method method_list[method_count];
4479/// }
4480///
4481llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4482 const std::string &Name,
4483 const char *Section,
4484 const ConstantVector &Methods) {
4485 // Return null for empty list.
4486 if (Methods.empty())
4487 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4488
4489 std::vector<llvm::Constant*> Values(3);
4490 // sizeof(struct _objc_method)
4491 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4492 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4493 // method_count
4494 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4495 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4496 Methods.size());
4497 Values[2] = llvm::ConstantArray::get(AT, Methods);
4498 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4499
4500 llvm::GlobalVariable *GV =
4501 new llvm::GlobalVariable(Init->getType(), false,
4502 llvm::GlobalValue::InternalLinkage,
4503 Init,
4504 Name,
4505 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004506 GV->setAlignment(
4507 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004508 GV->setSection(Section);
4509 UsedGlobals.push_back(GV);
4510 return llvm::ConstantExpr::getBitCast(GV,
4511 ObjCTypes.MethodListnfABIPtrTy);
4512}
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004513
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004514/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4515/// the given ivar.
4516///
4517llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00004518 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004519 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004520 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004521 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4522 '.' + Ivar->getNameAsString();
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004523 llvm::GlobalVariable *IvarOffsetGV =
4524 CGM.getModule().getGlobalVariable(Name);
4525 if (!IvarOffsetGV)
4526 IvarOffsetGV =
4527 new llvm::GlobalVariable(ObjCTypes.LongTy,
4528 false,
4529 llvm::GlobalValue::ExternalLinkage,
4530 0,
4531 Name,
4532 &CGM.getModule());
4533 return IvarOffsetGV;
4534}
4535
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004536llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004537 const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004538 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004539 unsigned long int Offset) {
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004540 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4541 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4542 Offset));
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004543 IvarOffsetGV->setAlignment(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004544 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004545
4546 // FIXME: This matches gcc, but shouldn't the visibility be set on
4547 // the use as well (i.e., in ObjCIvarOffsetVariable).
4548 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4549 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4550 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004551 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004552 else
Fariborz Jahanian745fd892009-04-06 18:30:00 +00004553 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004554 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian55343922009-02-03 00:09:52 +00004555 return IvarOffsetGV;
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004556}
4557
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004558/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar3c190812009-04-18 08:51:00 +00004559/// implementation. The return value has type
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004560/// IvarListnfABIPtrTy.
4561/// struct _ivar_t {
4562/// unsigned long int *offset; // pointer to ivar offset location
4563/// char *name;
4564/// char *type;
4565/// uint32_t alignment;
4566/// uint32_t size;
4567/// }
4568/// struct _ivar_list_t {
4569/// uint32 entsize; // sizeof(struct _ivar_t)
4570/// uint32 count;
4571/// struct _iver_t list[count];
4572/// }
4573///
Daniel Dunbar356f0742009-04-20 06:54:31 +00004574
4575void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4576 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4577 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4578 E = OID->ivar_end(); I != E; ++I) {
4579 // Ignore unnamed bit-fields.
4580 if (!(*I)->getDeclName())
4581 continue;
4582
4583 Res.push_back(*I);
4584 }
4585
4586 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4587 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4588 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4589 Res.push_back(IV);
4590}
4591
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004592llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4593 const ObjCImplementationDecl *ID) {
4594
4595 std::vector<llvm::Constant*> Ivars, Ivar(5);
4596
4597 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4598 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4599
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004600 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00004601 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00004602
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004603 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanianfbf44642009-03-31 18:11:23 +00004604 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar356f0742009-04-20 06:54:31 +00004605 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian84c45692009-04-01 19:37:34 +00004606
Daniel Dunbar356f0742009-04-20 06:54:31 +00004607 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4608 ObjCIvarDecl *IVD = OIvars[i];
4609 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004610 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00004611 GetIvarBaseOffset(Layout, Field));
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004612 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel593a07a2009-03-04 18:21:39 +00004613 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004614 const llvm::Type *FieldTy =
4615 CGM.getTypes().ConvertTypeForMem(Field->getType());
4616 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4617 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4618 Field->getType().getTypePtr()) >> 3;
4619 Align = llvm::Log2_32(Align);
4620 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004621 // NOTE. Size of a bitfield does not match gcc's, because of the
4622 // way bitfields are treated special in each. But I am told that
4623 // 'size' for bitfield ivars is ignored by the runtime so it does
4624 // not matter. If it matters, there is enough info to get the
4625 // bitfield right!
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004626 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4627 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4628 }
4629 // Return null for empty list.
4630 if (Ivars.empty())
4631 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4632 std::vector<llvm::Constant*> Values(3);
4633 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4634 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4635 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4636 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4637 Ivars.size());
4638 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4639 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4640 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4641 llvm::GlobalVariable *GV =
4642 new llvm::GlobalVariable(Init->getType(), false,
4643 llvm::GlobalValue::InternalLinkage,
4644 Init,
4645 Prefix + OID->getNameAsString(),
4646 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004647 GV->setAlignment(
4648 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004649 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004650
4651 UsedGlobals.push_back(GV);
4652 return llvm::ConstantExpr::getBitCast(GV,
4653 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004654}
4655
4656llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4657 const ObjCProtocolDecl *PD) {
4658 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4659
4660 if (!Entry) {
4661 // We use the initializer as a marker of whether this is a forward
4662 // reference or not. At module finalization we add the empty
4663 // contents for protocols which were referenced but never defined.
4664 Entry =
4665 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4666 llvm::GlobalValue::ExternalLinkage,
4667 0,
4668 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4669 &CGM.getModule());
4670 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4671 UsedGlobals.push_back(Entry);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004672 }
4673
4674 return Entry;
4675}
4676
4677/// GetOrEmitProtocol - Generate the protocol meta-data:
4678/// @code
4679/// struct _protocol_t {
4680/// id isa; // NULL
4681/// const char * const protocol_name;
4682/// const struct _protocol_list_t * protocol_list; // super protocols
4683/// const struct method_list_t * const instance_methods;
4684/// const struct method_list_t * const class_methods;
4685/// const struct method_list_t *optionalInstanceMethods;
4686/// const struct method_list_t *optionalClassMethods;
4687/// const struct _prop_list_t * properties;
4688/// const uint32_t size; // sizeof(struct _protocol_t)
4689/// const uint32_t flags; // = 0
4690/// }
4691/// @endcode
4692///
4693
4694llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4695 const ObjCProtocolDecl *PD) {
4696 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4697
4698 // Early exit if a defining object has already been generated.
4699 if (Entry && Entry->hasInitializer())
4700 return Entry;
4701
4702 const char *ProtocolName = PD->getNameAsCString();
4703
4704 // Construct method lists.
4705 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4706 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004707 for (ObjCProtocolDecl::instmeth_iterator
4708 i = PD->instmeth_begin(CGM.getContext()),
4709 e = PD->instmeth_end(CGM.getContext());
4710 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004711 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004712 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004713 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4714 OptInstanceMethods.push_back(C);
4715 } else {
4716 InstanceMethods.push_back(C);
4717 }
4718 }
4719
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004720 for (ObjCProtocolDecl::classmeth_iterator
4721 i = PD->classmeth_begin(CGM.getContext()),
4722 e = PD->classmeth_end(CGM.getContext());
4723 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004724 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004725 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004726 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4727 OptClassMethods.push_back(C);
4728 } else {
4729 ClassMethods.push_back(C);
4730 }
4731 }
4732
4733 std::vector<llvm::Constant*> Values(10);
4734 // isa is NULL
4735 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4736 Values[1] = GetClassName(PD->getIdentifier());
4737 Values[2] = EmitProtocolList(
4738 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4739 PD->protocol_begin(),
4740 PD->protocol_end());
4741
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004742 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004743 + PD->getNameAsString(),
4744 "__DATA, __objc_const",
4745 InstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004746 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004747 + PD->getNameAsString(),
4748 "__DATA, __objc_const",
4749 ClassMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004750 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004751 + PD->getNameAsString(),
4752 "__DATA, __objc_const",
4753 OptInstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004754 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004755 + PD->getNameAsString(),
4756 "__DATA, __objc_const",
4757 OptClassMethods);
4758 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4759 0, PD, ObjCTypes);
4760 uint32_t Size =
4761 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4762 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4763 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4764 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4765 Values);
4766
4767 if (Entry) {
4768 // Already created, fix the linkage and update the initializer.
Mike Stump36dbf222009-03-07 16:33:28 +00004769 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004770 Entry->setInitializer(Init);
4771 } else {
4772 Entry =
4773 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004774 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004775 Init,
4776 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4777 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004778 Entry->setAlignment(
4779 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004780 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004781 }
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004782 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4783
4784 // Use this protocol meta-data to build protocol list table in section
4785 // __DATA, __objc_protolist
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004786 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004787 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004788 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004789 Entry,
4790 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4791 +ProtocolName,
4792 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004793 PTGV->setAlignment(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004794 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00004795 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004796 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4797 UsedGlobals.push_back(PTGV);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004798 return Entry;
4799}
4800
4801/// EmitProtocolList - Generate protocol list meta-data:
4802/// @code
4803/// struct _protocol_list_t {
4804/// long protocol_count; // Note, this is 32/64 bit
4805/// struct _protocol_t[protocol_count];
4806/// }
4807/// @endcode
4808///
4809llvm::Constant *
4810CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4811 ObjCProtocolDecl::protocol_iterator begin,
4812 ObjCProtocolDecl::protocol_iterator end) {
4813 std::vector<llvm::Constant*> ProtocolRefs;
4814
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004815 // Just return null for empty protocol lists
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004816 if (begin == end)
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004817 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4818
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004819 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004820 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4821 if (GV)
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004822 return llvm::ConstantExpr::getBitCast(GV,
4823 ObjCTypes.ProtocolListnfABIPtrTy);
4824
4825 for (; begin != end; ++begin)
4826 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4827
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004828 // This list is null terminated.
4829 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004830 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004831
4832 std::vector<llvm::Constant*> Values(2);
4833 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4834 Values[1] =
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004835 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004836 ProtocolRefs.size()),
4837 ProtocolRefs);
4838
4839 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4840 GV = new llvm::GlobalVariable(Init->getType(), false,
4841 llvm::GlobalValue::InternalLinkage,
4842 Init,
4843 Name,
4844 &CGM.getModule());
4845 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004846 GV->setAlignment(
4847 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004848 UsedGlobals.push_back(GV);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004849 return llvm::ConstantExpr::getBitCast(GV,
4850 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004851}
4852
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004853/// GetMethodDescriptionConstant - This routine build following meta-data:
4854/// struct _objc_method {
4855/// SEL _cmd;
4856/// char *method_type;
4857/// char *_imp;
4858/// }
4859
4860llvm::Constant *
4861CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4862 std::vector<llvm::Constant*> Desc(3);
4863 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4864 ObjCTypes.SelectorPtrTy);
4865 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004866 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004867 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4868 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4869}
Fariborz Jahanian55343922009-02-03 00:09:52 +00004870
4871/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4872/// This code gen. amounts to generating code for:
4873/// @code
4874/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4875/// @encode
4876///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004877LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004878 CodeGen::CodeGenFunction &CGF,
4879 QualType ObjectTy,
4880 llvm::Value *BaseValue,
4881 const ObjCIvarDecl *Ivar,
4882 const FieldDecl *Field,
4883 unsigned CVRQualifiers) {
4884 assert(ObjectTy->isObjCInterfaceType() &&
4885 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00004886 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004887 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004888
Fariborz Jahanian55343922009-02-03 00:09:52 +00004889 // (char *) BaseValue
Chris Lattnerbb87be22009-04-17 17:46:19 +00004890 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian55343922009-02-03 00:09:52 +00004891 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4892 // (char*)BaseValue + Offset_symbol
4893 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4894 // (type *)((char*)BaseValue + Offset_symbol)
4895 const llvm::Type *IvarTy =
Chris Lattnerbb87be22009-04-17 17:46:19 +00004896 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian55343922009-02-03 00:09:52 +00004897 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4898 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004899
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004900 if (Ivar->isBitField()) {
Chris Lattnerbb87be22009-04-17 17:46:19 +00004901 QualType FieldTy = Field->getType();
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004902 CodeGenTypes::BitFieldInfo bitFieldInfo =
4903 CGM.getTypes().getBitFieldInfo(Field);
4904 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattnerbb87be22009-04-17 17:46:19 +00004905 FieldTy->isSignedIntegerType(),
4906 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004907 }
4908
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004909 LValue LV = LValue::MakeAddr(V,
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00004910 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4911 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004912 LValue::SetObjCIvar(LV, true);
4913 return LV;
Fariborz Jahanian55343922009-02-03 00:09:52 +00004914}
4915
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004916llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4917 CodeGen::CodeGenFunction &CGF,
4918 ObjCInterfaceDecl *Interface,
4919 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004920 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4921 false, "ivar");
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004922}
4923
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004924CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4925 CodeGen::CodeGenFunction &CGF,
4926 QualType ResultType,
4927 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004928 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004929 QualType Arg0Ty,
4930 bool IsSuper,
4931 const CallArgList &CallArgs) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004932 // FIXME. Even though IsSuper is passes. This function doese not
4933 // handle calls to 'super' receivers.
4934 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004935 llvm::Value *Arg0 = Receiver;
4936 if (!IsSuper)
4937 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004938
4939 // Find the message function name.
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00004940 // FIXME. This is too much work to get the ABI-specific result type
4941 // needed to find the message name.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004942 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4943 llvm::SmallVector<QualType, 16>());
4944 llvm::Constant *Fn;
4945 std::string Name("\01l_");
4946 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004947#if 0
4948 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004949 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4950 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4951 // FIXME. Is there a better way of getting these names.
4952 // They are available in RuntimeFunctions vector pair.
4953 Name += "objc_msgSendId_stret_fixup";
4954 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004955 else
4956#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004957 if (IsSuper) {
4958 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4959 Name += "objc_msgSendSuper2_stret_fixup";
4960 }
4961 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004962 {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004963 Fn = ObjCTypes.MessageSendStretFixupFn;
4964 Name += "objc_msgSend_stret_fixup";
4965 }
4966 }
Fariborz Jahanianbea03192009-02-05 19:35:43 +00004967 else if (ResultType->isFloatingType() &&
4968 // Selection of frret API only happens in 32bit nonfragile ABI.
4969 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004970 Fn = ObjCTypes.MessageSendFpretFixupFn;
4971 Name += "objc_msgSend_fpret_fixup";
4972 }
4973 else {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004974#if 0
4975// unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004976 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4977 Fn = ObjCTypes.MessageSendIdFixupFn;
4978 Name += "objc_msgSendId_fixup";
4979 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004980 else
4981#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004982 if (IsSuper) {
4983 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4984 Name += "objc_msgSendSuper2_fixup";
4985 }
4986 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004987 {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004988 Fn = ObjCTypes.MessageSendFixupFn;
4989 Name += "objc_msgSend_fixup";
4990 }
4991 }
4992 Name += '_';
4993 std::string SelName(Sel.getAsString());
4994 // Replace all ':' in selector name with '_' ouch!
4995 for(unsigned i = 0; i < SelName.size(); i++)
4996 if (SelName[i] == ':')
4997 SelName[i] = '_';
4998 Name += SelName;
4999 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5000 if (!GV) {
Daniel Dunbar4993e292009-04-15 19:03:14 +00005001 // Build message ref table entry.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005002 std::vector<llvm::Constant*> Values(2);
5003 Values[0] = Fn;
5004 Values[1] = GetMethodVarName(Sel);
5005 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5006 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00005007 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005008 Init,
5009 Name,
5010 &CGM.getModule());
5011 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbara405f782009-04-15 19:04:46 +00005012 GV->setAlignment(16);
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005013 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005014 }
5015 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005016
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005017 CallArgList ActualArgs;
5018 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5019 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5020 ObjCTypes.MessageRefCPtrTy));
5021 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005022 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5023 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5024 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanianf3c17752009-02-14 21:25:36 +00005025 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005026 Callee = CGF.Builder.CreateBitCast(Callee,
5027 llvm::PointerType::getUnqual(FTy));
5028 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005029}
5030
5031/// Generate code for a message send expression in the nonfragile abi.
5032CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5033 CodeGen::CodeGenFunction &CGF,
5034 QualType ResultType,
5035 Selector Sel,
5036 llvm::Value *Receiver,
5037 bool IsClassMessage,
5038 const CallArgList &CallArgs) {
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005039 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005040 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005041 false, CallArgs);
5042}
5043
Daniel Dunbarabbda222009-03-01 04:40:10 +00005044llvm::GlobalVariable *
Fariborz Jahanianab438842009-04-14 18:41:56 +00005045CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005046 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5047
Daniel Dunbar66b47512009-03-02 05:18:14 +00005048 if (!GV) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005049 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5050 llvm::GlobalValue::ExternalLinkage,
5051 0, Name, &CGM.getModule());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005052 }
5053
5054 return GV;
5055}
5056
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005057llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005058 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005059 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5060
5061 if (!Entry) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005062 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005063 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005064 Entry =
5065 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5066 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005067 ClassGV,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005068 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005069 &CGM.getModule());
5070 Entry->setAlignment(
5071 CGM.getTargetData().getPrefTypeAlignment(
5072 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar3c190812009-04-18 08:51:00 +00005073 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5074 UsedGlobals.push_back(Entry);
5075 }
5076
5077 return Builder.CreateLoad(Entry, false, "tmp");
5078}
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005079
Daniel Dunbar3c190812009-04-18 08:51:00 +00005080llvm::Value *
5081CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5082 const ObjCInterfaceDecl *ID) {
5083 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5084
5085 if (!Entry) {
5086 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5087 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5088 Entry =
5089 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5090 llvm::GlobalValue::InternalLinkage,
5091 ClassGV,
5092 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5093 &CGM.getModule());
5094 Entry->setAlignment(
5095 CGM.getTargetData().getPrefTypeAlignment(
5096 ObjCTypes.ClassnfABIPtrTy));
5097 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005098 UsedGlobals.push_back(Entry);
5099 }
5100
5101 return Builder.CreateLoad(Entry, false, "tmp");
5102}
5103
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005104/// EmitMetaClassRef - Return a Value * of the address of _class_t
5105/// meta-data
5106///
5107llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5108 const ObjCInterfaceDecl *ID) {
5109 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5110 if (Entry)
5111 return Builder.CreateLoad(Entry, false, "tmp");
5112
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005113 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005114 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005115 Entry =
5116 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5117 llvm::GlobalValue::InternalLinkage,
5118 MetaClassGV,
5119 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5120 &CGM.getModule());
5121 Entry->setAlignment(
5122 CGM.getTargetData().getPrefTypeAlignment(
5123 ObjCTypes.ClassnfABIPtrTy));
5124
Daniel Dunbar4993e292009-04-15 19:03:14 +00005125 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005126 UsedGlobals.push_back(Entry);
5127
5128 return Builder.CreateLoad(Entry, false, "tmp");
5129}
5130
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005131/// GetClass - Return a reference to the class for the given interface
5132/// decl.
5133llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5134 const ObjCInterfaceDecl *ID) {
5135 return EmitClassRef(Builder, ID);
5136}
5137
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005138/// Generates a message send where the super is the receiver. This is
5139/// a message send to self with special delivery semantics indicating
5140/// which class's method should be called.
5141CodeGen::RValue
5142CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5143 QualType ResultType,
5144 Selector Sel,
5145 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005146 bool isCategoryImpl,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005147 llvm::Value *Receiver,
5148 bool IsClassMessage,
5149 const CodeGen::CallArgList &CallArgs) {
5150 // ...
5151 // Create and init a super structure; this is a (receiver, class)
5152 // pair we will pass to objc_msgSendSuper.
5153 llvm::Value *ObjCSuper =
5154 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5155
5156 llvm::Value *ReceiverAsObject =
5157 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5158 CGF.Builder.CreateStore(ReceiverAsObject,
5159 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5160
5161 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005162 llvm::Value *Target;
5163 if (IsClassMessage) {
5164 if (isCategoryImpl) {
5165 // Message sent to "super' in a class method defined in
5166 // a category implementation.
Daniel Dunbar3c190812009-04-18 08:51:00 +00005167 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005168 Target = CGF.Builder.CreateStructGEP(Target, 0);
5169 Target = CGF.Builder.CreateLoad(Target);
5170 }
5171 else
5172 Target = EmitMetaClassRef(CGF.Builder, Class);
5173 }
5174 else
Daniel Dunbar3c190812009-04-18 08:51:00 +00005175 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005176
5177 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5178 // and ObjCTypes types.
5179 const llvm::Type *ClassTy =
5180 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5181 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5182 CGF.Builder.CreateStore(Target,
5183 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5184
5185 return EmitMessageSend(CGF, ResultType, Sel,
5186 ObjCSuper, ObjCTypes.SuperPtrCTy,
5187 true, CallArgs);
5188}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005189
5190llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5191 Selector Sel) {
5192 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5193
5194 if (!Entry) {
5195 llvm::Constant *Casted =
5196 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5197 ObjCTypes.SelectorPtrTy);
5198 Entry =
5199 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5200 llvm::GlobalValue::InternalLinkage,
5201 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5202 &CGM.getModule());
5203 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5204 UsedGlobals.push_back(Entry);
5205 }
5206
5207 return Builder.CreateLoad(Entry, false, "tmp");
5208}
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005209/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5210/// objc_assign_ivar (id src, id *dst)
5211///
5212void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5213 llvm::Value *src, llvm::Value *dst)
5214{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005215 const llvm::Type * SrcTy = src->getType();
5216 if (!isa<llvm::PointerType>(SrcTy)) {
5217 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5218 assert(Size <= 8 && "does not support size > 8");
5219 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5220 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005221 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5222 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005223 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5224 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5225 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5226 src, dst, "assignivar");
5227 return;
5228}
5229
5230/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5231/// objc_assign_strongCast (id src, id *dst)
5232///
5233void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5234 CodeGen::CodeGenFunction &CGF,
5235 llvm::Value *src, llvm::Value *dst)
5236{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005237 const llvm::Type * SrcTy = src->getType();
5238 if (!isa<llvm::PointerType>(SrcTy)) {
5239 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5240 assert(Size <= 8 && "does not support size > 8");
5241 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5242 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005243 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5244 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005245 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5246 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5247 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5248 src, dst, "weakassign");
5249 return;
5250}
5251
5252/// EmitObjCWeakRead - Code gen for loading value of a __weak
5253/// object: objc_read_weak (id *src)
5254///
5255llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5256 CodeGen::CodeGenFunction &CGF,
5257 llvm::Value *AddrWeakObj)
5258{
Eli Friedmanf8466232009-03-07 03:57:15 +00005259 const llvm::Type* DestTy =
5260 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005261 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5262 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5263 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00005264 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005265 return read_weak;
5266}
5267
5268/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5269/// objc_assign_weak (id src, id *dst)
5270///
5271void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5272 llvm::Value *src, llvm::Value *dst)
5273{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005274 const llvm::Type * SrcTy = src->getType();
5275 if (!isa<llvm::PointerType>(SrcTy)) {
5276 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5277 assert(Size <= 8 && "does not support size > 8");
5278 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5279 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005280 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5281 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005282 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5283 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00005284 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005285 src, dst, "weakassign");
5286 return;
5287}
5288
5289/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5290/// objc_assign_global (id src, id *dst)
5291///
5292void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5293 llvm::Value *src, llvm::Value *dst)
5294{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005295 const llvm::Type * SrcTy = src->getType();
5296 if (!isa<llvm::PointerType>(SrcTy)) {
5297 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5298 assert(Size <= 8 && "does not support size > 8");
5299 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5300 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005301 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5302 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005303 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5304 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5305 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5306 src, dst, "globalassign");
5307 return;
5308}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005309
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005310void
5311CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5312 const Stmt &S) {
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005313 bool isTry = isa<ObjCAtTryStmt>(S);
5314 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5315 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005316 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005317 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005318 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005319 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5320
5321 // For @synchronized, call objc_sync_enter(sync.expr). The
5322 // evaluation of the expression must occur before we enter the
5323 // @synchronized. We can safely avoid a temp here because jumps into
5324 // @synchronized are illegal & this will dominate uses.
5325 llvm::Value *SyncArg = 0;
5326 if (!isTry) {
5327 SyncArg =
5328 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5329 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00005330 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005331 }
5332
5333 // Push an EH context entry, used for handling rethrows and jumps
5334 // through finally.
5335 CGF.PushCleanupBlock(FinallyBlock);
5336
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005337 CGF.setInvokeDest(TryHandler);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005338
5339 CGF.EmitBlock(TryBlock);
5340 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5341 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5342 CGF.EmitBranchThroughCleanup(FinallyEnd);
5343
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005344 // Emit the exception handler.
5345
5346 CGF.EmitBlock(TryHandler);
5347
5348 llvm::Value *llvm_eh_exception =
5349 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5350 llvm::Value *llvm_eh_selector_i64 =
5351 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5352 llvm::Value *llvm_eh_typeid_for_i64 =
5353 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5354 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5355 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5356
5357 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5358 SelectorArgs.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005359 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005360
5361 // Construct the lists of (type, catch body) to handle.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005362 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005363 bool HasCatchAll = false;
5364 if (isTry) {
5365 if (const ObjCAtCatchStmt* CatchStmt =
5366 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5367 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005368 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005369 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005370
5371 // catch(...) always matches.
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005372 if (!CatchDecl) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005373 // Use i8* null here to signal this is a catch all, not a cleanup.
5374 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5375 SelectorArgs.push_back(Null);
5376 HasCatchAll = true;
5377 break;
5378 }
5379
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005380 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5381 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005382 llvm::Value *IDEHType =
5383 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5384 if (!IDEHType)
5385 IDEHType =
5386 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5387 llvm::GlobalValue::ExternalLinkage,
5388 0, "OBJC_EHTYPE_id", &CGM.getModule());
5389 SelectorArgs.push_back(IDEHType);
5390 HasCatchAll = true;
5391 break;
5392 }
5393
5394 // All other types should be Objective-C interface pointer types.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005395 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005396 assert(PT && "Invalid @catch type.");
5397 const ObjCInterfaceType *IT =
5398 PT->getPointeeType()->getAsObjCInterfaceType();
5399 assert(IT && "Invalid @catch type.");
Daniel Dunbarc2129532009-04-08 04:21:03 +00005400 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005401 SelectorArgs.push_back(EHType);
5402 }
5403 }
5404 }
5405
5406 // We use a cleanup unless there was already a catch all.
5407 if (!HasCatchAll) {
5408 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005409 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005410 }
5411
5412 llvm::Value *Selector =
5413 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5414 SelectorArgs.begin(), SelectorArgs.end(),
5415 "selector");
5416 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005417 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005418 const Stmt *CatchBody = Handlers[i].second;
5419
5420 llvm::BasicBlock *Next = 0;
5421
5422 // The last handler always matches.
5423 if (i + 1 != e) {
5424 assert(CatchParam && "Only last handler can be a catch all.");
5425
5426 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5427 Next = CGF.createBasicBlock("catch.next");
5428 llvm::Value *Id =
5429 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5430 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5431 ObjCTypes.Int8PtrTy));
5432 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5433 Match, Next);
5434
5435 CGF.EmitBlock(Match);
5436 }
5437
5438 if (CatchBody) {
5439 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5440 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5441
5442 // Cleanups must call objc_end_catch.
5443 //
5444 // FIXME: It seems incorrect for objc_begin_catch to be inside
5445 // this context, but this matches gcc.
5446 CGF.PushCleanupBlock(MatchEnd);
5447 CGF.setInvokeDest(MatchHandler);
5448
5449 llvm::Value *ExcObject =
5450 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5451
5452 // Bind the catch parameter if it exists.
5453 if (CatchParam) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005454 ExcObject =
5455 CGF.Builder.CreateBitCast(ExcObject,
5456 CGF.ConvertType(CatchParam->getType()));
5457 // CatchParam is a ParmVarDecl because of the grammar
5458 // construction used to handle this, but for codegen purposes
5459 // we treat this as a local decl.
5460 CGF.EmitLocalBlockVarDecl(*CatchParam);
5461 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005462 }
5463
5464 CGF.ObjCEHValueStack.push_back(ExcObject);
5465 CGF.EmitStmt(CatchBody);
5466 CGF.ObjCEHValueStack.pop_back();
5467
5468 CGF.EmitBranchThroughCleanup(FinallyEnd);
5469
5470 CGF.EmitBlock(MatchHandler);
5471
5472 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5473 // We are required to emit this call to satisfy LLVM, even
5474 // though we don't use the result.
5475 llvm::SmallVector<llvm::Value*, 8> Args;
5476 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005477 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005478 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5479 0));
5480 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5481 CGF.Builder.CreateStore(Exc, RethrowPtr);
5482 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5483
5484 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5485
5486 CGF.EmitBlock(MatchEnd);
5487
5488 // Unfortunately, we also have to generate another EH frame here
5489 // in case this throws.
5490 llvm::BasicBlock *MatchEndHandler =
5491 CGF.createBasicBlock("match.end.handler");
5492 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5493 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5494 Cont, MatchEndHandler,
5495 Args.begin(), Args.begin());
5496
5497 CGF.EmitBlock(Cont);
5498 if (Info.SwitchBlock)
5499 CGF.EmitBlock(Info.SwitchBlock);
5500 if (Info.EndBlock)
5501 CGF.EmitBlock(Info.EndBlock);
5502
5503 CGF.EmitBlock(MatchEndHandler);
5504 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5505 // We are required to emit this call to satisfy LLVM, even
5506 // though we don't use the result.
5507 Args.clear();
5508 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005509 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005510 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5511 0));
5512 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5513 CGF.Builder.CreateStore(Exc, RethrowPtr);
5514 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5515
5516 if (Next)
5517 CGF.EmitBlock(Next);
5518 } else {
5519 assert(!Next && "catchup should be last handler.");
5520
5521 CGF.Builder.CreateStore(Exc, RethrowPtr);
5522 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5523 }
5524 }
5525
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005526 // Pop the cleanup entry, the @finally is outside this cleanup
5527 // scope.
5528 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5529 CGF.setInvokeDest(PrevLandingPad);
5530
5531 CGF.EmitBlock(FinallyBlock);
5532
5533 if (isTry) {
5534 if (const ObjCAtFinallyStmt* FinallyStmt =
5535 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5536 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5537 } else {
5538 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5539 // @synchronized.
5540 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005541 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005542
5543 if (Info.SwitchBlock)
5544 CGF.EmitBlock(Info.SwitchBlock);
5545 if (Info.EndBlock)
5546 CGF.EmitBlock(Info.EndBlock);
5547
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005548 // Branch around the rethrow code.
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005549 CGF.EmitBranch(FinallyEnd);
5550
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005551 CGF.EmitBlock(FinallyRethrow);
5552 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5553 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005554 CGF.Builder.CreateUnreachable();
5555
5556 CGF.EmitBlock(FinallyEnd);
5557}
5558
Anders Carlsson1cf75362009-02-16 22:59:18 +00005559/// EmitThrowStmt - Generate code for a throw statement.
5560void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5561 const ObjCAtThrowStmt &S) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005562 llvm::Value *Exception;
Anders Carlsson1cf75362009-02-16 22:59:18 +00005563 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005564 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlsson1cf75362009-02-16 22:59:18 +00005565 } else {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005566 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5567 "Unexpected rethrow outside @catch block.");
5568 Exception = CGF.ObjCEHValueStack.back();
Anders Carlsson1cf75362009-02-16 22:59:18 +00005569 }
5570
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005571 llvm::Value *ExceptionAsObject =
5572 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5573 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5574 if (InvokeDest) {
5575 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5576 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5577 Cont, InvokeDest,
5578 &ExceptionAsObject, &ExceptionAsObject + 1);
5579 CGF.EmitBlock(Cont);
5580 } else
5581 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5582 CGF.Builder.CreateUnreachable();
5583
Anders Carlsson1cf75362009-02-16 22:59:18 +00005584 // Clear the insertion point to indicate we are in unreachable code.
5585 CGF.Builder.ClearInsertionPoint();
5586}
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005587
5588llvm::Value *
Daniel Dunbarc2129532009-04-08 04:21:03 +00005589CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5590 bool ForDefinition) {
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005591 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005592
Daniel Dunbarc2129532009-04-08 04:21:03 +00005593 // If we don't need a definition, return the entry if found or check
5594 // if we use an external reference.
5595 if (!ForDefinition) {
5596 if (Entry)
5597 return Entry;
Daniel Dunbarafac9be2009-04-07 06:43:45 +00005598
Daniel Dunbarc2129532009-04-08 04:21:03 +00005599 // If this type (or a super class) has the __objc_exception__
5600 // attribute, emit an external reference.
5601 if (hasObjCExceptionAttribute(ID))
5602 return Entry =
5603 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5604 llvm::GlobalValue::ExternalLinkage,
5605 0,
5606 (std::string("OBJC_EHTYPE_$_") +
5607 ID->getIdentifier()->getName()),
5608 &CGM.getModule());
5609 }
5610
5611 // Otherwise we need to either make a new entry or fill in the
5612 // initializer.
5613 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005614 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005615 std::string VTableName = "objc_ehtype_vtable";
5616 llvm::GlobalVariable *VTableGV =
5617 CGM.getModule().getGlobalVariable(VTableName);
5618 if (!VTableGV)
5619 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5620 llvm::GlobalValue::ExternalLinkage,
5621 0, VTableName, &CGM.getModule());
5622
5623 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5624
5625 std::vector<llvm::Constant*> Values(3);
5626 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5627 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005628 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005629 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5630
Daniel Dunbarc2129532009-04-08 04:21:03 +00005631 if (Entry) {
5632 Entry->setInitializer(Init);
5633 } else {
5634 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5635 llvm::GlobalValue::WeakAnyLinkage,
5636 Init,
5637 (std::string("OBJC_EHTYPE_$_") +
5638 ID->getIdentifier()->getName()),
5639 &CGM.getModule());
5640 }
5641
Daniel Dunbar8394fda2009-04-14 06:00:08 +00005642 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005643 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarc2129532009-04-08 04:21:03 +00005644 Entry->setAlignment(8);
5645
5646 if (ForDefinition) {
5647 Entry->setSection("__DATA,__objc_const");
5648 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5649 } else {
5650 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5651 }
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005652
5653 return Entry;
5654}
Anders Carlsson1cf75362009-02-16 22:59:18 +00005655
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00005656/* *** */
5657
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00005658CodeGen::CGObjCRuntime *
5659CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00005660 return new CGObjCMac(CGM);
5661}
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005662
5663CodeGen::CGObjCRuntime *
Fariborz Jahaniand0374812009-01-22 23:02:58 +00005664CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00005665 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005666}