blob: 58cfe8e16332fc7947da69db7c76713c0a55631e [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,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000704 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000705 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
706 ObjCInterfaceDecl *Interface,
707 const ObjCIvarDecl *Ivar);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000708};
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000709
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000710class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000711private:
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000712 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000713 llvm::GlobalVariable* ObjCEmptyCacheVar;
714 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000715
Daniel Dunbar3c190812009-04-18 08:51:00 +0000716 /// SuperClassReferences - uniqued super class references.
717 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
718
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000719 /// MetaClassReferences - uniqued meta class references.
720 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000721
722 /// EHTypeReferences - uniqued class ehtype references.
723 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000724
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000725 /// FinishNonFragileABIModule - Write out global data structures at the end of
726 /// processing a translation unit.
727 void FinishNonFragileABIModule();
Daniel Dunbarc2129532009-04-08 04:21:03 +0000728
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000729 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
730 unsigned InstanceStart,
731 unsigned InstanceSize,
732 const ObjCImplementationDecl *ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +0000733 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
734 llvm::Constant *IsAGV,
735 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +0000736 llvm::Constant *ClassRoGV,
737 bool HiddenVisibility);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000738
739 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
740
Fariborz Jahanian151747b2009-01-30 00:46:37 +0000741 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
742
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000743 /// EmitMethodList - Emit the method list for the given
744 /// implementation. The return value has type MethodListnfABITy.
745 llvm::Constant *EmitMethodList(const std::string &Name,
746 const char *Section,
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +0000747 const ConstantVector &Methods);
748 /// EmitIvarList - Emit the ivar list for the given
749 /// implementation. If ForClass is true the list of class ivars
750 /// (i.e. metaclass ivars) is emitted, otherwise the list of
751 /// interface ivars will be emitted. The return value has type
752 /// IvarListnfABIPtrTy.
753 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000754
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000755 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +0000756 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +0000757 unsigned long int offset);
758
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000759 /// GetOrEmitProtocol - Get the protocol object for the given
760 /// declaration, emitting it if necessary. The return value has type
761 /// ProtocolPtrTy.
762 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
763
764 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
765 /// object for the given declaration, emitting it if needed. These
766 /// forward references will be filled in with empty bodies if no
767 /// definition is seen. The return value has type ProtocolPtrTy.
768 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
769
770 /// EmitProtocolList - Generate the list of referenced
771 /// protocols. The return value has type ProtocolListPtrTy.
772 llvm::Constant *EmitProtocolList(const std::string &Name,
773 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000774 ObjCProtocolDecl::protocol_iterator end);
775
776 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
777 QualType ResultType,
778 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000779 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000780 QualType Arg0Ty,
781 bool IsSuper,
782 const CallArgList &CallArgs);
Daniel Dunbarabbda222009-03-01 04:40:10 +0000783
784 /// GetClassGlobal - Return the global variable for the Objective-C
785 /// class of the given name.
Fariborz Jahanianab438842009-04-14 18:41:56 +0000786 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
787
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000788 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar3c190812009-04-18 08:51:00 +0000789 /// for the given class reference.
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000790 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +0000791 const ObjCInterfaceDecl *ID);
792
793 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
794 /// for the given super class reference.
795 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
796 const ObjCInterfaceDecl *ID);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000797
798 /// EmitMetaClassRef - Return a Value * of the address of _class_t
799 /// meta-data
800 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
801 const ObjCInterfaceDecl *ID);
802
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000803 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
804 /// the given ivar.
805 ///
Daniel Dunbar07d204a2009-04-19 00:31:15 +0000806 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +0000807 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +0000808 const ObjCIvarDecl *Ivar);
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000809
Fariborz Jahanianebb82c62009-02-11 20:51:17 +0000810 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
811 /// for the given selector.
812 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000813
Daniel Dunbarc2129532009-04-08 04:21:03 +0000814 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000815 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbarc2129532009-04-08 04:21:03 +0000816 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
817 bool ForDefinition);
Daniel Dunbara2d275d2009-04-07 05:48:37 +0000818
819 const char *getMetaclassSymbolPrefix() const {
820 return "OBJC_METACLASS_$_";
821 }
Daniel Dunbarc0318b22009-03-02 06:08:11 +0000822
Daniel Dunbara2d275d2009-04-07 05:48:37 +0000823 const char *getClassSymbolPrefix() const {
824 return "OBJC_CLASS_$_";
825 }
826
Daniel Dunbarecb5d402009-04-19 23:41:48 +0000827 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
828 uint32_t &InstanceStart,
829 uint32_t &InstanceSize);
830
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000831public:
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000832 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000833 // FIXME. All stubs for now!
834 virtual llvm::Function *ModuleInitFunction();
835
836 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
837 QualType ResultType,
838 Selector Sel,
839 llvm::Value *Receiver,
840 bool IsClassMessage,
Fariborz Jahanian7e881162009-02-04 00:22:57 +0000841 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000842
843 virtual CodeGen::RValue
844 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
845 QualType ResultType,
846 Selector Sel,
847 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000848 bool isCategoryImpl,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000849 llvm::Value *Receiver,
850 bool IsClassMessage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +0000851 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000852
853 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian917c0402009-02-05 20:41:40 +0000854 const ObjCInterfaceDecl *ID);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000855
856 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanianebb82c62009-02-11 20:51:17 +0000857 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000858
Fariborz Jahanianfe49a092009-01-26 18:32:24 +0000859 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000860
861 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000862 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +0000863 const ObjCProtocolDecl *PD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000864
Chris Lattneraea1aee2009-03-22 21:03:39 +0000865 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000866 return ObjCTypes.GetPropertyFn;
867 }
Chris Lattneraea1aee2009-03-22 21:03:39 +0000868 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000869 return ObjCTypes.SetPropertyFn;
870 }
Chris Lattneraea1aee2009-03-22 21:03:39 +0000871 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar978d2be2009-02-16 18:48:45 +0000872 return ObjCTypes.EnumerationMutationFn;
873 }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000874
875 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000876 const Stmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000877 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlsson1cf75362009-02-16 22:59:18 +0000878 const ObjCAtThrowStmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000879 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000880 llvm::Value *AddrWeakObj);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000881 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000882 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000883 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000884 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000885 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000886 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000887 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +0000888 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000889 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
890 QualType ObjectTy,
891 llvm::Value *BaseValue,
892 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000893 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000894 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
895 ObjCInterfaceDecl *Interface,
896 const ObjCIvarDecl *Ivar);
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000897};
898
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000899} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000900
901/* *** Helper Functions *** */
902
903/// getConstantGEP() - Help routine to construct simple GEPs.
904static llvm::Constant *getConstantGEP(llvm::Constant *C,
905 unsigned idx0,
906 unsigned idx1) {
907 llvm::Value *Idxs[] = {
908 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
909 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
910 };
911 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
912}
913
Daniel Dunbarc2129532009-04-08 04:21:03 +0000914/// hasObjCExceptionAttribute - Return true if this class or any super
915/// class has the __objc_exception__ attribute.
916static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbar78582862009-04-13 21:08:27 +0000917 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbarc2129532009-04-08 04:21:03 +0000918 return true;
919 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
920 return hasObjCExceptionAttribute(Super);
921 return false;
922}
923
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000924/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000925
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000926CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
927 ObjCTypes(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000928{
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000929 ObjCABI = 1;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000930 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000931}
932
Daniel Dunbar434627a2008-08-16 00:25:02 +0000933/// GetClass - Return a reference to the class for the given interface
934/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000935llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000936 const ObjCInterfaceDecl *ID) {
937 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000938}
939
940/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000941llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000942 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000943}
944
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000945/// Generate a constant CFString object.
946/*
947 struct __builtin_CFString {
948 const int *isa; // point to __CFConstantStringClassReference
949 int flags;
950 const char *str;
951 long length;
952 };
953*/
954
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000955llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000956 const ObjCStringLiteral *SL) {
Steve Naroff9a744e52009-04-01 13:55:36 +0000957 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000958}
959
960/// Generates a message send where the super is the receiver. This is
961/// a message send to self with special delivery semantics indicating
962/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000963CodeGen::RValue
964CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000965 QualType ResultType,
966 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000967 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000968 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000969 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000970 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000971 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +0000972 // Create and init a super structure; this is a (receiver, class)
973 // pair we will pass to objc_msgSendSuper.
974 llvm::Value *ObjCSuper =
975 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
976 llvm::Value *ReceiverAsObject =
977 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
978 CGF.Builder.CreateStore(ReceiverAsObject,
979 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +0000980
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000981 // If this is a class message the metaclass is passed as the target.
982 llvm::Value *Target;
983 if (IsClassMessage) {
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000984 if (isCategoryImpl) {
985 // Message sent to 'super' in a class method defined in a category
986 // implementation requires an odd treatment.
987 // If we are in a class method, we must retrieve the
988 // _metaclass_ for the current class, pointed at by
989 // the class's "isa" pointer. The following assumes that
990 // isa" is the first ivar in a class (which it must be).
991 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
992 Target = CGF.Builder.CreateStructGEP(Target, 0);
993 Target = CGF.Builder.CreateLoad(Target);
994 }
995 else {
996 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
997 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
998 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
999 Target = Super;
1000 }
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001001 } else {
1002 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1003 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001004 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1005 // and ObjCTypes types.
1006 const llvm::Type *ClassTy =
1007 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001008 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001009 CGF.Builder.CreateStore(Target,
1010 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1011
Daniel Dunbardd851282008-08-30 05:35:15 +00001012 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001013 ObjCSuper, ObjCTypes.SuperPtrCTy,
1014 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001015}
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001016
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001017/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001018CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001019 QualType ResultType,
1020 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001021 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001022 bool IsClassMessage,
1023 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001024 llvm::Value *Arg0 =
1025 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +00001026 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001027 Arg0, CGF.getContext().getObjCIdType(),
1028 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001029}
1030
1031CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001032 QualType ResultType,
1033 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001034 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001035 QualType Arg0Ty,
1036 bool IsSuper,
1037 const CallArgList &CallArgs) {
1038 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001039 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1040 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1041 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001042 CGF.getContext().getObjCSelType()));
1043 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +00001044
Daniel Dunbar34bda882009-02-02 23:23:47 +00001045 CodeGenTypes &Types = CGM.getTypes();
1046 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1047 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001048
1049 llvm::Constant *Fn;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001050 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001051 Fn = ObjCTypes.getSendStretFn(IsSuper);
1052 } else if (ResultType->isFloatingType()) {
1053 // FIXME: Sadly, this is wrong. This actually depends on the
1054 // architecture. This happens to be right for x86-32 though.
1055 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1056 } else {
1057 Fn = ObjCTypes.getSendFn(IsSuper);
1058 }
Daniel Dunbara9976a22008-09-10 07:00:50 +00001059 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001060 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001061}
1062
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001063llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001064 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +00001065 // FIXME: I don't understand why gcc generates this, or where it is
1066 // resolved. Investigate. Its also wasteful to look this up over and
1067 // over.
1068 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1069
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001070 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1071 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001072}
1073
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001074void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001075 // FIXME: We shouldn't need this, the protocol decl should contain
1076 // enough information to tell us whether this was a declaration or a
1077 // definition.
1078 DefinedProtocols.insert(PD->getIdentifier());
1079
1080 // If we have generated a forward reference to this protocol, emit
1081 // it now. Otherwise do nothing, the protocol objects are lazily
1082 // emitted.
1083 if (Protocols.count(PD->getIdentifier()))
1084 GetOrEmitProtocol(PD);
1085}
1086
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001087llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001088 if (DefinedProtocols.count(PD->getIdentifier()))
1089 return GetOrEmitProtocol(PD);
1090 return GetOrEmitProtocolRef(PD);
1091}
1092
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001093/*
1094 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1095 struct _objc_protocol {
1096 struct _objc_protocol_extension *isa;
1097 char *protocol_name;
1098 struct _objc_protocol_list *protocol_list;
1099 struct _objc__method_prototype_list *instance_methods;
1100 struct _objc__method_prototype_list *class_methods
1101 };
1102
1103 See EmitProtocolExtension().
1104*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001105llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1106 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1107
1108 // Early exit if a defining object has already been generated.
1109 if (Entry && Entry->hasInitializer())
1110 return Entry;
1111
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001112 // FIXME: I don't understand why gcc generates this, or where it is
1113 // resolved. Investigate. Its also wasteful to look this up over and
1114 // over.
1115 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1116
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001117 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001118
1119 // Construct method lists.
1120 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1121 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001122 for (ObjCProtocolDecl::instmeth_iterator
1123 i = PD->instmeth_begin(CGM.getContext()),
1124 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001125 ObjCMethodDecl *MD = *i;
1126 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1127 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1128 OptInstanceMethods.push_back(C);
1129 } else {
1130 InstanceMethods.push_back(C);
1131 }
1132 }
1133
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001134 for (ObjCProtocolDecl::classmeth_iterator
1135 i = PD->classmeth_begin(CGM.getContext()),
1136 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001137 ObjCMethodDecl *MD = *i;
1138 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1139 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1140 OptClassMethods.push_back(C);
1141 } else {
1142 ClassMethods.push_back(C);
1143 }
1144 }
1145
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001146 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001147 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001148 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001149 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001150 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001151 PD->protocol_begin(),
1152 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001153 Values[3] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001154 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1155 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001156 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1157 InstanceMethods);
1158 Values[4] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001159 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1160 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001161 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1162 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001163 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1164 Values);
1165
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001166 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001167 // Already created, fix the linkage and update the initializer.
1168 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001169 Entry->setInitializer(Init);
1170 } else {
1171 Entry =
1172 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1173 llvm::GlobalValue::InternalLinkage,
1174 Init,
1175 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1176 &CGM.getModule());
1177 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001178 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001179 UsedGlobals.push_back(Entry);
1180 // FIXME: Is this necessary? Why only for protocol?
1181 Entry->setAlignment(4);
1182 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001183
1184 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001185}
1186
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001187llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001188 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1189
1190 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001191 // We use the initializer as a marker of whether this is a forward
1192 // reference or not. At module finalization we add the empty
1193 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001194 Entry =
1195 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001196 llvm::GlobalValue::ExternalLinkage,
1197 0,
Chris Lattner271d4c22008-11-24 05:29:24 +00001198 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001199 &CGM.getModule());
1200 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001201 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001202 UsedGlobals.push_back(Entry);
1203 // FIXME: Is this necessary? Why only for protocol?
1204 Entry->setAlignment(4);
1205 }
1206
1207 return Entry;
1208}
1209
1210/*
1211 struct _objc_protocol_extension {
1212 uint32_t size;
1213 struct objc_method_description_list *optional_instance_methods;
1214 struct objc_method_description_list *optional_class_methods;
1215 struct objc_property_list *instance_properties;
1216 };
1217*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001218llvm::Constant *
1219CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1220 const ConstantVector &OptInstanceMethods,
1221 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001222 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001223 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001224 std::vector<llvm::Constant*> Values(4);
1225 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001226 Values[1] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001227 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1228 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001229 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1230 OptInstanceMethods);
1231 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001232 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1233 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001234 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1235 OptClassMethods);
Chris Lattner271d4c22008-11-24 05:29:24 +00001236 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1237 PD->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001238 0, PD, ObjCTypes);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001239
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001240 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001241 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1242 Values[3]->isNullValue())
1243 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1244
1245 llvm::Constant *Init =
1246 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001247
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001248 // No special section, but goes in llvm.used
1249 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1250 Init,
1251 0, 0, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001252}
1253
1254/*
1255 struct objc_protocol_list {
1256 struct objc_protocol_list *next;
1257 long count;
1258 Protocol *list[];
1259 };
1260*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001261llvm::Constant *
1262CGObjCMac::EmitProtocolList(const std::string &Name,
1263 ObjCProtocolDecl::protocol_iterator begin,
1264 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001265 std::vector<llvm::Constant*> ProtocolRefs;
1266
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001267 for (; begin != end; ++begin)
1268 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001269
1270 // Just return null for empty protocol lists
1271 if (ProtocolRefs.empty())
1272 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1273
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001274 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001275 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1276
1277 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001278 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001279 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1280 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1281 Values[2] =
1282 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1283 ProtocolRefs.size()),
1284 ProtocolRefs);
1285
1286 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1287 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001288 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001289 4, false);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001290 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1291}
1292
1293/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001294 struct _objc_property {
1295 const char * const name;
1296 const char * const attributes;
1297 };
1298
1299 struct _objc_property_list {
1300 uint32_t entsize; // sizeof (struct _objc_property)
1301 uint32_t prop_count;
1302 struct _objc_property[prop_count];
1303 };
1304*/
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001305llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1306 const Decl *Container,
1307 const ObjCContainerDecl *OCD,
1308 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001309 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001310 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1311 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroffdcf1e842009-01-11 12:47:58 +00001312 const ObjCPropertyDecl *PD = *I;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001313 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001314 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001315 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1316 Prop));
1317 }
1318
1319 // Return null for empty list.
1320 if (Properties.empty())
1321 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1322
1323 unsigned PropertySize =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001324 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001325 std::vector<llvm::Constant*> Values(3);
1326 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1327 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1328 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1329 Properties.size());
1330 Values[2] = llvm::ConstantArray::get(AT, Properties);
1331 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1332
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001333 llvm::GlobalVariable *GV =
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001334 CreateMetadataVar(Name, Init,
1335 (ObjCABI == 2) ? "__DATA, __objc_const" :
1336 "__OBJC,__property,regular,no_dead_strip",
1337 (ObjCABI == 2) ? 8 : 4,
1338 true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001339 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001340}
1341
1342/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001343 struct objc_method_description_list {
1344 int count;
1345 struct objc_method_description list[];
1346 };
1347*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001348llvm::Constant *
1349CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1350 std::vector<llvm::Constant*> Desc(2);
1351 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1352 ObjCTypes.SelectorPtrTy);
1353 Desc[1] = GetMethodVarType(MD);
1354 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1355 Desc);
1356}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001357
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001358llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1359 const char *Section,
1360 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001361 // Return null for empty list.
1362 if (Methods.empty())
1363 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1364
1365 std::vector<llvm::Constant*> Values(2);
1366 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1367 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1368 Methods.size());
1369 Values[1] = llvm::ConstantArray::get(AT, Methods);
1370 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1371
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001372 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001373 return llvm::ConstantExpr::getBitCast(GV,
1374 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001375}
1376
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001377/*
1378 struct _objc_category {
1379 char *category_name;
1380 char *class_name;
1381 struct _objc_method_list *instance_methods;
1382 struct _objc_method_list *class_methods;
1383 struct _objc_protocol_list *protocols;
1384 uint32_t size; // <rdar://4585769>
1385 struct _objc_property_list *instance_properties;
1386 };
1387 */
Daniel Dunbarac93e472008-08-15 22:20:32 +00001388void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbard8439f22009-01-12 21:08:18 +00001389 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001390
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001391 // FIXME: This is poor design, the OCD should have a pointer to the
1392 // category decl. Additionally, note that Category can be null for
1393 // the @implementation w/o an @interface case. Sema should just
1394 // create one for us as it does for @implementation so everyone else
1395 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001396 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001397 const ObjCCategoryDecl *Category =
1398 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattner271d4c22008-11-24 05:29:24 +00001399 std::string ExtName(Interface->getNameAsString() + "_" +
1400 OCD->getNameAsString());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001401
Daniel Dunbar12996f52008-08-26 21:51:14 +00001402 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1403 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1404 e = OCD->instmeth_end(); i != e; ++i) {
1405 // Instance methods should always be defined.
1406 InstanceMethods.push_back(GetMethodConstant(*i));
1407 }
1408 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1409 e = OCD->classmeth_end(); i != e; ++i) {
1410 // Class methods should always be defined.
1411 ClassMethods.push_back(GetMethodConstant(*i));
1412 }
1413
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001414 std::vector<llvm::Constant*> Values(7);
1415 Values[0] = GetClassName(OCD->getIdentifier());
1416 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001417 Values[2] =
1418 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1419 ExtName,
1420 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001421 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001422 Values[3] =
1423 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001424 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001425 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001426 if (Category) {
1427 Values[4] =
1428 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1429 Category->protocol_begin(),
1430 Category->protocol_end());
1431 } else {
1432 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1433 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001434 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001435
1436 // If there is no category @interface then there can be no properties.
1437 if (Category) {
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001438 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001439 OCD, Category, ObjCTypes);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001440 } else {
1441 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1442 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001443
1444 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1445 Values);
1446
1447 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001448 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1449 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001450 4, true);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001451 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001452}
1453
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001454// FIXME: Get from somewhere?
1455enum ClassFlags {
1456 eClassFlags_Factory = 0x00001,
1457 eClassFlags_Meta = 0x00002,
1458 // <rdr://5142207>
1459 eClassFlags_HasCXXStructors = 0x02000,
1460 eClassFlags_Hidden = 0x20000,
1461 eClassFlags_ABI2_Hidden = 0x00010,
1462 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1463};
1464
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001465/*
1466 struct _objc_class {
1467 Class isa;
1468 Class super_class;
1469 const char *name;
1470 long version;
1471 long info;
1472 long instance_size;
1473 struct _objc_ivar_list *ivars;
1474 struct _objc_method_list *methods;
1475 struct _objc_cache *cache;
1476 struct _objc_protocol_list *protocols;
1477 // Objective-C 1.0 extensions (<rdr://4585769>)
1478 const char *ivar_layout;
1479 struct _objc_class_ext *ext;
1480 };
1481
1482 See EmitClassExtension();
1483 */
1484void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001485 DefinedSymbols.insert(ID->getIdentifier());
1486
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001487 std::string ClassName = ID->getNameAsString();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001488 // FIXME: Gross
1489 ObjCInterfaceDecl *Interface =
1490 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001491 llvm::Constant *Protocols =
Chris Lattner271d4c22008-11-24 05:29:24 +00001492 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001493 Interface->protocol_begin(),
1494 Interface->protocol_end());
Chris Lattner9fe470d2009-04-19 06:02:28 +00001495 const llvm::Type *InterfaceTy;
1496 if (Interface->isForwardDecl())
1497 InterfaceTy = llvm::StructType::get(NULL, NULL);
1498 else
1499 InterfaceTy =
Chris Lattner46ee0f32009-04-01 06:23:52 +00001500 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001501 unsigned Flags = eClassFlags_Factory;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001502 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001503
1504 // FIXME: Set CXX-structors flag.
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001505 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001506 Flags |= eClassFlags_Hidden;
1507
Daniel Dunbar12996f52008-08-26 21:51:14 +00001508 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1509 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1510 e = ID->instmeth_end(); i != e; ++i) {
1511 // Instance methods should always be defined.
1512 InstanceMethods.push_back(GetMethodConstant(*i));
1513 }
1514 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1515 e = ID->classmeth_end(); i != e; ++i) {
1516 // Class methods should always be defined.
1517 ClassMethods.push_back(GetMethodConstant(*i));
1518 }
1519
1520 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1521 e = ID->propimpl_end(); i != e; ++i) {
1522 ObjCPropertyImplDecl *PID = *i;
1523
1524 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1525 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1526
1527 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1528 if (llvm::Constant *C = GetMethodConstant(MD))
1529 InstanceMethods.push_back(C);
1530 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1531 if (llvm::Constant *C = GetMethodConstant(MD))
1532 InstanceMethods.push_back(C);
1533 }
1534 }
1535
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001536 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001537 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001538 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001539 // Record a reference to the super class.
1540 LazySymbols.insert(Super->getIdentifier());
1541
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001542 Values[ 1] =
1543 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1544 ObjCTypes.ClassPtrTy);
1545 } else {
1546 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1547 }
1548 Values[ 2] = GetClassName(ID->getIdentifier());
1549 // Version is always 0.
1550 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1551 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1552 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001553 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001554 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001555 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001556 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001557 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001558 // cache is always NULL.
1559 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1560 Values[ 9] = Protocols;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001561 // FIXME: Set ivar_layout
Fariborz Jahanian738ee712009-03-25 22:36:49 +00001562 // Values[10] = BuildIvarLayout(ID, true);
1563 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001564 Values[11] = EmitClassExtension(ID);
1565 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1566 Values);
1567
1568 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001569 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1570 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001571 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001572 DefinedClasses.push_back(GV);
1573}
1574
1575llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1576 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001577 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001578 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001579 unsigned Flags = eClassFlags_Meta;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001580 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001581
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001582 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001583 Flags |= eClassFlags_Hidden;
1584
1585 std::vector<llvm::Constant*> Values(12);
1586 // The isa for the metaclass is the root of the hierarchy.
1587 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1588 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1589 Root = Super;
1590 Values[ 0] =
1591 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1592 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001593 // The super class for the metaclass is emitted as the name of the
1594 // super class. The runtime fixes this up to point to the
1595 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001596 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1597 Values[ 1] =
1598 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1599 ObjCTypes.ClassPtrTy);
1600 } else {
1601 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1602 }
1603 Values[ 2] = GetClassName(ID->getIdentifier());
1604 // Version is always 0.
1605 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1606 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1607 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001608 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001609 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001610 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001611 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001612 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001613 // cache is always NULL.
1614 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1615 Values[ 9] = Protocols;
1616 // ivar_layout for metaclass is always NULL.
1617 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1618 // The class extension is always unused for metaclasses.
1619 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1620 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1621 Values);
1622
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001623 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001624 Name += ID->getNameAsCString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001625
1626 // Check for a forward reference.
1627 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1628 if (GV) {
1629 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1630 "Forward metaclass reference has incorrect type.");
1631 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1632 GV->setInitializer(Init);
1633 } else {
1634 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1635 llvm::GlobalValue::InternalLinkage,
1636 Init, Name,
1637 &CGM.getModule());
1638 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001639 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001640 GV->setAlignment(4);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001641 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001642
1643 return GV;
1644}
1645
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001646llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattner271d4c22008-11-24 05:29:24 +00001647 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001648
1649 // FIXME: Should we look these up somewhere other than the
1650 // module. Its a bit silly since we only generate these while
1651 // processing an implementation, so exactly one pointer would work
1652 // if know when we entered/exitted an implementation block.
1653
1654 // Check for an existing forward reference.
Fariborz Jahanian5fe09f72009-01-07 20:11:22 +00001655 // Previously, metaclass with internal linkage may have been defined.
1656 // pass 'true' as 2nd argument so it is returned.
1657 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001658 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1659 "Forward metaclass reference has incorrect type.");
1660 return GV;
1661 } else {
1662 // Generate as an external reference to keep a consistent
1663 // module. This will be patched up when we emit the metaclass.
1664 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1665 llvm::GlobalValue::ExternalLinkage,
1666 0,
1667 Name,
1668 &CGM.getModule());
1669 }
1670}
1671
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001672/*
1673 struct objc_class_ext {
1674 uint32_t size;
1675 const char *weak_ivar_layout;
1676 struct _objc_property_list *properties;
1677 };
1678*/
1679llvm::Constant *
1680CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1681 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001682 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001683
1684 std::vector<llvm::Constant*> Values(3);
1685 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001686 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00001687 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00001688 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001689 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001690 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001691
1692 // Return null if no extension bits are used.
1693 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1694 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1695
1696 llvm::Constant *Init =
1697 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001698 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001699 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1700 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001701}
1702
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001703/// getInterfaceDeclForIvar - Get the interface declaration node where
1704/// this ivar is declared in.
1705/// FIXME. Ideally, this info should be in the ivar node. But currently
1706/// it is not and prevailing wisdom is that ASTs should not have more
1707/// info than is absolutely needed, even though this info reflects the
1708/// source language.
1709///
1710static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1711 const ObjCInterfaceDecl *OI,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001712 const ObjCIvarDecl *IVD,
1713 ASTContext &Context) {
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001714 if (!OI)
1715 return 0;
1716 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1717 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1718 E = OI->ivar_end(); I != E; ++I)
1719 if ((*I)->getIdentifier() == IVD->getIdentifier())
1720 return OI;
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00001721 // look into properties.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001722 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1723 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00001724 ObjCPropertyDecl *PDecl = (*I);
1725 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1726 if (IV->getIdentifier() == IVD->getIdentifier())
1727 return OI;
1728 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001729 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001730}
1731
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001732/*
1733 struct objc_ivar {
1734 char *ivar_name;
1735 char *ivar_type;
1736 int ivar_offset;
1737 };
1738
1739 struct objc_ivar_list {
1740 int ivar_count;
1741 struct objc_ivar list[count];
1742 };
1743 */
1744llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001745 bool ForClass) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001746 std::vector<llvm::Constant*> Ivars, Ivar(3);
1747
1748 // When emitting the root class GCC emits ivar entries for the
1749 // actual class structure. It is not clear if we need to follow this
1750 // behavior; for now lets try and get away with not doing it. If so,
1751 // the cleanest solution would be to make up an ObjCInterfaceDecl
1752 // for the class.
1753 if (ForClass)
1754 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001755
1756 ObjCInterfaceDecl *OID =
1757 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00001758 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001759
Daniel Dunbar356f0742009-04-20 06:54:31 +00001760 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1761 GetNamedIvarList(OID, OIvars);
1762
1763 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1764 ObjCIvarDecl *IVD = OIvars[i];
1765 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar356f0742009-04-20 06:54:31 +00001766 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel593a07a2009-03-04 18:21:39 +00001767 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar72878722009-04-20 20:18:54 +00001768 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
1769 GetIvarBaseOffset(Layout, Field));
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001770 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001771 }
1772
1773 // Return null for empty list.
1774 if (Ivars.empty())
1775 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1776
1777 std::vector<llvm::Constant*> Values(2);
1778 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1779 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1780 Ivars.size());
1781 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1782 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1783
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001784 llvm::GlobalVariable *GV;
1785 if (ForClass)
1786 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar56756c32009-03-09 22:18:41 +00001787 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1788 4, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001789 else
1790 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1791 + ID->getNameAsString(),
1792 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001793 4, true);
1794 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001795}
1796
1797/*
1798 struct objc_method {
1799 SEL method_name;
1800 char *method_types;
1801 void *method;
1802 };
1803
1804 struct objc_method_list {
1805 struct objc_method_list *obsolete;
1806 int count;
1807 struct objc_method methods_list[count];
1808 };
1809*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00001810
1811/// GetMethodConstant - Return a struct objc_method constant for the
1812/// given method if it has been defined. The result is null if the
1813/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001814llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001815 // FIXME: Use DenseMap::lookup
1816 llvm::Function *Fn = MethodDefinitions[MD];
1817 if (!Fn)
1818 return 0;
1819
1820 std::vector<llvm::Constant*> Method(3);
1821 Method[0] =
1822 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1823 ObjCTypes.SelectorPtrTy);
1824 Method[1] = GetMethodVarType(MD);
1825 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1826 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1827}
1828
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001829llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1830 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001831 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001832 // Return null for empty list.
1833 if (Methods.empty())
1834 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1835
1836 std::vector<llvm::Constant*> Values(3);
1837 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1838 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1839 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1840 Methods.size());
1841 Values[2] = llvm::ConstantArray::get(AT, Methods);
1842 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1843
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001844 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001845 return llvm::ConstantExpr::getBitCast(GV,
1846 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00001847}
1848
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001849llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001850 const ObjCContainerDecl *CD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00001851 std::string Name;
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00001852 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarace33292008-08-16 03:19:19 +00001853
Daniel Dunbar34bda882009-02-02 23:23:47 +00001854 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001855 const llvm::FunctionType *MethodTy =
Daniel Dunbar34bda882009-02-02 23:23:47 +00001856 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarace33292008-08-16 03:19:19 +00001857 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001858 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00001859 llvm::GlobalValue::InternalLinkage,
1860 Name,
1861 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00001862 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00001863
Daniel Dunbarace33292008-08-16 03:19:19 +00001864 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001865}
1866
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00001867uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +00001868 const FieldDecl *Field) {
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00001869 if (!Field->isBitField())
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001870 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1871
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00001872 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001873 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1874 // FIXME: The "field no" for bitfields is something completely
1875 // different; it is the offset in multiples of the base type size!
1876 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1877 const llvm::Type *Ty =
1878 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1879 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1880 return (Offset + BFI.Begin) / 8;
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00001881}
1882
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00001883/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001884uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1885 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +00001886 const FieldDecl *Field) {
Fariborz Jahanian31614742009-04-20 22:03:45 +00001887 // Is this a c struct?
1888 if (!OI)
1889 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001890 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnerd391dab2009-03-31 08:33:16 +00001891 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1892 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00001893}
1894
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001895llvm::GlobalVariable *
1896CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1897 llvm::Constant *Init,
1898 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +00001899 unsigned Align,
1900 bool AddToUsed) {
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001901 const llvm::Type *Ty = Init->getType();
1902 llvm::GlobalVariable *GV =
1903 new llvm::GlobalVariable(Ty, false,
1904 llvm::GlobalValue::InternalLinkage,
1905 Init,
1906 Name,
1907 &CGM.getModule());
1908 if (Section)
1909 GV->setSection(Section);
Daniel Dunbareddddd22009-03-09 20:50:13 +00001910 if (Align)
1911 GV->setAlignment(Align);
1912 if (AddToUsed)
Daniel Dunbarc4594f22009-03-09 20:09:19 +00001913 UsedGlobals.push_back(GV);
1914 return GV;
1915}
1916
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001917llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001918 // Abuse this interface function as a place to finalize.
1919 FinishModule();
1920
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001921 return NULL;
1922}
1923
Chris Lattneraea1aee2009-03-22 21:03:39 +00001924llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbarf7103722008-09-24 03:38:44 +00001925 return ObjCTypes.GetPropertyFn;
1926}
1927
Chris Lattneraea1aee2009-03-22 21:03:39 +00001928llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbarf7103722008-09-24 03:38:44 +00001929 return ObjCTypes.SetPropertyFn;
1930}
1931
Chris Lattneraea1aee2009-03-22 21:03:39 +00001932llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson58d16242008-08-31 04:05:03 +00001933 return ObjCTypes.EnumerationMutationFn;
1934}
1935
Daniel Dunbar83544842008-09-28 01:03:14 +00001936/*
1937
1938Objective-C setjmp-longjmp (sjlj) Exception Handling
1939--
1940
1941The basic framework for a @try-catch-finally is as follows:
1942{
1943 objc_exception_data d;
1944 id _rethrow = null;
Anders Carlsson8559de12009-02-07 21:26:04 +00001945 bool _call_try_exit = true;
1946
Daniel Dunbar83544842008-09-28 01:03:14 +00001947 objc_exception_try_enter(&d);
1948 if (!setjmp(d.jmp_buf)) {
1949 ... try body ...
1950 } else {
1951 // exception path
1952 id _caught = objc_exception_extract(&d);
1953
1954 // enter new try scope for handlers
1955 if (!setjmp(d.jmp_buf)) {
1956 ... match exception and execute catch blocks ...
1957
1958 // fell off end, rethrow.
1959 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001960 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001961 } else {
1962 // exception in catch block
1963 _rethrow = objc_exception_extract(&d);
Anders Carlsson8559de12009-02-07 21:26:04 +00001964 _call_try_exit = false;
1965 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001966 }
1967 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001968 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001969
1970finally:
Anders Carlsson8559de12009-02-07 21:26:04 +00001971 if (_call_try_exit)
1972 objc_exception_try_exit(&d);
1973
Daniel Dunbar83544842008-09-28 01:03:14 +00001974 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001975 ... dispatch to finally destination ...
1976
1977finally_rethrow:
1978 objc_exception_throw(_rethrow);
1979
1980finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00001981}
1982
1983This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001984uses _rethrow to determine if objc_exception_try_exit should be called
1985and if the object should be rethrown. This breaks in the face of
1986throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00001987
1988We specialize this framework for a few particular circumstances:
1989
1990 - If there are no catch blocks, then we avoid emitting the second
1991 exception handling context.
1992
1993 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1994 e)) we avoid emitting the code to rethrow an uncaught exception.
1995
1996 - FIXME: If there is no @finally block we can do a few more
1997 simplifications.
1998
1999Rethrows and Jumps-Through-Finally
2000--
2001
2002Support for implicit rethrows and jumping through the finally block is
2003handled by storing the current exception-handling context in
2004ObjCEHStack.
2005
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002006In order to implement proper @finally semantics, we support one basic
2007mechanism for jumping through the finally block to an arbitrary
2008destination. Constructs which generate exits from a @try or @catch
2009block use this mechanism to implement the proper semantics by chaining
2010jumps, as necessary.
2011
2012This mechanism works like the one used for indirect goto: we
2013arbitrarily assign an ID to each destination and store the ID for the
2014destination in a variable prior to entering the finally block. At the
2015end of the finally block we simply create a switch to the proper
2016destination.
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002017
2018Code gen for @synchronized(expr) stmt;
2019Effectively generating code for:
2020objc_sync_enter(expr);
2021@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar83544842008-09-28 01:03:14 +00002022*/
2023
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002024void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2025 const Stmt &S) {
2026 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002027 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00002028 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson8559de12009-02-07 21:26:04 +00002029 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar72f96552008-11-11 02:29:29 +00002030 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2031 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2032 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar34416d62009-02-24 01:43:46 +00002033
2034 // For @synchronized, call objc_sync_enter(sync.expr). The
2035 // evaluation of the expression must occur before we enter the
2036 // @synchronized. We can safely avoid a temp here because jumps into
2037 // @synchronized are illegal & this will dominate uses.
2038 llvm::Value *SyncArg = 0;
2039 if (!isTry) {
2040 SyncArg =
2041 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2042 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00002043 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar34416d62009-02-24 01:43:46 +00002044 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002045
2046 // Push an EH context entry, used for handling rethrows and jumps
2047 // through finally.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002048 CGF.PushCleanupBlock(FinallyBlock);
2049
Anders Carlssonecd81832009-02-07 21:37:21 +00002050 CGF.ObjCEHValueStack.push_back(0);
2051
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002052 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00002053 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2054 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002055 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2056 "_rethrow");
Anders Carlsson8559de12009-02-07 21:26:04 +00002057 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2058 "_call_try_exit");
2059 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2060
Anders Carlssonfca6c292008-09-09 17:59:25 +00002061 // Enter a new try block and call setjmp.
2062 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2063 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2064 "jmpbufarray");
2065 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2066 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2067 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002068
Daniel Dunbar72f96552008-11-11 02:29:29 +00002069 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2070 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002071 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002072 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002073
2074 // Emit the @try block.
2075 CGF.EmitBlock(TryBlock);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002076 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2077 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002078 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002079
2080 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002081 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002082
2083 // Retrieve the exception object. We may emit multiple blocks but
2084 // nothing can cross this so the value is already in SSA form.
2085 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2086 ExceptionData,
2087 "caught");
Anders Carlssonecd81832009-02-07 21:37:21 +00002088 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002089 if (!isTry)
2090 {
2091 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002092 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002093 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002094 }
2095 else if (const ObjCAtCatchStmt* CatchStmt =
2096 cast<ObjCAtTryStmt>(S).getCatchStmts())
2097 {
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002098 // Enter a new exception try block (in case a @catch block throws
2099 // an exception).
Anders Carlssonfca6c292008-09-09 17:59:25 +00002100 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002101
Anders Carlssonfca6c292008-09-09 17:59:25 +00002102 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2103 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002104 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002105
Daniel Dunbar72f96552008-11-11 02:29:29 +00002106 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2107 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002108 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002109
2110 CGF.EmitBlock(CatchBlock);
2111
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002112 // Handle catch list. As a special case we check if everything is
2113 // matched and avoid generating code for falling off the end if
2114 // so.
2115 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002116 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00002117 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002118
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002119 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002120 const PointerType *PT = 0;
2121
Anders Carlssonfca6c292008-09-09 17:59:25 +00002122 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002123 if (!CatchParam) {
2124 AllMatched = true;
2125 } else {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002126 PT = CatchParam->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002127
Daniel Dunbard04c9352008-09-27 22:21:14 +00002128 // catch(id e) always matches.
2129 // FIXME: For the time being we also match id<X>; this should
2130 // be rejected by Sema instead.
Steve Naroff17c03822009-02-12 17:52:19 +00002131 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002132 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002133 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002134 }
2135
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002136 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00002137 if (CatchParam) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002138 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002139 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002140 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002141 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00002142
Anders Carlsson75d86732008-09-11 09:15:33 +00002143 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002144 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002145 break;
2146 }
2147
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002148 assert(PT && "Unexpected non-pointer type in @catch");
2149 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00002150 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002151 assert(ObjCType && "Catch parameter must have Objective-C type!");
2152
2153 // Check if the @catch block matches the exception object.
2154 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2155
Anders Carlssonfca6c292008-09-09 17:59:25 +00002156 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2157 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002158
Daniel Dunbar72f96552008-11-11 02:29:29 +00002159 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002160
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002161 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002162 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002163
2164 // Emit the @catch block.
2165 CGF.EmitBlock(MatchedBlock);
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002166 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002167 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00002168
2169 llvm::Value *Tmp =
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002170 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar83544842008-09-28 01:03:14 +00002171 "tmp");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002172 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002173
2174 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002175 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002176
2177 CGF.EmitBlock(NextCatchBlock);
2178 }
2179
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002180 if (!AllMatched) {
2181 // None of the handlers caught the exception, so store it to be
2182 // rethrown at the end of the @finally block.
2183 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002184 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002185 }
2186
2187 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002188 CGF.EmitBlock(CatchHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002189 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2190 ExceptionData),
2191 RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002192 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002193 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002194 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00002195 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002196 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002197 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002198 }
2199
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002200 // Pop the exception-handling stack entry. It is important to do
2201 // this now, because the code in the @finally block is not in this
2202 // context.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002203 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2204
Anders Carlssonecd81832009-02-07 21:37:21 +00002205 CGF.ObjCEHValueStack.pop_back();
2206
Anders Carlssonfca6c292008-09-09 17:59:25 +00002207 // Emit the @finally block.
2208 CGF.EmitBlock(FinallyBlock);
Anders Carlsson8559de12009-02-07 21:26:04 +00002209 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2210
2211 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2212
2213 CGF.EmitBlock(FinallyExit);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002214 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002215
2216 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002217 if (isTry) {
2218 if (const ObjCAtFinallyStmt* FinallyStmt =
2219 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2220 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar34416d62009-02-24 01:43:46 +00002221 } else {
2222 // Emit objc_sync_exit(expr); as finally's sole statement for
2223 // @synchronized.
2224 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanian3895d922008-11-21 19:21:53 +00002225 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00002226
Anders Carlsson00ffb962009-02-09 20:38:58 +00002227 // Emit the switch block
2228 if (Info.SwitchBlock)
2229 CGF.EmitBlock(Info.SwitchBlock);
2230 if (Info.EndBlock)
2231 CGF.EmitBlock(Info.EndBlock);
2232
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002233 CGF.EmitBlock(FinallyRethrow);
2234 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2235 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002236 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002237
2238 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00002239}
2240
2241void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002242 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00002243 llvm::Value *ExceptionAsObject;
2244
2245 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2246 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2247 ExceptionAsObject =
2248 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2249 } else {
Anders Carlssonecd81832009-02-07 21:37:21 +00002250 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00002251 "Unexpected rethrow outside @catch block.");
Anders Carlssonecd81832009-02-07 21:37:21 +00002252 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson05d7be72008-09-09 16:16:55 +00002253 }
2254
2255 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002256 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002257
2258 // Clear the insertion point to indicate we are in unreachable code.
2259 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00002260}
2261
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002262/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002263/// object: objc_read_weak (id *src)
2264///
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002265llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002266 llvm::Value *AddrWeakObj)
2267{
Eli Friedmanf8466232009-03-07 03:57:15 +00002268 const llvm::Type* DestTy =
2269 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002270 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002271 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002272 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00002273 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002274 return read_weak;
2275}
2276
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002277/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2278/// objc_assign_weak (id src, id *dst)
2279///
2280void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2281 llvm::Value *src, llvm::Value *dst)
2282{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002283 const llvm::Type * SrcTy = src->getType();
2284 if (!isa<llvm::PointerType>(SrcTy)) {
2285 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2286 assert(Size <= 8 && "does not support size > 8");
2287 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2288 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002289 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2290 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002291 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2292 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00002293 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002294 src, dst, "weakassign");
2295 return;
2296}
2297
Fariborz Jahanian17958902008-11-19 00:59:10 +00002298/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2299/// objc_assign_global (id src, id *dst)
2300///
2301void CGObjCMac::EmitObjCGlobalAssign(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);
Fariborz Jahanian17958902008-11-19 00:59:10 +00002314 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2315 src, dst, "globalassign");
2316 return;
2317}
2318
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002319/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2320/// objc_assign_ivar (id src, id *dst)
2321///
2322void CGObjCMac::EmitObjCIvarAssign(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 Jahanianf310b592008-11-20 19:23:36 +00002333 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2334 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2335 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2336 src, dst, "assignivar");
2337 return;
2338}
2339
Fariborz Jahanian17958902008-11-19 00:59:10 +00002340/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2341/// objc_assign_strongCast (id src, id *dst)
2342///
2343void CGObjCMac::EmitObjCStrongCastAssign(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 Jahaniand2f661a2008-11-19 17:34:06 +00002354 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2355 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00002356 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2357 src, dst, "weakassign");
2358 return;
2359}
2360
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002361/// EmitObjCValueForIvar - Code Gen for ivar reference.
2362///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002363LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2364 QualType ObjectTy,
2365 llvm::Value *BaseValue,
2366 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002367 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002368 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2369 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002370 if (Ivar->isBitField())
2371 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2372 CVRQualifiers);
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002373 // TODO: Add a special case for isa (index 0)
2374 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2375 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002376 LValue LV = LValue::MakeAddr(V,
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00002377 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2378 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002379 LValue::SetObjCIvar(LV, true);
2380 return LV;
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002381}
2382
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002383llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2384 ObjCInterfaceDecl *Interface,
2385 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002386 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbarf0587c62009-04-20 00:37:55 +00002387 const FieldDecl *Field =
2388 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +00002389 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002390 return llvm::ConstantInt::get(
2391 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2392 Offset);
2393}
2394
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002395/* *** Private Interface *** */
2396
2397/// EmitImageInfo - Emit the image info marker used to encode some module
2398/// level information.
2399///
2400/// See: <rdr://4810609&4810587&4810587>
2401/// struct IMAGE_INFO {
2402/// unsigned version;
2403/// unsigned flags;
2404/// };
2405enum ImageInfoFlags {
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002406 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2407 // this implies.
2408 eImageInfo_GarbageCollected = (1 << 1),
2409 eImageInfo_GCOnly = (1 << 2),
2410 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2411
2412 // A flag indicating that the module has no instances of an
2413 // @synthesize of a superclass variable. <rdar://problem/6803242>
2414 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002415};
2416
2417void CGObjCMac::EmitImageInfo() {
2418 unsigned version = 0; // Version is unused?
2419 unsigned flags = 0;
2420
2421 // FIXME: Fix and continue?
2422 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2423 flags |= eImageInfo_GarbageCollected;
2424 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2425 flags |= eImageInfo_GCOnly;
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002426
2427 // We never allow @synthesize of a superclass property.
2428 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002429
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002430 // Emitted as int[2];
2431 llvm::Constant *values[2] = {
2432 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2433 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2434 };
2435 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002436
2437 const char *Section;
2438 if (ObjCABI == 1)
2439 Section = "__OBJC, __image_info,regular";
2440 else
2441 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002442 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002443 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2444 llvm::ConstantArray::get(AT, values, 2),
2445 Section,
2446 0,
2447 true);
2448 GV->setConstant(true);
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002449}
2450
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002451
2452// struct objc_module {
2453// unsigned long version;
2454// unsigned long size;
2455// const char *name;
2456// Symtab symtab;
2457// };
2458
2459// FIXME: Get from somewhere
2460static const int ModuleVersion = 7;
2461
2462void CGObjCMac::EmitModuleInfo() {
Daniel Dunbard8439f22009-01-12 21:08:18 +00002463 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002464
2465 std::vector<llvm::Constant*> Values(4);
2466 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2467 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00002468 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002469 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002470 Values[3] = EmitModuleSymbols();
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002471 CreateMetadataVar("\01L_OBJC_MODULES",
2472 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2473 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00002474 4, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002475}
2476
2477llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002478 unsigned NumClasses = DefinedClasses.size();
2479 unsigned NumCategories = DefinedCategories.size();
2480
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002481 // Return null if no symbols were defined.
2482 if (!NumClasses && !NumCategories)
2483 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2484
2485 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002486 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2487 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2488 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2489 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2490
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002491 // The runtime expects exactly the list of defined classes followed
2492 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002493 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002494 for (unsigned i=0; i<NumClasses; i++)
2495 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2496 ObjCTypes.Int8PtrTy);
2497 for (unsigned i=0; i<NumCategories; i++)
2498 Symbols[NumClasses + i] =
2499 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2500 ObjCTypes.Int8PtrTy);
2501
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002502 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002503 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002504 NumClasses + NumCategories),
2505 Symbols);
2506
2507 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2508
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002509 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002510 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2511 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002512 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002513 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2514}
2515
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002516llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002517 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002518 LazySymbols.insert(ID->getIdentifier());
2519
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002520 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2521
2522 if (!Entry) {
2523 llvm::Constant *Casted =
2524 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2525 ObjCTypes.ClassPtrTy);
2526 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002527 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2528 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002529 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002530 }
2531
2532 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002533}
2534
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002535llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002536 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2537
2538 if (!Entry) {
2539 llvm::Constant *Casted =
2540 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2541 ObjCTypes.SelectorPtrTy);
2542 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002543 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2544 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002545 4, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002546 }
2547
2548 return Builder.CreateLoad(Entry, false, "tmp");
2549}
2550
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00002551llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002552 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002553
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002554 if (!Entry)
2555 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2556 llvm::ConstantArray::get(Ident->getName()),
2557 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002558 1, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002559
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002560 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002561}
2562
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002563/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2564/// interface declaration.
2565const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2566 const ObjCInterfaceDecl *OID) const {
Daniel Dunbarecb5d402009-04-19 23:41:48 +00002567 // FIXME: When does this happen? It seems pretty bad to do this...
Daniel Dunbar72878722009-04-20 20:18:54 +00002568 if (OID->isForwardDecl())
2569 return CGM.getTargetData().getStructLayout(llvm::StructType::get(NULL,
2570 NULL));
2571
2572 QualType T =
2573 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2574 const llvm::StructType *InterfaceTy =
2575 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2576 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002577}
2578
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00002579/// GetIvarLayoutName - Returns a unique constant for the given
2580/// ivar layout bitmap.
2581llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2582 const ObjCCommonTypesHelper &ObjCTypes) {
2583 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2584}
2585
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002586void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2587 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +00002588 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002589 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002590 unsigned int BytePos, bool ForStrongLayout,
2591 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002592 bool IsUnion = (RD && RD->isUnion());
2593 uint64_t MaxUnionIvarSize = 0;
2594 uint64_t MaxSkippedUnionIvarSize = 0;
2595 FieldDecl *MaxField = 0;
2596 FieldDecl *MaxSkippedField = 0;
Chris Lattner9329cf52009-03-31 08:48:01 +00002597 unsigned base = 0;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002598 if (RecFields.empty())
2599 return;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002600 if (IsUnion)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002601 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattner9329cf52009-03-31 08:48:01 +00002602 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2603 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2604
2605 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2606
2607 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002608 FieldDecl *Field = RecFields[i];
2609 // Skip over unnamed or bitfields
2610 if (!Field->getIdentifier() || Field->isBitField())
2611 continue;
2612 QualType FQT = Field->getType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002613 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002614 if (FQT->isUnionType())
2615 HasUnion = true;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002616 else
2617 assert(FQT->isRecordType() &&
2618 "only union/record is supported for ivar layout bitmap");
2619
Fariborz Jahanian37931062009-03-10 16:22:08 +00002620 const RecordType *RT = FQT->getAsRecordType();
2621 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarecb5d402009-04-19 23:41:48 +00002622 // FIXME - Find a more efficient way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002623 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2624 RD->field_end(CGM.getContext()));
Fariborz Jahanian31614742009-04-20 22:03:45 +00002625 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2626 const llvm::StructLayout *RecLayout =
2627 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2628
2629 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002630 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian37931062009-03-10 16:22:08 +00002631 ForStrongLayout, Index, SkIndex,
2632 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002633 TmpRecFields.clear();
Fariborz Jahanian37931062009-03-10 16:22:08 +00002634 continue;
2635 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002636
2637 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002638 const ConstantArrayType *CArray =
2639 dyn_cast_or_null<ConstantArrayType>(Array);
2640 assert(CArray && "only array with know element size is supported");
2641 FQT = CArray->getElementType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002642 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2643 const ConstantArrayType *CArray =
2644 dyn_cast_or_null<ConstantArrayType>(Array);
2645 FQT = CArray->getElementType();
2646 }
2647
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002648 assert(!FQT->isUnionType() &&
2649 "layout for array of unions not supported");
2650 if (FQT->isRecordType()) {
2651 uint64_t ElCount = CArray->getSize().getZExtValue();
2652 int OldIndex = Index;
2653 int OldSkIndex = SkIndex;
2654
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002655 // FIXME - Use a common routine with the above!
2656 const RecordType *RT = FQT->getAsRecordType();
2657 const RecordDecl *RD = RT->getDecl();
2658 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002659 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2660 RD->field_end(CGM.getContext()));
Fariborz Jahanian31614742009-04-20 22:03:45 +00002661 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2662 const llvm::StructLayout *RecLayout =
2663 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattner9329cf52009-03-31 08:48:01 +00002664
Fariborz Jahanian31614742009-04-20 22:03:45 +00002665 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002666 TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002667 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002668 ForStrongLayout, Index, SkIndex,
2669 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002670 TmpRecFields.clear();
2671
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002672 // Replicate layout information for each array element. Note that
2673 // one element is already done.
2674 uint64_t ElIx = 1;
2675 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2676 ElIx < ElCount; ElIx++) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002677 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002678 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2679 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002680 GC_IVAR gcivar;
2681 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2682 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2683 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002684 }
2685
Chris Lattner9329cf52009-03-31 08:48:01 +00002686 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002687 GC_IVAR skivar;
2688 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2689 skivar.ivar_size = SkipIvars[i].ivar_size;
2690 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002691 }
2692 }
2693 continue;
2694 }
Fariborz Jahanian37931062009-03-10 16:22:08 +00002695 }
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002696 // At this point, we are done with Record/Union and array there of.
2697 // For other arrays we are down to its element type.
2698 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2699 do {
2700 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2701 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2702 break;
2703 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002704 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002705 GCAttr = QualType::Strong;
2706 break;
2707 }
2708 else if (const PointerType *PT = FQT->getAsPointerType()) {
2709 FQT = PT->getPointeeType();
2710 }
2711 else {
2712 break;
2713 }
2714 } while (true);
Chris Lattner9329cf52009-03-31 08:48:01 +00002715
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002716 if ((ForStrongLayout && GCAttr == QualType::Strong)
2717 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2718 if (IsUnion)
2719 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002720 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2721 / WordSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002722 if (UnionIvarSize > MaxUnionIvarSize)
2723 {
2724 MaxUnionIvarSize = UnionIvarSize;
2725 MaxField = Field;
2726 }
2727 }
2728 else
2729 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002730 GC_IVAR gcivar;
2731 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2732 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2733 WordSizeInBits;
2734 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002735 }
2736 }
2737 else if ((ForStrongLayout &&
2738 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2739 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2740 if (IsUnion)
2741 {
2742 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2743 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2744 {
2745 MaxSkippedUnionIvarSize = UnionIvarSize;
2746 MaxSkippedField = Field;
2747 }
2748 }
2749 else
2750 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002751 GC_IVAR skivar;
2752 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2753 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2754 WordSizeInBits;
2755 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002756 }
2757 }
2758 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002759 if (MaxField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002760 GC_IVAR gcivar;
2761 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2762 gcivar.ivar_size = MaxUnionIvarSize;
2763 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002764 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002765
2766 if (MaxSkippedField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002767 GC_IVAR skivar;
2768 skivar.ivar_bytepos = BytePos +
2769 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2770 skivar.ivar_size = MaxSkippedUnionIvarSize;
2771 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002772 }
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002773}
2774
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002775static int
Chris Lattner9329cf52009-03-31 08:48:01 +00002776IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002777{
2778 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2779 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2780
2781 if (sa < sb)
2782 return -1;
2783 if (sa > sb)
2784 return 1;
2785 return 0;
2786}
2787
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002788/// BuildIvarLayout - Builds ivar layout bitmap for the class
2789/// implementation for the __strong or __weak case.
2790/// The layout map displays which words in ivar list must be skipped
2791/// and which must be scanned by GC (see below). String is built of bytes.
2792/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2793/// of words to skip and right nibble is count of words to scan. So, each
2794/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2795/// represented by a 0x00 byte which also ends the string.
2796/// 1. when ForStrongLayout is true, following ivars are scanned:
2797/// - id, Class
2798/// - object *
2799/// - __strong anything
2800///
2801/// 2. When ForStrongLayout is false, following ivars are scanned:
2802/// - __weak anything
2803///
Fariborz Jahanian37931062009-03-10 16:22:08 +00002804llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002805 const ObjCImplementationDecl *OMD,
2806 bool ForStrongLayout) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002807 int Index = -1;
2808 int SkIndex = -1;
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002809 bool hasUnion = false;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002810 int SkipScan;
2811 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002812 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2813 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2814 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002815
Chris Lattner9329cf52009-03-31 08:48:01 +00002816 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002817 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002818 CGM.getContext().CollectObjCIvars(OI, RecFields);
2819 if (RecFields.empty())
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002820 return llvm::Constant::getNullValue(PtrTy);
Chris Lattner9329cf52009-03-31 08:48:01 +00002821
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002822 SkipIvars.clear();
2823 IvarsInfo.clear();
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00002824
2825 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattner9329cf52009-03-31 08:48:01 +00002826 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2827 Index, SkIndex, hasUnion);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002828 if (Index == -1)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002829 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002830
2831 // Sort on byte position in case we encounterred a union nested in
2832 // the ivar list.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002833 if (hasUnion && !IvarsInfo.empty())
2834 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2835 if (hasUnion && !SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002836 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2837
2838 // Build the string of skip/scan nibbles
2839 SkipScan = -1;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002840 SkipScanIvars.clear();
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002841 unsigned int WordSize =
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002842 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002843 if (IvarsInfo[0].ivar_bytepos == 0) {
2844 WordsToSkip = 0;
2845 WordsToScan = IvarsInfo[0].ivar_size;
2846 }
2847 else {
2848 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2849 WordsToScan = IvarsInfo[0].ivar_size;
2850 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002851 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002852 {
2853 unsigned int TailPrevGCObjC =
2854 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2855 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2856 {
2857 // consecutive 'scanned' object pointers.
2858 WordsToScan += IvarsInfo[i].ivar_size;
2859 }
2860 else
2861 {
2862 // Skip over 'gc'able object pointer which lay over each other.
2863 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2864 continue;
2865 // Must skip over 1 or more words. We save current skip/scan values
2866 // and start a new pair.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002867 SKIP_SCAN SkScan;
2868 SkScan.skip = WordsToSkip;
2869 SkScan.scan = WordsToScan;
2870 SkipScanIvars.push_back(SkScan); ++SkipScan;
2871
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002872 // Skip the hole.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002873 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2874 SkScan.scan = 0;
2875 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002876 WordsToSkip = 0;
2877 WordsToScan = IvarsInfo[i].ivar_size;
2878 }
2879 }
2880 if (WordsToScan > 0)
2881 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002882 SKIP_SCAN SkScan;
2883 SkScan.skip = WordsToSkip;
2884 SkScan.scan = WordsToScan;
2885 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002886 }
2887
2888 bool BytesSkipped = false;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002889 if (!SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002890 {
2891 int LastByteSkipped =
2892 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2893 int LastByteScanned =
2894 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2895 BytesSkipped = (LastByteSkipped > LastByteScanned);
2896 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2897 if (BytesSkipped)
2898 {
2899 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002900 SKIP_SCAN SkScan;
2901 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2902 SkScan.scan = 0;
2903 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002904 }
2905 }
2906 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2907 // as 0xMN.
2908 for (int i = 0; i <= SkipScan; i++)
2909 {
2910 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2911 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2912 // 0xM0 followed by 0x0N detected.
2913 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2914 for (int j = i+1; j < SkipScan; j++)
2915 SkipScanIvars[j] = SkipScanIvars[j+1];
2916 --SkipScan;
2917 }
2918 }
2919
2920 // Generate the string.
2921 std::string BitMap;
2922 for (int i = 0; i <= SkipScan; i++)
2923 {
2924 unsigned char byte;
2925 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2926 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2927 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2928 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2929
2930 if (skip_small > 0 || skip_big > 0)
2931 BytesSkipped = true;
2932 // first skip big.
2933 for (unsigned int ix = 0; ix < skip_big; ix++)
2934 BitMap += (unsigned char)(0xf0);
2935
2936 // next (skip small, scan)
2937 if (skip_small)
2938 {
2939 byte = skip_small << 4;
2940 if (scan_big > 0)
2941 {
2942 byte |= 0xf;
2943 --scan_big;
2944 }
2945 else if (scan_small)
2946 {
2947 byte |= scan_small;
2948 scan_small = 0;
2949 }
2950 BitMap += byte;
2951 }
2952 // next scan big
2953 for (unsigned int ix = 0; ix < scan_big; ix++)
2954 BitMap += (unsigned char)(0x0f);
2955 // last scan small
2956 if (scan_small)
2957 {
2958 byte = scan_small;
2959 BitMap += byte;
2960 }
2961 }
2962 // null terminate string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002963 unsigned char zero = 0;
2964 BitMap += zero;
Fariborz Jahanian31614742009-04-20 22:03:45 +00002965
2966 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
2967 printf("\n%s ivar layout for class '%s': ",
2968 ForStrongLayout ? "strong" : "weak",
2969 OMD->getClassInterface()->getNameAsCString());
2970 const unsigned char *s = (unsigned char*)BitMap.c_str();
2971 for (unsigned i = 0; i < BitMap.size(); i++)
2972 if (!(s[i] & 0xf0))
2973 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2974 else
2975 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2976 printf("\n");
2977 }
2978
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00002979 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2980 // final layout.
2981 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002982 return llvm::Constant::getNullValue(PtrTy);
2983 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2984 llvm::ConstantArray::get(BitMap.c_str()),
2985 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002986 1, true);
Fariborz Jahanian31614742009-04-20 22:03:45 +00002987 return getConstantGEP(Entry, 0, 0);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002988}
2989
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00002990llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002991 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2992
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002993 // FIXME: Avoid std::string copying.
2994 if (!Entry)
2995 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2996 llvm::ConstantArray::get(Sel.getAsString()),
2997 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002998 1, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002999
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003000 return getConstantGEP(Entry, 0, 0);
3001}
3002
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003003// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003004llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003005 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3006}
3007
3008// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003009llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003010 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3011}
3012
Daniel Dunbar356f0742009-04-20 06:54:31 +00003013llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel593a07a2009-03-04 18:21:39 +00003014 std::string TypeStr;
3015 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3016
3017 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003018
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003019 if (!Entry)
3020 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3021 llvm::ConstantArray::get(TypeStr),
3022 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003023 1, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003024
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003025 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003026}
3027
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003028llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003029 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00003030 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3031 TypeStr);
Devang Patel593a07a2009-03-04 18:21:39 +00003032
3033 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3034
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003035 if (!Entry)
3036 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3037 llvm::ConstantArray::get(TypeStr),
3038 "__TEXT,__cstring,cstring_literals",
3039 1, true);
Devang Patel593a07a2009-03-04 18:21:39 +00003040
3041 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003042}
3043
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003044// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003045llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003046 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3047
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003048 if (!Entry)
3049 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3050 llvm::ConstantArray::get(Ident->getName()),
3051 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003052 1, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003053
3054 return getConstantGEP(Entry, 0, 0);
3055}
3056
3057// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003058// FIXME: This Decl should be more precise.
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003059llvm::Constant *
3060 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3061 const Decl *Container) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003062 std::string TypeStr;
3063 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003064 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3065}
3066
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003067void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3068 const ObjCContainerDecl *CD,
3069 std::string &NameOut) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00003070 NameOut = '\01';
3071 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner3a8f2942008-11-24 03:33:13 +00003072 NameOut += '[';
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00003073 assert (CD && "Missing container decl in GetNameForMethod");
3074 NameOut += CD->getNameAsString();
Fariborz Jahanian6e4b7372009-04-16 18:34:20 +00003075 if (const ObjCCategoryImplDecl *CID =
3076 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3077 NameOut += '(';
3078 NameOut += CID->getNameAsString();
3079 NameOut+= ')';
3080 }
Chris Lattner3a8f2942008-11-24 03:33:13 +00003081 NameOut += ' ';
3082 NameOut += D->getSelector().getAsString();
3083 NameOut += ']';
Daniel Dunbarace33292008-08-16 03:19:19 +00003084}
3085
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003086void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003087 EmitModuleInfo();
3088
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003089 // Emit the dummy bodies for any protocols which were referenced but
3090 // never defined.
3091 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3092 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3093 if (i->second->hasInitializer())
3094 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003095
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003096 std::vector<llvm::Constant*> Values(5);
3097 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3098 Values[1] = GetClassName(i->first);
3099 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3100 Values[3] = Values[4] =
3101 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3102 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3103 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3104 Values));
3105 }
3106
3107 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003108 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003109 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003110 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003111 }
3112
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003113 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003114 llvm::GlobalValue *GV =
3115 new llvm::GlobalVariable(AT, false,
3116 llvm::GlobalValue::AppendingLinkage,
3117 llvm::ConstantArray::get(AT, Used),
3118 "llvm.used",
3119 &CGM.getModule());
3120
3121 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003122
3123 // Add assembler directives to add lazy undefined symbol references
3124 // for classes which are referenced but not defined. This is
3125 // important for correct linker interaction.
3126
3127 // FIXME: Uh, this isn't particularly portable.
3128 std::stringstream s;
Anders Carlsson63f98352008-12-10 02:21:04 +00003129
3130 if (!CGM.getModule().getModuleInlineAsm().empty())
3131 s << "\n";
3132
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003133 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3134 e = LazySymbols.end(); i != e; ++i) {
3135 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3136 }
3137 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3138 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003139 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003140 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3141 }
Anders Carlsson63f98352008-12-10 02:21:04 +00003142
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003143 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003144}
3145
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003146CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003147 : CGObjCCommonMac(cgm),
3148 ObjCTypes(cgm)
3149{
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003150 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003151 ObjCABI = 2;
3152}
3153
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003154/* *** */
3155
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003156ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3157: CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003158{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003159 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3160 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003161
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003162 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003163 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003164 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00003165 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003166 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3167
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003168 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003169 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003170 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003171
3172 // FIXME: It would be nice to unify this with the opaque type, so
3173 // that the IR comes out a bit cleaner.
3174 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3175 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003176
3177 // I'm not sure I like this. The implicit coordination is a bit
3178 // gross. We should solve this in a reasonable fashion because this
3179 // is a pretty common task (match some runtime data structure with
3180 // an LLVM data structure).
3181
3182 // FIXME: This is leaked.
3183 // FIXME: Merge with rewriter code?
3184
3185 // struct _objc_super {
3186 // id self;
3187 // Class cls;
3188 // }
3189 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3190 SourceLocation(),
3191 &Ctx.Idents.get("_objc_super"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003192 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3193 Ctx.getObjCIdType(), 0, false));
3194 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3195 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003196 RD->completeDefinition(Ctx);
3197
3198 SuperCTy = Ctx.getTagDeclType(RD);
3199 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3200
3201 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003202 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3203
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003204 // struct _prop_t {
3205 // char *name;
3206 // char *attributes;
3207 // }
3208 PropertyTy = llvm::StructType::get(Int8PtrTy,
3209 Int8PtrTy,
3210 NULL);
3211 CGM.getModule().addTypeName("struct._prop_t",
3212 PropertyTy);
3213
3214 // struct _prop_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003215 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003216 // uint32_t count_of_properties;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003217 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003218 // }
3219 PropertyListTy = llvm::StructType::get(IntTy,
3220 IntTy,
3221 llvm::ArrayType::get(PropertyTy, 0),
3222 NULL);
3223 CGM.getModule().addTypeName("struct._prop_list_t",
3224 PropertyListTy);
3225 // struct _prop_list_t *
3226 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3227
3228 // struct _objc_method {
3229 // SEL _cmd;
3230 // char *method_type;
3231 // char *_imp;
3232 // }
3233 MethodTy = llvm::StructType::get(SelectorPtrTy,
3234 Int8PtrTy,
3235 Int8PtrTy,
3236 NULL);
3237 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003238
3239 // struct _objc_cache *
3240 CacheTy = llvm::OpaqueType::get();
3241 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3242 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003243
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003244 // Property manipulation functions.
Daniel Dunbardac29922009-02-04 00:44:42 +00003245
3246 QualType IdType = Ctx.getObjCIdType();
3247 QualType SelType = Ctx.getObjCSelType();
3248 llvm::SmallVector<QualType,16> Params;
3249 const llvm::FunctionType *FTy;
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003250
3251 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbardac29922009-02-04 00:44:42 +00003252 Params.push_back(IdType);
3253 Params.push_back(SelType);
3254 Params.push_back(Ctx.LongTy);
3255 Params.push_back(Ctx.BoolTy);
3256 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3257 false);
3258 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003259
3260 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3261 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003262 Params.push_back(IdType);
3263 Params.push_back(SelType);
3264 Params.push_back(Ctx.LongTy);
3265 Params.push_back(IdType);
3266 Params.push_back(Ctx.BoolTy);
3267 Params.push_back(Ctx.BoolTy);
3268 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3269 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3270
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003271 // Enumeration mutation.
Daniel Dunbardac29922009-02-04 00:44:42 +00003272
3273 // void objc_enumerationMutation (id)
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003274 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003275 Params.push_back(IdType);
3276 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3277 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3278 "objc_enumerationMutation");
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003279
3280 // gc's API
3281 // id objc_read_weak (id *)
3282 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003283 Params.push_back(Ctx.getPointerType(IdType));
3284 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3285 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3286
Chris Lattner293c1d32009-04-17 22:12:36 +00003287 // id objc_assign_global (id, id *)
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003288 Params.clear();
Daniel Dunbardac29922009-02-04 00:44:42 +00003289 Params.push_back(IdType);
3290 Params.push_back(Ctx.getPointerType(IdType));
3291
3292 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbardac29922009-02-04 00:44:42 +00003293 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3294 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3295 GcAssignStrongCastFn =
3296 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlsson1cf75362009-02-16 22:59:18 +00003297
3298 // void objc_exception_throw(id)
3299 Params.clear();
3300 Params.push_back(IdType);
3301
3302 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlsson1cf75362009-02-16 22:59:18 +00003303 ExceptionThrowFn =
3304 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar34416d62009-02-24 01:43:46 +00003305
3306 // synchronized APIs
Daniel Dunbar34416d62009-02-24 01:43:46 +00003307 // void objc_sync_exit (id)
3308 Params.clear();
3309 Params.push_back(IdType);
3310
3311 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar34416d62009-02-24 01:43:46 +00003312 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003313}
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003314
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003315ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3316 : ObjCCommonTypesHelper(cgm)
3317{
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003318 // struct _objc_method_description {
3319 // SEL name;
3320 // char *types;
3321 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003322 MethodDescriptionTy =
3323 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003324 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003325 NULL);
3326 CGM.getModule().addTypeName("struct._objc_method_description",
3327 MethodDescriptionTy);
3328
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003329 // struct _objc_method_description_list {
3330 // int count;
3331 // struct _objc_method_description[1];
3332 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003333 MethodDescriptionListTy =
3334 llvm::StructType::get(IntTy,
3335 llvm::ArrayType::get(MethodDescriptionTy, 0),
3336 NULL);
3337 CGM.getModule().addTypeName("struct._objc_method_description_list",
3338 MethodDescriptionListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003339
3340 // struct _objc_method_description_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003341 MethodDescriptionListPtrTy =
3342 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3343
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003344 // Protocol description structures
3345
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003346 // struct _objc_protocol_extension {
3347 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3348 // struct _objc_method_description_list *optional_instance_methods;
3349 // struct _objc_method_description_list *optional_class_methods;
3350 // struct _objc_property_list *instance_properties;
3351 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003352 ProtocolExtensionTy =
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003353 llvm::StructType::get(IntTy,
3354 MethodDescriptionListPtrTy,
3355 MethodDescriptionListPtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003356 PropertyListPtrTy,
3357 NULL);
3358 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3359 ProtocolExtensionTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003360
3361 // struct _objc_protocol_extension *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003362 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3363
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003364 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003365
3366 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3367 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3368
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003369 const llvm::Type *T =
3370 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3371 LongTy,
3372 llvm::ArrayType::get(ProtocolTyHolder, 0),
3373 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003374 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3375
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003376 // struct _objc_protocol {
3377 // struct _objc_protocol_extension *isa;
3378 // char *protocol_name;
3379 // struct _objc_protocol **_objc_protocol_list;
3380 // struct _objc_method_description_list *instance_methods;
3381 // struct _objc_method_description_list *class_methods;
3382 // }
3383 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003384 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003385 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3386 MethodDescriptionListPtrTy,
3387 MethodDescriptionListPtrTy,
3388 NULL);
3389 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3390
3391 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3392 CGM.getModule().addTypeName("struct._objc_protocol_list",
3393 ProtocolListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003394 // struct _objc_protocol_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003395 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3396
3397 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003398 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003399 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003400
3401 // Class description structures
3402
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003403 // struct _objc_ivar {
3404 // char *ivar_name;
3405 // char *ivar_type;
3406 // int ivar_offset;
3407 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003408 IvarTy = llvm::StructType::get(Int8PtrTy,
3409 Int8PtrTy,
3410 IntTy,
3411 NULL);
3412 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3413
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003414 // struct _objc_ivar_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003415 IvarListTy = llvm::OpaqueType::get();
3416 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3417 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3418
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003419 // struct _objc_method_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003420 MethodListTy = llvm::OpaqueType::get();
3421 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3422 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3423
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003424 // struct _objc_class_extension *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003425 ClassExtensionTy =
3426 llvm::StructType::get(IntTy,
3427 Int8PtrTy,
3428 PropertyListPtrTy,
3429 NULL);
3430 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3431 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3432
3433 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3434
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003435 // struct _objc_class {
3436 // Class isa;
3437 // Class super_class;
3438 // char *name;
3439 // long version;
3440 // long info;
3441 // long instance_size;
3442 // struct _objc_ivar_list *ivars;
3443 // struct _objc_method_list *methods;
3444 // struct _objc_cache *cache;
3445 // struct _objc_protocol_list *protocols;
3446 // char *ivar_layout;
3447 // struct _objc_class_ext *ext;
3448 // };
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003449 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3450 llvm::PointerType::getUnqual(ClassTyHolder),
3451 Int8PtrTy,
3452 LongTy,
3453 LongTy,
3454 LongTy,
3455 IvarListPtrTy,
3456 MethodListPtrTy,
3457 CachePtrTy,
3458 ProtocolListPtrTy,
3459 Int8PtrTy,
3460 ClassExtensionPtrTy,
3461 NULL);
3462 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3463
3464 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3465 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3466 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3467
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003468 // struct _objc_category {
3469 // char *category_name;
3470 // char *class_name;
3471 // struct _objc_method_list *instance_method;
3472 // struct _objc_method_list *class_method;
3473 // uint32_t size; // sizeof(struct _objc_category)
3474 // struct _objc_property_list *instance_properties;// category's @property
3475 // }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003476 CategoryTy = llvm::StructType::get(Int8PtrTy,
3477 Int8PtrTy,
3478 MethodListPtrTy,
3479 MethodListPtrTy,
3480 ProtocolListPtrTy,
3481 IntTy,
3482 PropertyListPtrTy,
3483 NULL);
3484 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3485
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003486 // Global metadata structures
3487
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003488 // struct _objc_symtab {
3489 // long sel_ref_cnt;
3490 // SEL *refs;
3491 // short cls_def_cnt;
3492 // short cat_def_cnt;
3493 // char *defs[cls_def_cnt + cat_def_cnt];
3494 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003495 SymtabTy = llvm::StructType::get(LongTy,
3496 SelectorPtrTy,
3497 ShortTy,
3498 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003499 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003500 NULL);
3501 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3502 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3503
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003504 // struct _objc_module {
3505 // long version;
3506 // long size; // sizeof(struct _objc_module)
3507 // char *name;
3508 // struct _objc_symtab* symtab;
3509 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003510 ModuleTy =
3511 llvm::StructType::get(LongTy,
3512 LongTy,
3513 Int8PtrTy,
3514 SymtabPtrTy,
3515 NULL);
3516 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003517
Daniel Dunbarf7103722008-09-24 03:38:44 +00003518 // Message send functions.
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003519
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003520 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003521 std::vector<const llvm::Type*> Params;
3522 Params.push_back(ObjectPtrTy);
3523 Params.push_back(SelectorPtrTy);
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003524 MessageSendFn =
3525 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3526 Params,
3527 true),
3528 "objc_msgSend");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003529
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003530 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003531 Params.clear();
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003532 Params.push_back(ObjectPtrTy);
3533 Params.push_back(SelectorPtrTy);
3534 MessageSendStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003535 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3536 Params,
3537 true),
3538 "objc_msgSend_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003539
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003540 //
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003541 Params.clear();
3542 Params.push_back(ObjectPtrTy);
3543 Params.push_back(SelectorPtrTy);
3544 // FIXME: This should be long double on x86_64?
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003545 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003546 MessageSendFpretFn =
3547 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3548 Params,
3549 true),
3550 "objc_msgSend_fpret");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003551
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003552 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003553 Params.clear();
3554 Params.push_back(SuperPtrTy);
3555 Params.push_back(SelectorPtrTy);
3556 MessageSendSuperFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003557 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3558 Params,
3559 true),
3560 "objc_msgSendSuper");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003561
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003562 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3563 // SEL op, ...)
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003564 Params.clear();
3565 Params.push_back(Int8PtrTy);
3566 Params.push_back(SuperPtrTy);
3567 Params.push_back(SelectorPtrTy);
3568 MessageSendSuperStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003569 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3570 Params,
3571 true),
3572 "objc_msgSendSuper_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00003573
3574 // There is no objc_msgSendSuper_fpret? How can that work?
3575 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson58d16242008-08-31 04:05:03 +00003576
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003577 // FIXME: This is the size of the setjmp buffer and should be
3578 // target specific. 18 is what's used on 32-bit X86.
3579 uint64_t SetJmpBufferSize = 18;
3580
3581 // Exceptions
3582 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00003583 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003584
3585 ExceptionDataTy =
3586 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3587 SetJmpBufferSize),
3588 StackPtrTy, NULL);
3589 CGM.getModule().addTypeName("struct._objc_exception_data",
3590 ExceptionDataTy);
3591
3592 Params.clear();
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003593 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3594 ExceptionTryEnterFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003595 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3596 Params,
3597 false),
3598 "objc_exception_try_enter");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003599 ExceptionTryExitFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003600 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3601 Params,
3602 false),
3603 "objc_exception_try_exit");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003604 ExceptionExtractFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003605 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3606 Params,
3607 false),
3608 "objc_exception_extract");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003609
3610 Params.clear();
3611 Params.push_back(ClassPtrTy);
3612 Params.push_back(ObjectPtrTy);
3613 ExceptionMatchFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003614 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3615 Params,
3616 false),
3617 "objc_exception_match");
Chris Lattnerdd978702008-11-15 21:26:17 +00003618
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003619 Params.clear();
3620 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3621 SetJmpFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00003622 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3623 Params,
3624 false),
3625 "_setjmp");
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003626
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003627}
3628
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003629ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003630: ObjCCommonTypesHelper(cgm)
3631{
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003632 // struct _method_list_t {
3633 // uint32_t entsize; // sizeof(struct _objc_method)
3634 // uint32_t method_count;
3635 // struct _objc_method method_list[method_count];
3636 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003637 MethodListnfABITy = llvm::StructType::get(IntTy,
3638 IntTy,
3639 llvm::ArrayType::get(MethodTy, 0),
3640 NULL);
3641 CGM.getModule().addTypeName("struct.__method_list_t",
3642 MethodListnfABITy);
3643 // struct method_list_t *
3644 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003645
3646 // struct _protocol_t {
3647 // id isa; // NULL
3648 // const char * const protocol_name;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003649 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003650 // const struct method_list_t * const instance_methods;
3651 // const struct method_list_t * const class_methods;
3652 // const struct method_list_t *optionalInstanceMethods;
3653 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003654 // const struct _prop_list_t * properties;
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003655 // const uint32_t size; // sizeof(struct _protocol_t)
3656 // const uint32_t flags; // = 0
3657 // }
3658
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003659 // Holder for struct _protocol_list_t *
3660 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3661
3662 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3663 Int8PtrTy,
3664 llvm::PointerType::getUnqual(
3665 ProtocolListTyHolder),
3666 MethodListnfABIPtrTy,
3667 MethodListnfABIPtrTy,
3668 MethodListnfABIPtrTy,
3669 MethodListnfABIPtrTy,
3670 PropertyListPtrTy,
3671 IntTy,
3672 IntTy,
3673 NULL);
3674 CGM.getModule().addTypeName("struct._protocol_t",
3675 ProtocolnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003676
3677 // struct _protocol_t*
3678 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003679
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00003680 // struct _protocol_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003681 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003682 // struct _protocol_t *[protocol_count];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003683 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003684 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3685 llvm::ArrayType::get(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003686 ProtocolnfABIPtrTy, 0),
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003687 NULL);
3688 CGM.getModule().addTypeName("struct._objc_protocol_list",
3689 ProtocolListnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003690 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3691 ProtocolListnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003692
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003693 // struct _objc_protocol_list*
3694 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003695
3696 // struct _ivar_t {
3697 // unsigned long int *offset; // pointer to ivar offset location
3698 // char *name;
3699 // char *type;
3700 // uint32_t alignment;
3701 // uint32_t size;
3702 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003703 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3704 Int8PtrTy,
3705 Int8PtrTy,
3706 IntTy,
3707 IntTy,
3708 NULL);
3709 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3710
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003711 // struct _ivar_list_t {
3712 // uint32 entsize; // sizeof(struct _ivar_t)
3713 // uint32 count;
3714 // struct _iver_t list[count];
3715 // }
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00003716 IvarListnfABITy = llvm::StructType::get(IntTy,
3717 IntTy,
3718 llvm::ArrayType::get(
3719 IvarnfABITy, 0),
3720 NULL);
3721 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3722
3723 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003724
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003725 // struct _class_ro_t {
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003726 // uint32_t const flags;
3727 // uint32_t const instanceStart;
3728 // uint32_t const instanceSize;
3729 // uint32_t const reserved; // only when building for 64bit targets
3730 // const uint8_t * const ivarLayout;
3731 // const char *const name;
3732 // const struct _method_list_t * const baseMethods;
3733 // const struct _objc_protocol_list *const baseProtocols;
3734 // const struct _ivar_list_t *const ivars;
3735 // const uint8_t * const weakIvarLayout;
3736 // const struct _prop_list_t * const properties;
3737 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003738
3739 // FIXME. Add 'reserved' field in 64bit abi mode!
3740 ClassRonfABITy = llvm::StructType::get(IntTy,
3741 IntTy,
3742 IntTy,
3743 Int8PtrTy,
3744 Int8PtrTy,
3745 MethodListnfABIPtrTy,
3746 ProtocolListnfABIPtrTy,
3747 IvarListnfABIPtrTy,
3748 Int8PtrTy,
3749 PropertyListPtrTy,
3750 NULL);
3751 CGM.getModule().addTypeName("struct._class_ro_t",
3752 ClassRonfABITy);
3753
3754 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3755 std::vector<const llvm::Type*> Params;
3756 Params.push_back(ObjectPtrTy);
3757 Params.push_back(SelectorPtrTy);
3758 ImpnfABITy = llvm::PointerType::getUnqual(
3759 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3760
3761 // struct _class_t {
3762 // struct _class_t *isa;
3763 // struct _class_t * const superclass;
3764 // void *cache;
3765 // IMP *vtable;
3766 // struct class_ro_t *ro;
3767 // }
3768
3769 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3770 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3771 llvm::PointerType::getUnqual(ClassTyHolder),
3772 CachePtrTy,
3773 llvm::PointerType::getUnqual(ImpnfABITy),
3774 llvm::PointerType::getUnqual(
3775 ClassRonfABITy),
3776 NULL);
3777 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3778
3779 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3780 ClassnfABITy);
3781
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003782 // LLVM for struct _class_t *
3783 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3784
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003785 // struct _category_t {
3786 // const char * const name;
3787 // struct _class_t *const cls;
3788 // const struct _method_list_t * const instance_methods;
3789 // const struct _method_list_t * const class_methods;
3790 // const struct _protocol_list_t * const protocols;
3791 // const struct _prop_list_t * const properties;
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003792 // }
3793 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003794 ClassnfABIPtrTy,
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003795 MethodListnfABIPtrTy,
3796 MethodListnfABIPtrTy,
3797 ProtocolListnfABIPtrTy,
3798 PropertyListPtrTy,
3799 NULL);
3800 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003801
3802 // New types for nonfragile abi messaging.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003803 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3804 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003805
3806 // MessageRefTy - LLVM for:
3807 // struct _message_ref_t {
3808 // IMP messenger;
3809 // SEL name;
3810 // };
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003811
3812 // First the clang type for struct _message_ref_t
3813 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3814 SourceLocation(),
3815 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003816 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3817 Ctx.VoidPtrTy, 0, false));
3818 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3819 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003820 RD->completeDefinition(Ctx);
3821
3822 MessageRefCTy = Ctx.getTagDeclType(RD);
3823 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3824 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003825
3826 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3827 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3828
3829 // SuperMessageRefTy - LLVM for:
3830 // struct _super_message_ref_t {
3831 // SUPER_IMP messenger;
3832 // SEL name;
3833 // };
3834 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3835 SelectorPtrTy,
3836 NULL);
3837 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3838
3839 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3840 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3841
3842 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3843 Params.clear();
3844 Params.push_back(ObjectPtrTy);
3845 Params.push_back(MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00003846 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3847 Params,
3848 true);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003849 MessageSendFixupFn =
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00003850 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003851 "objc_msgSend_fixup");
3852
3853 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3854 MessageSendFpretFixupFn =
3855 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3856 Params,
3857 true),
3858 "objc_msgSend_fpret_fixup");
3859
3860 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3861 MessageSendStretFixupFn =
3862 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3863 Params,
3864 true),
3865 "objc_msgSend_stret_fixup");
3866
3867 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3868 MessageSendIdFixupFn =
3869 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3870 Params,
3871 true),
3872 "objc_msgSendId_fixup");
3873
3874
3875 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3876 MessageSendIdStretFixupFn =
3877 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3878 Params,
3879 true),
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003880 "objc_msgSendId_stret_fixup");
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003881
3882 // id objc_msgSendSuper2_fixup (struct objc_super *,
3883 // struct _super_message_ref_t*, ...)
3884 Params.clear();
3885 Params.push_back(SuperPtrTy);
3886 Params.push_back(SuperMessageRefPtrTy);
3887 MessageSendSuper2FixupFn =
3888 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3889 Params,
3890 true),
3891 "objc_msgSendSuper2_fixup");
3892
3893
3894 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3895 // struct _super_message_ref_t*, ...)
3896 MessageSendSuper2StretFixupFn =
3897 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3898 Params,
3899 true),
3900 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00003901
3902 Params.clear();
Daniel Dunbar75de89f2009-02-24 07:47:38 +00003903 Params.push_back(Int8PtrTy);
3904 UnwindResumeOrRethrowFn =
3905 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3906 Params,
3907 false),
3908 "_Unwind_Resume_or_Rethrow");
Daniel Dunbar9c285e72009-03-01 04:46:24 +00003909 ObjCBeginCatchFn =
3910 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3911 Params,
3912 false),
3913 "objc_begin_catch");
3914
3915 Params.clear();
3916 ObjCEndCatchFn =
3917 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3918 Params,
3919 false),
3920 "objc_end_catch");
3921
3922 // struct objc_typeinfo {
3923 // const void** vtable; // objc_ehtype_vtable + 2
3924 // const char* name; // c++ typeinfo string
3925 // Class cls;
3926 // };
3927 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3928 Int8PtrTy,
3929 ClassnfABIPtrTy,
3930 NULL);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00003931 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00003932 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003933}
3934
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003935llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3936 FinishNonFragileABIModule();
3937
3938 return NULL;
3939}
3940
3941void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3942 // nonfragile abi has no module definition.
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00003943
3944 // Build list of all implemented classe addresses in array
3945 // L_OBJC_LABEL_CLASS_$.
3946 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3947 // list of 'nonlazy' implementations (defined as those with a +load{}
3948 // method!!).
3949 unsigned NumClasses = DefinedClasses.size();
3950 if (NumClasses) {
3951 std::vector<llvm::Constant*> Symbols(NumClasses);
3952 for (unsigned i=0; i<NumClasses; i++)
3953 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3954 ObjCTypes.Int8PtrTy);
3955 llvm::Constant* Init =
3956 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3957 NumClasses),
3958 Symbols);
3959
3960 llvm::GlobalVariable *GV =
3961 new llvm::GlobalVariable(Init->getType(), false,
3962 llvm::GlobalValue::InternalLinkage,
3963 Init,
3964 "\01L_OBJC_LABEL_CLASS_$",
3965 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00003966 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00003967 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3968 UsedGlobals.push_back(GV);
3969 }
3970
3971 // Build list of all implemented category addresses in array
3972 // L_OBJC_LABEL_CATEGORY_$.
3973 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3974 // list of 'nonlazy' category implementations (defined as those with a +load{}
3975 // method!!).
3976 unsigned NumCategory = DefinedCategories.size();
3977 if (NumCategory) {
3978 std::vector<llvm::Constant*> Symbols(NumCategory);
3979 for (unsigned i=0; i<NumCategory; i++)
3980 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3981 ObjCTypes.Int8PtrTy);
3982 llvm::Constant* Init =
3983 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3984 NumCategory),
3985 Symbols);
3986
3987 llvm::GlobalVariable *GV =
3988 new llvm::GlobalVariable(Init->getType(), false,
3989 llvm::GlobalValue::InternalLinkage,
3990 Init,
3991 "\01L_OBJC_LABEL_CATEGORY_$",
3992 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00003993 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00003994 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3995 UsedGlobals.push_back(GV);
3996 }
3997
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00003998 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3999 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4000 std::vector<llvm::Constant*> Values(2);
4001 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004002 unsigned int flags = 0;
Fariborz Jahanian27f58962009-02-24 23:34:44 +00004003 // FIXME: Fix and continue?
4004 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4005 flags |= eImageInfo_GarbageCollected;
4006 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4007 flags |= eImageInfo_GCOnly;
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004008 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004009 llvm::Constant* Init = llvm::ConstantArray::get(
4010 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4011 Values);
4012 llvm::GlobalVariable *IMGV =
4013 new llvm::GlobalVariable(Init->getType(), false,
4014 llvm::GlobalValue::InternalLinkage,
4015 Init,
4016 "\01L_OBJC_IMAGE_INFO",
4017 &CGM.getModule());
4018 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4019 UsedGlobals.push_back(IMGV);
4020
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004021 std::vector<llvm::Constant*> Used;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004022
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004023 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4024 e = UsedGlobals.end(); i != e; ++i) {
4025 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4026 }
Fariborz Jahanianab438842009-04-14 18:41:56 +00004027
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004028 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4029 llvm::GlobalValue *GV =
4030 new llvm::GlobalVariable(AT, false,
4031 llvm::GlobalValue::AppendingLinkage,
4032 llvm::ConstantArray::get(AT, Used),
4033 "llvm.used",
4034 &CGM.getModule());
4035
4036 GV->setSection("llvm.metadata");
4037
4038}
4039
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004040// Metadata flags
4041enum MetaDataDlags {
4042 CLS = 0x0,
4043 CLS_META = 0x1,
4044 CLS_ROOT = 0x2,
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004045 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004046 CLS_EXCEPTION = 0x20
4047};
4048/// BuildClassRoTInitializer - generate meta-data for:
4049/// struct _class_ro_t {
4050/// uint32_t const flags;
4051/// uint32_t const instanceStart;
4052/// uint32_t const instanceSize;
4053/// uint32_t const reserved; // only when building for 64bit targets
4054/// const uint8_t * const ivarLayout;
4055/// const char *const name;
4056/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004057/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004058/// const struct _ivar_list_t *const ivars;
4059/// const uint8_t * const weakIvarLayout;
4060/// const struct _prop_list_t * const properties;
4061/// }
4062///
4063llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4064 unsigned flags,
4065 unsigned InstanceStart,
4066 unsigned InstanceSize,
4067 const ObjCImplementationDecl *ID) {
4068 std::string ClassName = ID->getNameAsString();
4069 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4070 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4071 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4072 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4073 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004074 // FIXME. ivarLayout is currently null!
Fariborz Jahanian31614742009-04-20 22:03:45 +00004075 // Values[ 3] = BuildIvarLayout(ID, true);
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00004076 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004077 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004078 // const struct _method_list_t * const baseMethods;
4079 std::vector<llvm::Constant*> Methods;
4080 std::string MethodListName("\01l_OBJC_$_");
4081 if (flags & CLS_META) {
4082 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4083 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4084 e = ID->classmeth_end(); i != e; ++i) {
4085 // Class methods should always be defined.
4086 Methods.push_back(GetMethodConstant(*i));
4087 }
4088 } else {
4089 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4090 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4091 e = ID->instmeth_end(); i != e; ++i) {
4092 // Instance methods should always be defined.
4093 Methods.push_back(GetMethodConstant(*i));
4094 }
Fariborz Jahanian78355ec2009-01-28 22:46:49 +00004095 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4096 e = ID->propimpl_end(); i != e; ++i) {
4097 ObjCPropertyImplDecl *PID = *i;
4098
4099 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4100 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4101
4102 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4103 if (llvm::Constant *C = GetMethodConstant(MD))
4104 Methods.push_back(C);
4105 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4106 if (llvm::Constant *C = GetMethodConstant(MD))
4107 Methods.push_back(C);
4108 }
4109 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004110 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004111 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004112 "__DATA, __objc_const", Methods);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004113
4114 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4115 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4116 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4117 + OID->getNameAsString(),
4118 OID->protocol_begin(),
4119 OID->protocol_end());
4120
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004121 if (flags & CLS_META)
4122 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4123 else
4124 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004125 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian31614742009-04-20 22:03:45 +00004126 // Values[ 8] = BuildIvarLayout(ID, false);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00004127 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004128 if (flags & CLS_META)
4129 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4130 else
4131 Values[ 9] =
4132 EmitPropertyList(
4133 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4134 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004135 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4136 Values);
4137 llvm::GlobalVariable *CLASS_RO_GV =
4138 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4139 llvm::GlobalValue::InternalLinkage,
4140 Init,
4141 (flags & CLS_META) ?
4142 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4143 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4144 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004145 CLASS_RO_GV->setAlignment(
4146 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004147 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004148 return CLASS_RO_GV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004149
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004150}
4151
4152/// BuildClassMetaData - This routine defines that to-level meta-data
4153/// for the given ClassName for:
4154/// struct _class_t {
4155/// struct _class_t *isa;
4156/// struct _class_t * const superclass;
4157/// void *cache;
4158/// IMP *vtable;
4159/// struct class_ro_t *ro;
4160/// }
4161///
Fariborz Jahanian06726462009-01-24 21:21:53 +00004162llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4163 std::string &ClassName,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004164 llvm::Constant *IsAGV,
4165 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004166 llvm::Constant *ClassRoGV,
4167 bool HiddenVisibility) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004168 std::vector<llvm::Constant*> Values(5);
4169 Values[0] = IsAGV;
Fariborz Jahanian06726462009-01-24 21:21:53 +00004170 Values[1] = SuperClassGV
4171 ? SuperClassGV
4172 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004173 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4174 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4175 Values[4] = ClassRoGV; // &CLASS_RO_GV
4176 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4177 Values);
Daniel Dunbarabbda222009-03-01 04:40:10 +00004178 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4179 GV->setInitializer(Init);
Fariborz Jahanian7c891592009-01-31 01:07:39 +00004180 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004181 GV->setAlignment(
4182 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004183 if (HiddenVisibility)
4184 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004185 return GV;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004186}
4187
Daniel Dunbar72878722009-04-20 20:18:54 +00004188/// countInheritedIvars - count number of ivars in class and its super class(s)
4189///
4190static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4191 ASTContext &Context) {
4192 int count = 0;
4193 if (!OI)
4194 return 0;
4195 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4196 if (SuperClass)
4197 count += countInheritedIvars(SuperClass, Context);
4198 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4199 E = OI->ivar_end(); I != E; ++I)
4200 ++count;
4201 // look into properties.
4202 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4203 E = OI->prop_end(Context); I != E; ++I) {
4204 if ((*I)->getPropertyIvarDecl())
4205 ++count;
4206 }
4207 return count;
4208}
4209
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004210void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4211 uint32_t &InstanceStart,
4212 uint32_t &InstanceSize) {
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004213 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4214
Daniel Dunbarde585722009-04-20 07:18:49 +00004215 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4216 CGM.getContext());
4217 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4218 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4219 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4220 while (countSuperClassIvars-- > 0) {
4221 lastField = firstField;
4222 ++firstField;
4223 }
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004224
4225 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4226 ifield = firstField; ifield != e; ++ifield)
4227 lastField = ifield;
4228
4229 InstanceStart = InstanceSize = 0;
4230 if (lastField != RD->field_end(CGM.getContext())) {
4231 FieldDecl *Field = *lastField;
4232 const llvm::Type *FieldTy =
4233 CGM.getTypes().ConvertTypeForMem(Field->getType());
4234 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4235 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4236 if (firstField == RD->field_end(CGM.getContext()))
4237 InstanceStart = InstanceSize;
4238 else {
4239 Field = *firstField;
4240 InstanceStart = GetIvarBaseOffset(Layout, Field);
4241 }
4242 }
4243}
4244
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004245void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4246 std::string ClassName = ID->getNameAsString();
4247 if (!ObjCEmptyCacheVar) {
4248 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004249 ObjCTypes.CacheTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004250 false,
4251 llvm::GlobalValue::ExternalLinkage,
4252 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004253 "_objc_empty_cache",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004254 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004255
4256 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004257 ObjCTypes.ImpnfABITy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004258 false,
4259 llvm::GlobalValue::ExternalLinkage,
4260 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004261 "_objc_empty_vtable",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004262 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004263 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004264 assert(ID->getClassInterface() &&
4265 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar72878722009-04-20 20:18:54 +00004266 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004267 uint32_t InstanceStart =
4268 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4269 uint32_t InstanceSize = InstanceStart;
4270 uint32_t flags = CLS_META;
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004271 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4272 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004273
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004274 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004275
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004276 bool classIsHidden =
4277 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004278 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004279 flags |= OBJC2_CLS_HIDDEN;
4280 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004281 // class is root
4282 flags |= CLS_ROOT;
Daniel Dunbarabbda222009-03-01 04:40:10 +00004283 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanianab438842009-04-14 18:41:56 +00004284 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004285 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004286 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004287 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4288 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4289 Root = Super;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004290 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004291 // work on super class metadata symbol.
4292 std::string SuperClassName =
4293 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanianab438842009-04-14 18:41:56 +00004294 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004295 }
4296 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4297 InstanceStart,
4298 InstanceSize,ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004299 std::string TClassName = ObjCMetaClassName + ClassName;
4300 llvm::GlobalVariable *MetaTClass =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004301 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4302 classIsHidden);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004303
Fariborz Jahanian06726462009-01-24 21:21:53 +00004304 // Metadata for the class
4305 flags = CLS;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004306 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004307 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbarc2129532009-04-08 04:21:03 +00004308
4309 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4310 flags |= CLS_EXCEPTION;
4311
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004312 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004313 flags |= CLS_ROOT;
4314 SuperClassGV = 0;
Chris Lattner9fe470d2009-04-19 06:02:28 +00004315 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004316 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004317 std::string RootClassName =
Fariborz Jahanian06726462009-01-24 21:21:53 +00004318 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbarabbda222009-03-01 04:40:10 +00004319 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004320 }
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004321 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004322 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianddd2fdd2009-01-24 23:43:01 +00004323 InstanceStart,
4324 InstanceSize,
4325 ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004326
4327 TClassName = ObjCClassName + ClassName;
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004328 llvm::GlobalVariable *ClassMD =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004329 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4330 classIsHidden);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004331 DefinedClasses.push_back(ClassMD);
Daniel Dunbarc2129532009-04-08 04:21:03 +00004332
4333 // Force the definition of the EHType if necessary.
4334 if (flags & CLS_EXCEPTION)
4335 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004336}
4337
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004338/// GenerateProtocolRef - This routine is called to generate code for
4339/// a protocol reference expression; as in:
4340/// @code
4341/// @protocol(Proto1);
4342/// @endcode
4343/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4344/// which will hold address of the protocol meta-data.
4345///
4346llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4347 const ObjCProtocolDecl *PD) {
4348
Fariborz Jahaniand3243322009-04-10 18:47:34 +00004349 // This routine is called for @protocol only. So, we must build definition
4350 // of protocol's meta-data (not a reference to it!)
4351 //
4352 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004353 ObjCTypes.ExternalProtocolPtrTy);
4354
4355 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4356 ProtocolName += PD->getNameAsCString();
4357
4358 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4359 if (PTGV)
4360 return Builder.CreateLoad(PTGV, false, "tmp");
4361 PTGV = new llvm::GlobalVariable(
4362 Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00004363 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004364 Init,
4365 ProtocolName,
4366 &CGM.getModule());
4367 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4368 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4369 UsedGlobals.push_back(PTGV);
4370 return Builder.CreateLoad(PTGV, false, "tmp");
4371}
4372
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004373/// GenerateCategory - Build metadata for a category implementation.
4374/// struct _category_t {
4375/// const char * const name;
4376/// struct _class_t *const cls;
4377/// const struct _method_list_t * const instance_methods;
4378/// const struct _method_list_t * const class_methods;
4379/// const struct _protocol_list_t * const protocols;
4380/// const struct _prop_list_t * const properties;
4381/// }
4382///
4383void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4384{
4385 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004386 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4387 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004388 "_$_" + OCD->getNameAsString());
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004389 std::string ExtClassName(getClassSymbolPrefix() +
4390 Interface->getNameAsString());
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004391
4392 std::vector<llvm::Constant*> Values(6);
4393 Values[0] = GetClassName(OCD->getIdentifier());
4394 // meta-class entry symbol
Daniel Dunbarabbda222009-03-01 04:40:10 +00004395 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004396 Values[1] = ClassGV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004397 std::vector<llvm::Constant*> Methods;
4398 std::string MethodListName(Prefix);
4399 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4400 "_$_" + OCD->getNameAsString();
4401
4402 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4403 e = OCD->instmeth_end(); i != e; ++i) {
4404 // Instance methods should always be defined.
4405 Methods.push_back(GetMethodConstant(*i));
4406 }
4407
4408 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004409 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004410 Methods);
4411
4412 MethodListName = Prefix;
4413 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4414 OCD->getNameAsString();
4415 Methods.clear();
4416 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4417 e = OCD->classmeth_end(); i != e; ++i) {
4418 // Class methods should always be defined.
4419 Methods.push_back(GetMethodConstant(*i));
4420 }
4421
4422 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004423 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004424 Methods);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004425 const ObjCCategoryDecl *Category =
4426 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian8c7904b2009-02-13 17:52:22 +00004427 if (Category) {
4428 std::string ExtName(Interface->getNameAsString() + "_$_" +
4429 OCD->getNameAsString());
4430 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4431 + Interface->getNameAsString() + "_$_"
4432 + Category->getNameAsString(),
4433 Category->protocol_begin(),
4434 Category->protocol_end());
4435 Values[5] =
4436 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4437 OCD, Category, ObjCTypes);
4438 }
4439 else {
4440 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4441 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4442 }
4443
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004444 llvm::Constant *Init =
4445 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4446 Values);
4447 llvm::GlobalVariable *GCATV
4448 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4449 false,
4450 llvm::GlobalValue::InternalLinkage,
4451 Init,
4452 ExtCatName,
4453 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004454 GCATV->setAlignment(
4455 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004456 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004457 UsedGlobals.push_back(GCATV);
4458 DefinedCategories.push_back(GCATV);
4459}
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004460
4461/// GetMethodConstant - Return a struct objc_method constant for the
4462/// given method if it has been defined. The result is null if the
4463/// method has not been defined. The return value has type MethodPtrTy.
4464llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4465 const ObjCMethodDecl *MD) {
4466 // FIXME: Use DenseMap::lookup
4467 llvm::Function *Fn = MethodDefinitions[MD];
4468 if (!Fn)
4469 return 0;
4470
4471 std::vector<llvm::Constant*> Method(3);
4472 Method[0] =
4473 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4474 ObjCTypes.SelectorPtrTy);
4475 Method[1] = GetMethodVarType(MD);
4476 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4477 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4478}
4479
4480/// EmitMethodList - Build meta-data for method declarations
4481/// struct _method_list_t {
4482/// uint32_t entsize; // sizeof(struct _objc_method)
4483/// uint32_t method_count;
4484/// struct _objc_method method_list[method_count];
4485/// }
4486///
4487llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4488 const std::string &Name,
4489 const char *Section,
4490 const ConstantVector &Methods) {
4491 // Return null for empty list.
4492 if (Methods.empty())
4493 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4494
4495 std::vector<llvm::Constant*> Values(3);
4496 // sizeof(struct _objc_method)
4497 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4498 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4499 // method_count
4500 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4501 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4502 Methods.size());
4503 Values[2] = llvm::ConstantArray::get(AT, Methods);
4504 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4505
4506 llvm::GlobalVariable *GV =
4507 new llvm::GlobalVariable(Init->getType(), false,
4508 llvm::GlobalValue::InternalLinkage,
4509 Init,
4510 Name,
4511 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004512 GV->setAlignment(
4513 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004514 GV->setSection(Section);
4515 UsedGlobals.push_back(GV);
4516 return llvm::ConstantExpr::getBitCast(GV,
4517 ObjCTypes.MethodListnfABIPtrTy);
4518}
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004519
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004520/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4521/// the given ivar.
4522///
4523llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00004524 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004525 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004526 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004527 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4528 '.' + Ivar->getNameAsString();
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004529 llvm::GlobalVariable *IvarOffsetGV =
4530 CGM.getModule().getGlobalVariable(Name);
4531 if (!IvarOffsetGV)
4532 IvarOffsetGV =
4533 new llvm::GlobalVariable(ObjCTypes.LongTy,
4534 false,
4535 llvm::GlobalValue::ExternalLinkage,
4536 0,
4537 Name,
4538 &CGM.getModule());
4539 return IvarOffsetGV;
4540}
4541
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004542llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004543 const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004544 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004545 unsigned long int Offset) {
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004546 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4547 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4548 Offset));
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004549 IvarOffsetGV->setAlignment(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004550 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004551
4552 // FIXME: This matches gcc, but shouldn't the visibility be set on
4553 // the use as well (i.e., in ObjCIvarOffsetVariable).
4554 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4555 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4556 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004557 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004558 else
Fariborz Jahanian745fd892009-04-06 18:30:00 +00004559 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004560 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian55343922009-02-03 00:09:52 +00004561 return IvarOffsetGV;
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004562}
4563
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004564/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar3c190812009-04-18 08:51:00 +00004565/// implementation. The return value has type
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004566/// IvarListnfABIPtrTy.
4567/// struct _ivar_t {
4568/// unsigned long int *offset; // pointer to ivar offset location
4569/// char *name;
4570/// char *type;
4571/// uint32_t alignment;
4572/// uint32_t size;
4573/// }
4574/// struct _ivar_list_t {
4575/// uint32 entsize; // sizeof(struct _ivar_t)
4576/// uint32 count;
4577/// struct _iver_t list[count];
4578/// }
4579///
Daniel Dunbar356f0742009-04-20 06:54:31 +00004580
4581void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4582 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4583 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4584 E = OID->ivar_end(); I != E; ++I) {
4585 // Ignore unnamed bit-fields.
4586 if (!(*I)->getDeclName())
4587 continue;
4588
4589 Res.push_back(*I);
4590 }
4591
4592 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4593 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4594 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4595 Res.push_back(IV);
4596}
4597
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004598llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4599 const ObjCImplementationDecl *ID) {
4600
4601 std::vector<llvm::Constant*> Ivars, Ivar(5);
4602
4603 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4604 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4605
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004606 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00004607 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00004608
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004609 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanianfbf44642009-03-31 18:11:23 +00004610 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar356f0742009-04-20 06:54:31 +00004611 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian84c45692009-04-01 19:37:34 +00004612
Daniel Dunbar356f0742009-04-20 06:54:31 +00004613 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4614 ObjCIvarDecl *IVD = OIvars[i];
4615 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004616 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00004617 GetIvarBaseOffset(Layout, Field));
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004618 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel593a07a2009-03-04 18:21:39 +00004619 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004620 const llvm::Type *FieldTy =
4621 CGM.getTypes().ConvertTypeForMem(Field->getType());
4622 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4623 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4624 Field->getType().getTypePtr()) >> 3;
4625 Align = llvm::Log2_32(Align);
4626 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004627 // NOTE. Size of a bitfield does not match gcc's, because of the
4628 // way bitfields are treated special in each. But I am told that
4629 // 'size' for bitfield ivars is ignored by the runtime so it does
4630 // not matter. If it matters, there is enough info to get the
4631 // bitfield right!
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004632 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4633 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4634 }
4635 // Return null for empty list.
4636 if (Ivars.empty())
4637 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4638 std::vector<llvm::Constant*> Values(3);
4639 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4640 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4641 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4642 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4643 Ivars.size());
4644 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4645 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4646 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4647 llvm::GlobalVariable *GV =
4648 new llvm::GlobalVariable(Init->getType(), false,
4649 llvm::GlobalValue::InternalLinkage,
4650 Init,
4651 Prefix + OID->getNameAsString(),
4652 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004653 GV->setAlignment(
4654 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004655 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004656
4657 UsedGlobals.push_back(GV);
4658 return llvm::ConstantExpr::getBitCast(GV,
4659 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004660}
4661
4662llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4663 const ObjCProtocolDecl *PD) {
4664 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4665
4666 if (!Entry) {
4667 // We use the initializer as a marker of whether this is a forward
4668 // reference or not. At module finalization we add the empty
4669 // contents for protocols which were referenced but never defined.
4670 Entry =
4671 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4672 llvm::GlobalValue::ExternalLinkage,
4673 0,
4674 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4675 &CGM.getModule());
4676 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4677 UsedGlobals.push_back(Entry);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004678 }
4679
4680 return Entry;
4681}
4682
4683/// GetOrEmitProtocol - Generate the protocol meta-data:
4684/// @code
4685/// struct _protocol_t {
4686/// id isa; // NULL
4687/// const char * const protocol_name;
4688/// const struct _protocol_list_t * protocol_list; // super protocols
4689/// const struct method_list_t * const instance_methods;
4690/// const struct method_list_t * const class_methods;
4691/// const struct method_list_t *optionalInstanceMethods;
4692/// const struct method_list_t *optionalClassMethods;
4693/// const struct _prop_list_t * properties;
4694/// const uint32_t size; // sizeof(struct _protocol_t)
4695/// const uint32_t flags; // = 0
4696/// }
4697/// @endcode
4698///
4699
4700llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4701 const ObjCProtocolDecl *PD) {
4702 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4703
4704 // Early exit if a defining object has already been generated.
4705 if (Entry && Entry->hasInitializer())
4706 return Entry;
4707
4708 const char *ProtocolName = PD->getNameAsCString();
4709
4710 // Construct method lists.
4711 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4712 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004713 for (ObjCProtocolDecl::instmeth_iterator
4714 i = PD->instmeth_begin(CGM.getContext()),
4715 e = PD->instmeth_end(CGM.getContext());
4716 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004717 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004718 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004719 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4720 OptInstanceMethods.push_back(C);
4721 } else {
4722 InstanceMethods.push_back(C);
4723 }
4724 }
4725
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004726 for (ObjCProtocolDecl::classmeth_iterator
4727 i = PD->classmeth_begin(CGM.getContext()),
4728 e = PD->classmeth_end(CGM.getContext());
4729 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004730 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004731 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004732 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4733 OptClassMethods.push_back(C);
4734 } else {
4735 ClassMethods.push_back(C);
4736 }
4737 }
4738
4739 std::vector<llvm::Constant*> Values(10);
4740 // isa is NULL
4741 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4742 Values[1] = GetClassName(PD->getIdentifier());
4743 Values[2] = EmitProtocolList(
4744 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4745 PD->protocol_begin(),
4746 PD->protocol_end());
4747
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004748 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004749 + PD->getNameAsString(),
4750 "__DATA, __objc_const",
4751 InstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004752 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004753 + PD->getNameAsString(),
4754 "__DATA, __objc_const",
4755 ClassMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004756 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004757 + PD->getNameAsString(),
4758 "__DATA, __objc_const",
4759 OptInstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004760 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004761 + PD->getNameAsString(),
4762 "__DATA, __objc_const",
4763 OptClassMethods);
4764 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4765 0, PD, ObjCTypes);
4766 uint32_t Size =
4767 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4768 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4769 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4770 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4771 Values);
4772
4773 if (Entry) {
4774 // Already created, fix the linkage and update the initializer.
Mike Stump36dbf222009-03-07 16:33:28 +00004775 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004776 Entry->setInitializer(Init);
4777 } else {
4778 Entry =
4779 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004780 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004781 Init,
4782 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4783 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004784 Entry->setAlignment(
4785 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004786 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004787 }
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004788 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4789
4790 // Use this protocol meta-data to build protocol list table in section
4791 // __DATA, __objc_protolist
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004792 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004793 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004794 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004795 Entry,
4796 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4797 +ProtocolName,
4798 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004799 PTGV->setAlignment(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004800 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00004801 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004802 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4803 UsedGlobals.push_back(PTGV);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004804 return Entry;
4805}
4806
4807/// EmitProtocolList - Generate protocol list meta-data:
4808/// @code
4809/// struct _protocol_list_t {
4810/// long protocol_count; // Note, this is 32/64 bit
4811/// struct _protocol_t[protocol_count];
4812/// }
4813/// @endcode
4814///
4815llvm::Constant *
4816CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4817 ObjCProtocolDecl::protocol_iterator begin,
4818 ObjCProtocolDecl::protocol_iterator end) {
4819 std::vector<llvm::Constant*> ProtocolRefs;
4820
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004821 // Just return null for empty protocol lists
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004822 if (begin == end)
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004823 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4824
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004825 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004826 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4827 if (GV)
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004828 return llvm::ConstantExpr::getBitCast(GV,
4829 ObjCTypes.ProtocolListnfABIPtrTy);
4830
4831 for (; begin != end; ++begin)
4832 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4833
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004834 // This list is null terminated.
4835 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004836 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004837
4838 std::vector<llvm::Constant*> Values(2);
4839 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4840 Values[1] =
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004841 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004842 ProtocolRefs.size()),
4843 ProtocolRefs);
4844
4845 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4846 GV = new llvm::GlobalVariable(Init->getType(), false,
4847 llvm::GlobalValue::InternalLinkage,
4848 Init,
4849 Name,
4850 &CGM.getModule());
4851 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004852 GV->setAlignment(
4853 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004854 UsedGlobals.push_back(GV);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004855 return llvm::ConstantExpr::getBitCast(GV,
4856 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004857}
4858
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004859/// GetMethodDescriptionConstant - This routine build following meta-data:
4860/// struct _objc_method {
4861/// SEL _cmd;
4862/// char *method_type;
4863/// char *_imp;
4864/// }
4865
4866llvm::Constant *
4867CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4868 std::vector<llvm::Constant*> Desc(3);
4869 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4870 ObjCTypes.SelectorPtrTy);
4871 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004872 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004873 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4874 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4875}
Fariborz Jahanian55343922009-02-03 00:09:52 +00004876
4877/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4878/// This code gen. amounts to generating code for:
4879/// @code
4880/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4881/// @encode
4882///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004883LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004884 CodeGen::CodeGenFunction &CGF,
4885 QualType ObjectTy,
4886 llvm::Value *BaseValue,
4887 const ObjCIvarDecl *Ivar,
Fariborz Jahanian55343922009-02-03 00:09:52 +00004888 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00004889 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4890 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004891 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004892
Fariborz Jahanian55343922009-02-03 00:09:52 +00004893 // (char *) BaseValue
Chris Lattnerbb87be22009-04-17 17:46:19 +00004894 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian55343922009-02-03 00:09:52 +00004895 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4896 // (char*)BaseValue + Offset_symbol
4897 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4898 // (type *)((char*)BaseValue + Offset_symbol)
4899 const llvm::Type *IvarTy =
Chris Lattnerbb87be22009-04-17 17:46:19 +00004900 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian55343922009-02-03 00:09:52 +00004901 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4902 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004903
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004904 if (Ivar->isBitField()) {
Chris Lattnerbb87be22009-04-17 17:46:19 +00004905 QualType FieldTy = Field->getType();
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004906 CodeGenTypes::BitFieldInfo bitFieldInfo =
4907 CGM.getTypes().getBitFieldInfo(Field);
4908 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattnerbb87be22009-04-17 17:46:19 +00004909 FieldTy->isSignedIntegerType(),
4910 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahanian40a94a92009-03-09 20:44:22 +00004911 }
4912
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004913 LValue LV = LValue::MakeAddr(V,
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00004914 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4915 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004916 LValue::SetObjCIvar(LV, true);
4917 return LV;
Fariborz Jahanian55343922009-02-03 00:09:52 +00004918}
4919
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004920llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4921 CodeGen::CodeGenFunction &CGF,
4922 ObjCInterfaceDecl *Interface,
4923 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004924 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4925 false, "ivar");
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004926}
4927
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004928CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4929 CodeGen::CodeGenFunction &CGF,
4930 QualType ResultType,
4931 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004932 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004933 QualType Arg0Ty,
4934 bool IsSuper,
4935 const CallArgList &CallArgs) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004936 // FIXME. Even though IsSuper is passes. This function doese not
4937 // handle calls to 'super' receivers.
4938 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004939 llvm::Value *Arg0 = Receiver;
4940 if (!IsSuper)
4941 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004942
4943 // Find the message function name.
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00004944 // FIXME. This is too much work to get the ABI-specific result type
4945 // needed to find the message name.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004946 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4947 llvm::SmallVector<QualType, 16>());
4948 llvm::Constant *Fn;
4949 std::string Name("\01l_");
4950 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004951#if 0
4952 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004953 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4954 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4955 // FIXME. Is there a better way of getting these names.
4956 // They are available in RuntimeFunctions vector pair.
4957 Name += "objc_msgSendId_stret_fixup";
4958 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004959 else
4960#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004961 if (IsSuper) {
4962 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4963 Name += "objc_msgSendSuper2_stret_fixup";
4964 }
4965 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004966 {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004967 Fn = ObjCTypes.MessageSendStretFixupFn;
4968 Name += "objc_msgSend_stret_fixup";
4969 }
4970 }
Fariborz Jahanianbea03192009-02-05 19:35:43 +00004971 else if (ResultType->isFloatingType() &&
4972 // Selection of frret API only happens in 32bit nonfragile ABI.
4973 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004974 Fn = ObjCTypes.MessageSendFpretFixupFn;
4975 Name += "objc_msgSend_fpret_fixup";
4976 }
4977 else {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004978#if 0
4979// unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004980 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4981 Fn = ObjCTypes.MessageSendIdFixupFn;
4982 Name += "objc_msgSendId_fixup";
4983 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004984 else
4985#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004986 if (IsSuper) {
4987 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4988 Name += "objc_msgSendSuper2_fixup";
4989 }
4990 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00004991 {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004992 Fn = ObjCTypes.MessageSendFixupFn;
4993 Name += "objc_msgSend_fixup";
4994 }
4995 }
4996 Name += '_';
4997 std::string SelName(Sel.getAsString());
4998 // Replace all ':' in selector name with '_' ouch!
4999 for(unsigned i = 0; i < SelName.size(); i++)
5000 if (SelName[i] == ':')
5001 SelName[i] = '_';
5002 Name += SelName;
5003 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5004 if (!GV) {
Daniel Dunbar4993e292009-04-15 19:03:14 +00005005 // Build message ref table entry.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005006 std::vector<llvm::Constant*> Values(2);
5007 Values[0] = Fn;
5008 Values[1] = GetMethodVarName(Sel);
5009 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5010 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00005011 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005012 Init,
5013 Name,
5014 &CGM.getModule());
5015 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbara405f782009-04-15 19:04:46 +00005016 GV->setAlignment(16);
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005017 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005018 }
5019 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005020
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005021 CallArgList ActualArgs;
5022 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5023 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5024 ObjCTypes.MessageRefCPtrTy));
5025 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005026 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5027 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5028 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanianf3c17752009-02-14 21:25:36 +00005029 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005030 Callee = CGF.Builder.CreateBitCast(Callee,
5031 llvm::PointerType::getUnqual(FTy));
5032 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005033}
5034
5035/// Generate code for a message send expression in the nonfragile abi.
5036CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5037 CodeGen::CodeGenFunction &CGF,
5038 QualType ResultType,
5039 Selector Sel,
5040 llvm::Value *Receiver,
5041 bool IsClassMessage,
5042 const CallArgList &CallArgs) {
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005043 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005044 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005045 false, CallArgs);
5046}
5047
Daniel Dunbarabbda222009-03-01 04:40:10 +00005048llvm::GlobalVariable *
Fariborz Jahanianab438842009-04-14 18:41:56 +00005049CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005050 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5051
Daniel Dunbar66b47512009-03-02 05:18:14 +00005052 if (!GV) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005053 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5054 llvm::GlobalValue::ExternalLinkage,
5055 0, Name, &CGM.getModule());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005056 }
5057
5058 return GV;
5059}
5060
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005061llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005062 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005063 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5064
5065 if (!Entry) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005066 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005067 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005068 Entry =
5069 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5070 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005071 ClassGV,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005072 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005073 &CGM.getModule());
5074 Entry->setAlignment(
5075 CGM.getTargetData().getPrefTypeAlignment(
5076 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar3c190812009-04-18 08:51:00 +00005077 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5078 UsedGlobals.push_back(Entry);
5079 }
5080
5081 return Builder.CreateLoad(Entry, false, "tmp");
5082}
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005083
Daniel Dunbar3c190812009-04-18 08:51:00 +00005084llvm::Value *
5085CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5086 const ObjCInterfaceDecl *ID) {
5087 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5088
5089 if (!Entry) {
5090 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5091 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5092 Entry =
5093 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5094 llvm::GlobalValue::InternalLinkage,
5095 ClassGV,
5096 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5097 &CGM.getModule());
5098 Entry->setAlignment(
5099 CGM.getTargetData().getPrefTypeAlignment(
5100 ObjCTypes.ClassnfABIPtrTy));
5101 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005102 UsedGlobals.push_back(Entry);
5103 }
5104
5105 return Builder.CreateLoad(Entry, false, "tmp");
5106}
5107
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005108/// EmitMetaClassRef - Return a Value * of the address of _class_t
5109/// meta-data
5110///
5111llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5112 const ObjCInterfaceDecl *ID) {
5113 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5114 if (Entry)
5115 return Builder.CreateLoad(Entry, false, "tmp");
5116
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005117 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005118 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005119 Entry =
5120 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5121 llvm::GlobalValue::InternalLinkage,
5122 MetaClassGV,
5123 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5124 &CGM.getModule());
5125 Entry->setAlignment(
5126 CGM.getTargetData().getPrefTypeAlignment(
5127 ObjCTypes.ClassnfABIPtrTy));
5128
Daniel Dunbar4993e292009-04-15 19:03:14 +00005129 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005130 UsedGlobals.push_back(Entry);
5131
5132 return Builder.CreateLoad(Entry, false, "tmp");
5133}
5134
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005135/// GetClass - Return a reference to the class for the given interface
5136/// decl.
5137llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5138 const ObjCInterfaceDecl *ID) {
5139 return EmitClassRef(Builder, ID);
5140}
5141
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005142/// Generates a message send where the super is the receiver. This is
5143/// a message send to self with special delivery semantics indicating
5144/// which class's method should be called.
5145CodeGen::RValue
5146CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5147 QualType ResultType,
5148 Selector Sel,
5149 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005150 bool isCategoryImpl,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005151 llvm::Value *Receiver,
5152 bool IsClassMessage,
5153 const CodeGen::CallArgList &CallArgs) {
5154 // ...
5155 // Create and init a super structure; this is a (receiver, class)
5156 // pair we will pass to objc_msgSendSuper.
5157 llvm::Value *ObjCSuper =
5158 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5159
5160 llvm::Value *ReceiverAsObject =
5161 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5162 CGF.Builder.CreateStore(ReceiverAsObject,
5163 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5164
5165 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005166 llvm::Value *Target;
5167 if (IsClassMessage) {
5168 if (isCategoryImpl) {
5169 // Message sent to "super' in a class method defined in
5170 // a category implementation.
Daniel Dunbar3c190812009-04-18 08:51:00 +00005171 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005172 Target = CGF.Builder.CreateStructGEP(Target, 0);
5173 Target = CGF.Builder.CreateLoad(Target);
5174 }
5175 else
5176 Target = EmitMetaClassRef(CGF.Builder, Class);
5177 }
5178 else
Daniel Dunbar3c190812009-04-18 08:51:00 +00005179 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005180
5181 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5182 // and ObjCTypes types.
5183 const llvm::Type *ClassTy =
5184 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5185 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5186 CGF.Builder.CreateStore(Target,
5187 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5188
5189 return EmitMessageSend(CGF, ResultType, Sel,
5190 ObjCSuper, ObjCTypes.SuperPtrCTy,
5191 true, CallArgs);
5192}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005193
5194llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5195 Selector Sel) {
5196 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5197
5198 if (!Entry) {
5199 llvm::Constant *Casted =
5200 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5201 ObjCTypes.SelectorPtrTy);
5202 Entry =
5203 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5204 llvm::GlobalValue::InternalLinkage,
5205 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5206 &CGM.getModule());
5207 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5208 UsedGlobals.push_back(Entry);
5209 }
5210
5211 return Builder.CreateLoad(Entry, false, "tmp");
5212}
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005213/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5214/// objc_assign_ivar (id src, id *dst)
5215///
5216void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5217 llvm::Value *src, llvm::Value *dst)
5218{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005219 const llvm::Type * SrcTy = src->getType();
5220 if (!isa<llvm::PointerType>(SrcTy)) {
5221 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5222 assert(Size <= 8 && "does not support size > 8");
5223 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5224 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005225 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5226 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005227 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5228 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5229 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5230 src, dst, "assignivar");
5231 return;
5232}
5233
5234/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5235/// objc_assign_strongCast (id src, id *dst)
5236///
5237void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5238 CodeGen::CodeGenFunction &CGF,
5239 llvm::Value *src, llvm::Value *dst)
5240{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005241 const llvm::Type * SrcTy = src->getType();
5242 if (!isa<llvm::PointerType>(SrcTy)) {
5243 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5244 assert(Size <= 8 && "does not support size > 8");
5245 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5246 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005247 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5248 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005249 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5250 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5251 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5252 src, dst, "weakassign");
5253 return;
5254}
5255
5256/// EmitObjCWeakRead - Code gen for loading value of a __weak
5257/// object: objc_read_weak (id *src)
5258///
5259llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5260 CodeGen::CodeGenFunction &CGF,
5261 llvm::Value *AddrWeakObj)
5262{
Eli Friedmanf8466232009-03-07 03:57:15 +00005263 const llvm::Type* DestTy =
5264 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005265 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5266 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5267 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00005268 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005269 return read_weak;
5270}
5271
5272/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5273/// objc_assign_weak (id src, id *dst)
5274///
5275void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5276 llvm::Value *src, llvm::Value *dst)
5277{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005278 const llvm::Type * SrcTy = src->getType();
5279 if (!isa<llvm::PointerType>(SrcTy)) {
5280 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5281 assert(Size <= 8 && "does not support size > 8");
5282 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5283 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005284 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5285 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005286 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5287 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00005288 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005289 src, dst, "weakassign");
5290 return;
5291}
5292
5293/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5294/// objc_assign_global (id src, id *dst)
5295///
5296void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5297 llvm::Value *src, llvm::Value *dst)
5298{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005299 const llvm::Type * SrcTy = src->getType();
5300 if (!isa<llvm::PointerType>(SrcTy)) {
5301 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5302 assert(Size <= 8 && "does not support size > 8");
5303 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5304 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005305 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5306 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005307 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5308 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5309 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5310 src, dst, "globalassign");
5311 return;
5312}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005313
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005314void
5315CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5316 const Stmt &S) {
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005317 bool isTry = isa<ObjCAtTryStmt>(S);
5318 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5319 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005320 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005321 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005322 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005323 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5324
5325 // For @synchronized, call objc_sync_enter(sync.expr). The
5326 // evaluation of the expression must occur before we enter the
5327 // @synchronized. We can safely avoid a temp here because jumps into
5328 // @synchronized are illegal & this will dominate uses.
5329 llvm::Value *SyncArg = 0;
5330 if (!isTry) {
5331 SyncArg =
5332 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5333 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00005334 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005335 }
5336
5337 // Push an EH context entry, used for handling rethrows and jumps
5338 // through finally.
5339 CGF.PushCleanupBlock(FinallyBlock);
5340
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005341 CGF.setInvokeDest(TryHandler);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005342
5343 CGF.EmitBlock(TryBlock);
5344 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5345 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5346 CGF.EmitBranchThroughCleanup(FinallyEnd);
5347
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005348 // Emit the exception handler.
5349
5350 CGF.EmitBlock(TryHandler);
5351
5352 llvm::Value *llvm_eh_exception =
5353 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5354 llvm::Value *llvm_eh_selector_i64 =
5355 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5356 llvm::Value *llvm_eh_typeid_for_i64 =
5357 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5358 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5359 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5360
5361 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5362 SelectorArgs.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005363 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005364
5365 // Construct the lists of (type, catch body) to handle.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005366 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005367 bool HasCatchAll = false;
5368 if (isTry) {
5369 if (const ObjCAtCatchStmt* CatchStmt =
5370 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5371 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005372 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005373 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005374
5375 // catch(...) always matches.
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005376 if (!CatchDecl) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005377 // Use i8* null here to signal this is a catch all, not a cleanup.
5378 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5379 SelectorArgs.push_back(Null);
5380 HasCatchAll = true;
5381 break;
5382 }
5383
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005384 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5385 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005386 llvm::Value *IDEHType =
5387 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5388 if (!IDEHType)
5389 IDEHType =
5390 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5391 llvm::GlobalValue::ExternalLinkage,
5392 0, "OBJC_EHTYPE_id", &CGM.getModule());
5393 SelectorArgs.push_back(IDEHType);
5394 HasCatchAll = true;
5395 break;
5396 }
5397
5398 // All other types should be Objective-C interface pointer types.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005399 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005400 assert(PT && "Invalid @catch type.");
5401 const ObjCInterfaceType *IT =
5402 PT->getPointeeType()->getAsObjCInterfaceType();
5403 assert(IT && "Invalid @catch type.");
Daniel Dunbarc2129532009-04-08 04:21:03 +00005404 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005405 SelectorArgs.push_back(EHType);
5406 }
5407 }
5408 }
5409
5410 // We use a cleanup unless there was already a catch all.
5411 if (!HasCatchAll) {
5412 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005413 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005414 }
5415
5416 llvm::Value *Selector =
5417 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5418 SelectorArgs.begin(), SelectorArgs.end(),
5419 "selector");
5420 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005421 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005422 const Stmt *CatchBody = Handlers[i].second;
5423
5424 llvm::BasicBlock *Next = 0;
5425
5426 // The last handler always matches.
5427 if (i + 1 != e) {
5428 assert(CatchParam && "Only last handler can be a catch all.");
5429
5430 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5431 Next = CGF.createBasicBlock("catch.next");
5432 llvm::Value *Id =
5433 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5434 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5435 ObjCTypes.Int8PtrTy));
5436 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5437 Match, Next);
5438
5439 CGF.EmitBlock(Match);
5440 }
5441
5442 if (CatchBody) {
5443 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5444 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5445
5446 // Cleanups must call objc_end_catch.
5447 //
5448 // FIXME: It seems incorrect for objc_begin_catch to be inside
5449 // this context, but this matches gcc.
5450 CGF.PushCleanupBlock(MatchEnd);
5451 CGF.setInvokeDest(MatchHandler);
5452
5453 llvm::Value *ExcObject =
5454 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5455
5456 // Bind the catch parameter if it exists.
5457 if (CatchParam) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005458 ExcObject =
5459 CGF.Builder.CreateBitCast(ExcObject,
5460 CGF.ConvertType(CatchParam->getType()));
5461 // CatchParam is a ParmVarDecl because of the grammar
5462 // construction used to handle this, but for codegen purposes
5463 // we treat this as a local decl.
5464 CGF.EmitLocalBlockVarDecl(*CatchParam);
5465 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005466 }
5467
5468 CGF.ObjCEHValueStack.push_back(ExcObject);
5469 CGF.EmitStmt(CatchBody);
5470 CGF.ObjCEHValueStack.pop_back();
5471
5472 CGF.EmitBranchThroughCleanup(FinallyEnd);
5473
5474 CGF.EmitBlock(MatchHandler);
5475
5476 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5477 // We are required to emit this call to satisfy LLVM, even
5478 // though we don't use the result.
5479 llvm::SmallVector<llvm::Value*, 8> Args;
5480 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005481 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005482 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5483 0));
5484 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5485 CGF.Builder.CreateStore(Exc, RethrowPtr);
5486 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5487
5488 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5489
5490 CGF.EmitBlock(MatchEnd);
5491
5492 // Unfortunately, we also have to generate another EH frame here
5493 // in case this throws.
5494 llvm::BasicBlock *MatchEndHandler =
5495 CGF.createBasicBlock("match.end.handler");
5496 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5497 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5498 Cont, MatchEndHandler,
5499 Args.begin(), Args.begin());
5500
5501 CGF.EmitBlock(Cont);
5502 if (Info.SwitchBlock)
5503 CGF.EmitBlock(Info.SwitchBlock);
5504 if (Info.EndBlock)
5505 CGF.EmitBlock(Info.EndBlock);
5506
5507 CGF.EmitBlock(MatchEndHandler);
5508 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5509 // We are required to emit this call to satisfy LLVM, even
5510 // though we don't use the result.
5511 Args.clear();
5512 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005513 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005514 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5515 0));
5516 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5517 CGF.Builder.CreateStore(Exc, RethrowPtr);
5518 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5519
5520 if (Next)
5521 CGF.EmitBlock(Next);
5522 } else {
5523 assert(!Next && "catchup should be last handler.");
5524
5525 CGF.Builder.CreateStore(Exc, RethrowPtr);
5526 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5527 }
5528 }
5529
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005530 // Pop the cleanup entry, the @finally is outside this cleanup
5531 // scope.
5532 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5533 CGF.setInvokeDest(PrevLandingPad);
5534
5535 CGF.EmitBlock(FinallyBlock);
5536
5537 if (isTry) {
5538 if (const ObjCAtFinallyStmt* FinallyStmt =
5539 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5540 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5541 } else {
5542 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5543 // @synchronized.
5544 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005545 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005546
5547 if (Info.SwitchBlock)
5548 CGF.EmitBlock(Info.SwitchBlock);
5549 if (Info.EndBlock)
5550 CGF.EmitBlock(Info.EndBlock);
5551
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005552 // Branch around the rethrow code.
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005553 CGF.EmitBranch(FinallyEnd);
5554
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005555 CGF.EmitBlock(FinallyRethrow);
5556 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5557 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005558 CGF.Builder.CreateUnreachable();
5559
5560 CGF.EmitBlock(FinallyEnd);
5561}
5562
Anders Carlsson1cf75362009-02-16 22:59:18 +00005563/// EmitThrowStmt - Generate code for a throw statement.
5564void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5565 const ObjCAtThrowStmt &S) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005566 llvm::Value *Exception;
Anders Carlsson1cf75362009-02-16 22:59:18 +00005567 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005568 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlsson1cf75362009-02-16 22:59:18 +00005569 } else {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005570 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5571 "Unexpected rethrow outside @catch block.");
5572 Exception = CGF.ObjCEHValueStack.back();
Anders Carlsson1cf75362009-02-16 22:59:18 +00005573 }
5574
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005575 llvm::Value *ExceptionAsObject =
5576 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5577 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5578 if (InvokeDest) {
5579 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5580 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5581 Cont, InvokeDest,
5582 &ExceptionAsObject, &ExceptionAsObject + 1);
5583 CGF.EmitBlock(Cont);
5584 } else
5585 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5586 CGF.Builder.CreateUnreachable();
5587
Anders Carlsson1cf75362009-02-16 22:59:18 +00005588 // Clear the insertion point to indicate we are in unreachable code.
5589 CGF.Builder.ClearInsertionPoint();
5590}
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005591
5592llvm::Value *
Daniel Dunbarc2129532009-04-08 04:21:03 +00005593CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5594 bool ForDefinition) {
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005595 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005596
Daniel Dunbarc2129532009-04-08 04:21:03 +00005597 // If we don't need a definition, return the entry if found or check
5598 // if we use an external reference.
5599 if (!ForDefinition) {
5600 if (Entry)
5601 return Entry;
Daniel Dunbarafac9be2009-04-07 06:43:45 +00005602
Daniel Dunbarc2129532009-04-08 04:21:03 +00005603 // If this type (or a super class) has the __objc_exception__
5604 // attribute, emit an external reference.
5605 if (hasObjCExceptionAttribute(ID))
5606 return Entry =
5607 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5608 llvm::GlobalValue::ExternalLinkage,
5609 0,
5610 (std::string("OBJC_EHTYPE_$_") +
5611 ID->getIdentifier()->getName()),
5612 &CGM.getModule());
5613 }
5614
5615 // Otherwise we need to either make a new entry or fill in the
5616 // initializer.
5617 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005618 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005619 std::string VTableName = "objc_ehtype_vtable";
5620 llvm::GlobalVariable *VTableGV =
5621 CGM.getModule().getGlobalVariable(VTableName);
5622 if (!VTableGV)
5623 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5624 llvm::GlobalValue::ExternalLinkage,
5625 0, VTableName, &CGM.getModule());
5626
5627 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5628
5629 std::vector<llvm::Constant*> Values(3);
5630 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5631 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005632 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005633 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5634
Daniel Dunbarc2129532009-04-08 04:21:03 +00005635 if (Entry) {
5636 Entry->setInitializer(Init);
5637 } else {
5638 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5639 llvm::GlobalValue::WeakAnyLinkage,
5640 Init,
5641 (std::string("OBJC_EHTYPE_$_") +
5642 ID->getIdentifier()->getName()),
5643 &CGM.getModule());
5644 }
5645
Daniel Dunbar8394fda2009-04-14 06:00:08 +00005646 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005647 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarc2129532009-04-08 04:21:03 +00005648 Entry->setAlignment(8);
5649
5650 if (ForDefinition) {
5651 Entry->setSection("__DATA,__objc_const");
5652 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5653 } else {
5654 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5655 }
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005656
5657 return Entry;
5658}
Anders Carlsson1cf75362009-02-16 22:59:18 +00005659
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00005660/* *** */
5661
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00005662CodeGen::CGObjCRuntime *
5663CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00005664 return new CGObjCMac(CGM);
5665}
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005666
5667CodeGen::CGObjCRuntime *
Fariborz Jahaniand0374812009-01-22 23:02:58 +00005668CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00005669 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005670}