blob: 238f7c5eadd87e9759d365add76c2c43e99684c2 [file] [log] [blame]
Daniel Dunbarc17a4d32008-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 Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-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 Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-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 Jahaniand55b6fc2009-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 Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-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 Jahaniandb286862009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000115
Daniel Dunbar1c566672009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-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 Dunbar1c566672009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000127
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000131
Fariborz Jahanianee0af742009-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 Lattner74391b42009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000148
Daniel Dunbar6efc0c52008-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 Dunbar6efc0c52008-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 Dunbar86e253a2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-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 Dunbar27f9d772008-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 Dunbar27f9d772008-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 Carlsson124526b2008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson124526b2008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000210
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214
215
Chris Lattner74391b42009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattner74391b42009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattner74391b42009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000227};
228
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000232public:
Chris Lattner74391b42009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahaniand55b6fc2009-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 Dunbar948e2582009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahaniand55b6fc2009-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 Jahanianaa23b572009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahaniand55b6fc2009-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 Jahanian2e4672b2009-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 Jahanian83a8a752009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000295
Fariborz Jahanianef163782009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian2e4672b2009-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 Dunbar8ecbaf22009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattnerb02e53b2009-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 Dunbar8ecbaf22009-02-24 07:47:38 +0000319
Chris Lattner74391b42009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000324
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000333 public:
Fariborz Jahaniana5a10c32009-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 Jahanian9397e1d2009-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 Jahanianee0af742009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000350
Fariborz Jahanian9397e1d2009-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 Jahaniana5a10c32009-03-10 16:22:08 +0000355
Daniel Dunbar242d4dc2008-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 Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000371
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbarc45ef602008-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 Jahanianee0af742009-01-21 22:04:16 +0000379
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000385
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000388
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar0c0e7a62008-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 Jahanianee0af742009-01-21 22:04:16 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000400
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000403
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000407
Fariborz Jahanian56210f72009-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);
Devang Patel7794bb82009-03-04 18:21:39 +0000425 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-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 Jahanian058a1b72009-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 Jahanian21e6f172009-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 Jahaniand61a50a2009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000456
Fariborz Jahaniand80d81b2009-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 Jahanian46b86c62009-01-28 19:12:34 +0000462 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
463 RecordDecl::field_iterator &FIV,
464 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000465 /// EmitPropertyList - Emit the given property list. The return
466 /// value has type PropertyListPtrTy.
467 llvm::Constant *EmitPropertyList(const std::string &Name,
468 const Decl *Container,
469 const ObjCContainerDecl *OCD,
470 const ObjCCommonTypesHelper &ObjCTypes);
471
Fariborz Jahanianda320092009-01-29 19:24:30 +0000472 /// GetProtocolRef - Return a reference to the internal protocol
473 /// description, creating an empty one if it has not been
474 /// defined. The return value has type ProtocolPtrTy.
475 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000476
477 /// GetIvarBaseOffset - returns ivars byte offset.
478 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000479 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000480
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
483 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000484 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000485
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000486 /// CreateMetadataVar - Create a global variable with internal
487 /// linkage for use by the Objective-C runtime.
488 ///
489 /// This is a convenience wrapper which not only creates the
490 /// variable, but also sets the section and alignment and adds the
491 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000492 ///
493 /// \param Name - The variable name.
494 /// \param Init - The variable initializer; this is also used to
495 /// define the type of the variable.
496 /// \param Section - The section the variable should go into, or 0.
497 /// \param Align - The alignment for the variable, or 0.
498 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000499 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000500 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
501 llvm::Constant *Init,
502 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000503 unsigned Align,
504 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000505
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000506public:
507 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
508 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000509
Steve Naroff33fdb732009-03-31 16:53:37 +0000510 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000511
512 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
513 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000514
515 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
516
517 /// GetOrEmitProtocol - Get the protocol object for the given
518 /// declaration, emitting it if necessary. The return value has type
519 /// ProtocolPtrTy.
520 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
521
522 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
523 /// object for the given declaration, emitting it if needed. These
524 /// forward references will be filled in with empty bodies if no
525 /// definition is seen. The return value has type ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000527};
528
529class CGObjCMac : public CGObjCCommonMac {
530private:
531 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000532 /// EmitImageInfo - Emit the image info marker used to encode some module
533 /// level information.
534 void EmitImageInfo();
535
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000536 /// EmitModuleInfo - Another marker encoding module level
537 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000538 void EmitModuleInfo();
539
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000540 /// EmitModuleSymols - Emit module symbols, the list of defined
541 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000542 llvm::Constant *EmitModuleSymbols();
543
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000544 /// FinishModule - Write out global data structures at the end of
545 /// processing a translation unit.
546 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000547
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000548 /// EmitClassExtension - Generate the class extension structure used
549 /// to store the weak ivar layout and properties. The return value
550 /// has type ClassExtensionPtrTy.
551 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
552
553 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
554 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000555 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000556 const ObjCInterfaceDecl *ID);
557
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000558 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000559 QualType ResultType,
560 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000561 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000562 QualType Arg0Ty,
563 bool IsSuper,
564 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000565
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000566 /// EmitIvarList - Emit the ivar list for the given
567 /// implementation. If ForClass is true the list of class ivars
568 /// (i.e. metaclass ivars) is emitted, otherwise the list of
569 /// interface ivars will be emitted. The return value has type
570 /// IvarListPtrTy.
571 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000572 bool ForClass);
573
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000574 /// EmitMetaClass - Emit a forward reference to the class structure
575 /// for the metaclass of the given interface. The return value has
576 /// type ClassPtrTy.
577 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
578
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000579 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000581 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
582 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000583 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000584 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000585
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000586 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000587
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000588 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000589
590 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000591 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000592 llvm::Constant *EmitMethodList(const std::string &Name,
593 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000594 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000595
596 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000597 /// method declarations.
598 /// - TypeName: The name for the type containing the methods.
599 /// - IsProtocol: True iff these methods are for a protocol.
600 /// - ClassMethds: True iff these are class methods.
601 /// - Required: When true, only "required" methods are
602 /// listed. Similarly, when false only "optional" methods are
603 /// listed. For classes this should always be true.
604 /// - begin, end: The method list to output.
605 ///
606 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000607 llvm::Constant *EmitMethodDescList(const std::string &Name,
608 const char *Section,
609 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000610
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000611 /// GetOrEmitProtocol - Get the protocol object for the given
612 /// declaration, emitting it if necessary. The return value has type
613 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000614 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000615
616 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
617 /// object for the given declaration, emitting it if needed. These
618 /// forward references will be filled in with empty bodies if no
619 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000621
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000622 /// EmitProtocolExtension - Generate the protocol extension
623 /// structure used to store optional instance and class methods, and
624 /// protocol properties. The return value has type
625 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000626 llvm::Constant *
627 EmitProtocolExtension(const ObjCProtocolDecl *PD,
628 const ConstantVector &OptInstanceMethods,
629 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000630
631 /// EmitProtocolList - Generate the list of referenced
632 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +0000633 llvm::Constant *EmitProtocolList(const std::string &Name,
634 ObjCProtocolDecl::protocol_iterator begin,
635 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000636
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000637 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
638 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000639 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000640
Fariborz Jahanianda320092009-01-29 19:24:30 +0000641 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000642 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000643
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000644 virtual llvm::Function *ModuleInitFunction();
645
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000646 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000647 QualType ResultType,
648 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000649 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000650 bool IsClassMessage,
651 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000652
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000653 virtual CodeGen::RValue
654 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000655 QualType ResultType,
656 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000657 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000658 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000659 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000660 bool IsClassMessage,
661 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000662
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000663 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000664 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000665
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000666 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000667
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000668 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000669
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000670 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000673 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000674
Chris Lattner74391b42009-03-22 21:03:39 +0000675 virtual llvm::Constant *GetPropertyGetFunction();
676 virtual llvm::Constant *GetPropertySetFunction();
677 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000678
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000679 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
680 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000681 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
682 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000683 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000684 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000685 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
686 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000687 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
688 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000689 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
690 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000691 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000693
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000694 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
695 QualType ObjectTy,
696 llvm::Value *BaseValue,
697 const ObjCIvarDecl *Ivar,
698 const FieldDecl *Field,
699 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000700 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
701 ObjCInterfaceDecl *Interface,
702 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000703};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000704
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000705class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000706private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000707 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000708 llvm::GlobalVariable* ObjCEmptyCacheVar;
709 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000710
Daniel Dunbar11394522009-04-18 08:51:00 +0000711 /// SuperClassReferences - uniqued super class references.
712 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
713
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000714 /// MetaClassReferences - uniqued meta class references.
715 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000716
717 /// EHTypeReferences - uniqued class ehtype references.
718 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000719
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000720 /// FinishNonFragileABIModule - Write out global data structures at the end of
721 /// processing a translation unit.
722 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000723
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000724 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
725 unsigned InstanceStart,
726 unsigned InstanceSize,
727 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000728 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
729 llvm::Constant *IsAGV,
730 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000731 llvm::Constant *ClassRoGV,
732 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000733
734 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
735
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000736 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
737
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000738 /// EmitMethodList - Emit the method list for the given
739 /// implementation. The return value has type MethodListnfABITy.
740 llvm::Constant *EmitMethodList(const std::string &Name,
741 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000742 const ConstantVector &Methods);
743 /// EmitIvarList - Emit the ivar list for the given
744 /// implementation. If ForClass is true the list of class ivars
745 /// (i.e. metaclass ivars) is emitted, otherwise the list of
746 /// interface ivars will be emitted. The return value has type
747 /// IvarListnfABIPtrTy.
748 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000749
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000750 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000751 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000752 unsigned long int offset);
753
Fariborz Jahanianda320092009-01-29 19:24:30 +0000754 /// GetOrEmitProtocol - Get the protocol object for the given
755 /// declaration, emitting it if necessary. The return value has type
756 /// ProtocolPtrTy.
757 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
758
759 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
760 /// object for the given declaration, emitting it if needed. These
761 /// forward references will be filled in with empty bodies if no
762 /// definition is seen. The return value has type ProtocolPtrTy.
763 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
764
765 /// EmitProtocolList - Generate the list of referenced
766 /// protocols. The return value has type ProtocolListPtrTy.
767 llvm::Constant *EmitProtocolList(const std::string &Name,
768 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000769 ObjCProtocolDecl::protocol_iterator end);
770
771 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
772 QualType ResultType,
773 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000774 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000775 QualType Arg0Ty,
776 bool IsSuper,
777 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000778
779 /// GetClassGlobal - Return the global variable for the Objective-C
780 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000781 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
782
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000783 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000784 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000785 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000786 const ObjCInterfaceDecl *ID);
787
788 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
789 /// for the given super class reference.
790 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
791 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000792
793 /// EmitMetaClassRef - Return a Value * of the address of _class_t
794 /// meta-data
795 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
796 const ObjCInterfaceDecl *ID);
797
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000798 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
799 /// the given ivar.
800 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000801 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000802 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000803 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000804
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000805 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
806 /// for the given selector.
807 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000808
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000809 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000810 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000811 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
812 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000813
814 const char *getMetaclassSymbolPrefix() const {
815 return "OBJC_METACLASS_$_";
816 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000817
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000818 const char *getClassSymbolPrefix() const {
819 return "OBJC_CLASS_$_";
820 }
821
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000822public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000823 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000824 // FIXME. All stubs for now!
825 virtual llvm::Function *ModuleInitFunction();
826
827 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
828 QualType ResultType,
829 Selector Sel,
830 llvm::Value *Receiver,
831 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000832 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000833
834 virtual CodeGen::RValue
835 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
836 QualType ResultType,
837 Selector Sel,
838 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000839 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000840 llvm::Value *Receiver,
841 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000842 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000843
844 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000845 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000846
847 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000848 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000849
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000850 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000851
852 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000853 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000854 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000855
Chris Lattner74391b42009-03-22 21:03:39 +0000856 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000857 return ObjCTypes.GetPropertyFn;
858 }
Chris Lattner74391b42009-03-22 21:03:39 +0000859 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000860 return ObjCTypes.SetPropertyFn;
861 }
Chris Lattner74391b42009-03-22 21:03:39 +0000862 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000863 return ObjCTypes.EnumerationMutationFn;
864 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000865
866 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000867 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000868 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000869 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000870 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000871 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000872 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000873 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000874 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000875 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000876 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000877 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000878 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000879 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000880 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
881 QualType ObjectTy,
882 llvm::Value *BaseValue,
883 const ObjCIvarDecl *Ivar,
884 const FieldDecl *Field,
885 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000886 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
887 ObjCInterfaceDecl *Interface,
888 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000889};
890
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000891} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000892
893/* *** Helper Functions *** */
894
895/// getConstantGEP() - Help routine to construct simple GEPs.
896static llvm::Constant *getConstantGEP(llvm::Constant *C,
897 unsigned idx0,
898 unsigned idx1) {
899 llvm::Value *Idxs[] = {
900 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
901 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
902 };
903 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
904}
905
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000906/// hasObjCExceptionAttribute - Return true if this class or any super
907/// class has the __objc_exception__ attribute.
908static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000909 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000910 return true;
911 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
912 return hasObjCExceptionAttribute(Super);
913 return false;
914}
915
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000916/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000917
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000918CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
919 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000920{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000921 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000922 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000923}
924
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000925/// GetClass - Return a reference to the class for the given interface
926/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000927llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000928 const ObjCInterfaceDecl *ID) {
929 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000930}
931
932/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000933llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000934 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000935}
936
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000937/// Generate a constant CFString object.
938/*
939 struct __builtin_CFString {
940 const int *isa; // point to __CFConstantStringClassReference
941 int flags;
942 const char *str;
943 long length;
944 };
945*/
946
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000947llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000948 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000949 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000950}
951
952/// Generates a message send where the super is the receiver. This is
953/// a message send to self with special delivery semantics indicating
954/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000955CodeGen::RValue
956CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000957 QualType ResultType,
958 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000959 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000960 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000961 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000962 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000963 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000964 // Create and init a super structure; this is a (receiver, class)
965 // pair we will pass to objc_msgSendSuper.
966 llvm::Value *ObjCSuper =
967 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
968 llvm::Value *ReceiverAsObject =
969 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
970 CGF.Builder.CreateStore(ReceiverAsObject,
971 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000972
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000973 // If this is a class message the metaclass is passed as the target.
974 llvm::Value *Target;
975 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000976 if (isCategoryImpl) {
977 // Message sent to 'super' in a class method defined in a category
978 // implementation requires an odd treatment.
979 // If we are in a class method, we must retrieve the
980 // _metaclass_ for the current class, pointed at by
981 // the class's "isa" pointer. The following assumes that
982 // isa" is the first ivar in a class (which it must be).
983 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
984 Target = CGF.Builder.CreateStructGEP(Target, 0);
985 Target = CGF.Builder.CreateLoad(Target);
986 }
987 else {
988 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
989 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
990 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
991 Target = Super;
992 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000993 } else {
994 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
995 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000996 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
997 // and ObjCTypes types.
998 const llvm::Type *ClassTy =
999 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001000 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001001 CGF.Builder.CreateStore(Target,
1002 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1003
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001004 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001005 ObjCSuper, ObjCTypes.SuperPtrCTy,
1006 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001007}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001008
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001009/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001010CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001011 QualType ResultType,
1012 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001013 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001014 bool IsClassMessage,
1015 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001016 llvm::Value *Arg0 =
1017 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001018 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001019 Arg0, CGF.getContext().getObjCIdType(),
1020 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001021}
1022
1023CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001024 QualType ResultType,
1025 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001026 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001027 QualType Arg0Ty,
1028 bool IsSuper,
1029 const CallArgList &CallArgs) {
1030 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001031 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1032 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1033 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001034 CGF.getContext().getObjCSelType()));
1035 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001036
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001037 CodeGenTypes &Types = CGM.getTypes();
1038 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1039 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001040
1041 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001042 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001043 Fn = ObjCTypes.getSendStretFn(IsSuper);
1044 } else if (ResultType->isFloatingType()) {
1045 // FIXME: Sadly, this is wrong. This actually depends on the
1046 // architecture. This happens to be right for x86-32 though.
1047 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1048 } else {
1049 Fn = ObjCTypes.getSendFn(IsSuper);
1050 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001051 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001052 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001053}
1054
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001055llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001056 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001057 // FIXME: I don't understand why gcc generates this, or where it is
1058 // resolved. Investigate. Its also wasteful to look this up over and
1059 // over.
1060 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1061
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001062 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1063 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001064}
1065
Fariborz Jahanianda320092009-01-29 19:24:30 +00001066void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001067 // FIXME: We shouldn't need this, the protocol decl should contain
1068 // enough information to tell us whether this was a declaration or a
1069 // definition.
1070 DefinedProtocols.insert(PD->getIdentifier());
1071
1072 // If we have generated a forward reference to this protocol, emit
1073 // it now. Otherwise do nothing, the protocol objects are lazily
1074 // emitted.
1075 if (Protocols.count(PD->getIdentifier()))
1076 GetOrEmitProtocol(PD);
1077}
1078
Fariborz Jahanianda320092009-01-29 19:24:30 +00001079llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001080 if (DefinedProtocols.count(PD->getIdentifier()))
1081 return GetOrEmitProtocol(PD);
1082 return GetOrEmitProtocolRef(PD);
1083}
1084
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001085/*
1086 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1087 struct _objc_protocol {
1088 struct _objc_protocol_extension *isa;
1089 char *protocol_name;
1090 struct _objc_protocol_list *protocol_list;
1091 struct _objc__method_prototype_list *instance_methods;
1092 struct _objc__method_prototype_list *class_methods
1093 };
1094
1095 See EmitProtocolExtension().
1096*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001097llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1098 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1099
1100 // Early exit if a defining object has already been generated.
1101 if (Entry && Entry->hasInitializer())
1102 return Entry;
1103
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001104 // FIXME: I don't understand why gcc generates this, or where it is
1105 // resolved. Investigate. Its also wasteful to look this up over and
1106 // over.
1107 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1108
Chris Lattner8ec03f52008-11-24 03:54:41 +00001109 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001110
1111 // Construct method lists.
1112 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1113 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001114 for (ObjCProtocolDecl::instmeth_iterator
1115 i = PD->instmeth_begin(CGM.getContext()),
1116 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001117 ObjCMethodDecl *MD = *i;
1118 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1119 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1120 OptInstanceMethods.push_back(C);
1121 } else {
1122 InstanceMethods.push_back(C);
1123 }
1124 }
1125
Douglas Gregor6ab35242009-04-09 21:40:53 +00001126 for (ObjCProtocolDecl::classmeth_iterator
1127 i = PD->classmeth_begin(CGM.getContext()),
1128 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001129 ObjCMethodDecl *MD = *i;
1130 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1131 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1132 OptClassMethods.push_back(C);
1133 } else {
1134 ClassMethods.push_back(C);
1135 }
1136 }
1137
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001138 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001139 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001140 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001141 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001142 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001143 PD->protocol_begin(),
1144 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001145 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001146 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1147 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001148 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1149 InstanceMethods);
1150 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001151 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1152 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001153 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1154 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001155 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1156 Values);
1157
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001158 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001159 // Already created, fix the linkage and update the initializer.
1160 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001161 Entry->setInitializer(Init);
1162 } else {
1163 Entry =
1164 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1165 llvm::GlobalValue::InternalLinkage,
1166 Init,
1167 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1168 &CGM.getModule());
1169 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001170 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001171 UsedGlobals.push_back(Entry);
1172 // FIXME: Is this necessary? Why only for protocol?
1173 Entry->setAlignment(4);
1174 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001175
1176 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001177}
1178
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001179llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001180 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1181
1182 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001183 // We use the initializer as a marker of whether this is a forward
1184 // reference or not. At module finalization we add the empty
1185 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001186 Entry =
1187 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001188 llvm::GlobalValue::ExternalLinkage,
1189 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001190 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001191 &CGM.getModule());
1192 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001193 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001194 UsedGlobals.push_back(Entry);
1195 // FIXME: Is this necessary? Why only for protocol?
1196 Entry->setAlignment(4);
1197 }
1198
1199 return Entry;
1200}
1201
1202/*
1203 struct _objc_protocol_extension {
1204 uint32_t size;
1205 struct objc_method_description_list *optional_instance_methods;
1206 struct objc_method_description_list *optional_class_methods;
1207 struct objc_property_list *instance_properties;
1208 };
1209*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001210llvm::Constant *
1211CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1212 const ConstantVector &OptInstanceMethods,
1213 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001214 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001215 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001216 std::vector<llvm::Constant*> Values(4);
1217 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001218 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001219 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1220 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001221 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1222 OptInstanceMethods);
1223 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001224 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1225 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001226 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1227 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001228 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1229 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001230 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001231
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001232 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001233 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1234 Values[3]->isNullValue())
1235 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1236
1237 llvm::Constant *Init =
1238 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001239
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001240 // No special section, but goes in llvm.used
1241 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1242 Init,
1243 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001244}
1245
1246/*
1247 struct objc_protocol_list {
1248 struct objc_protocol_list *next;
1249 long count;
1250 Protocol *list[];
1251 };
1252*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001253llvm::Constant *
1254CGObjCMac::EmitProtocolList(const std::string &Name,
1255 ObjCProtocolDecl::protocol_iterator begin,
1256 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257 std::vector<llvm::Constant*> ProtocolRefs;
1258
Daniel Dunbardbc93372008-08-21 21:57:41 +00001259 for (; begin != end; ++begin)
1260 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261
1262 // Just return null for empty protocol lists
1263 if (ProtocolRefs.empty())
1264 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1265
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001266 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001267 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1268
1269 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001270 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001271 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1272 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1273 Values[2] =
1274 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1275 ProtocolRefs.size()),
1276 ProtocolRefs);
1277
1278 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1279 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001280 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001281 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001282 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1283}
1284
1285/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001286 struct _objc_property {
1287 const char * const name;
1288 const char * const attributes;
1289 };
1290
1291 struct _objc_property_list {
1292 uint32_t entsize; // sizeof (struct _objc_property)
1293 uint32_t prop_count;
1294 struct _objc_property[prop_count];
1295 };
1296*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001297llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1298 const Decl *Container,
1299 const ObjCContainerDecl *OCD,
1300 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001301 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001302 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1303 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001304 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001305 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001306 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001307 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1308 Prop));
1309 }
1310
1311 // Return null for empty list.
1312 if (Properties.empty())
1313 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1314
1315 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001316 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001317 std::vector<llvm::Constant*> Values(3);
1318 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1319 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1320 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1321 Properties.size());
1322 Values[2] = llvm::ConstantArray::get(AT, Properties);
1323 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1324
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001325 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001326 CreateMetadataVar(Name, Init,
1327 (ObjCABI == 2) ? "__DATA, __objc_const" :
1328 "__OBJC,__property,regular,no_dead_strip",
1329 (ObjCABI == 2) ? 8 : 4,
1330 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001331 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001332}
1333
1334/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001335 struct objc_method_description_list {
1336 int count;
1337 struct objc_method_description list[];
1338 };
1339*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001340llvm::Constant *
1341CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1342 std::vector<llvm::Constant*> Desc(2);
1343 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1344 ObjCTypes.SelectorPtrTy);
1345 Desc[1] = GetMethodVarType(MD);
1346 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1347 Desc);
1348}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001349
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001350llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1351 const char *Section,
1352 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001353 // Return null for empty list.
1354 if (Methods.empty())
1355 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1356
1357 std::vector<llvm::Constant*> Values(2);
1358 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1359 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1360 Methods.size());
1361 Values[1] = llvm::ConstantArray::get(AT, Methods);
1362 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1363
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001364 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001365 return llvm::ConstantExpr::getBitCast(GV,
1366 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001367}
1368
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001369/*
1370 struct _objc_category {
1371 char *category_name;
1372 char *class_name;
1373 struct _objc_method_list *instance_methods;
1374 struct _objc_method_list *class_methods;
1375 struct _objc_protocol_list *protocols;
1376 uint32_t size; // <rdar://4585769>
1377 struct _objc_property_list *instance_properties;
1378 };
1379 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001380void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001381 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001382
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001383 // FIXME: This is poor design, the OCD should have a pointer to the
1384 // category decl. Additionally, note that Category can be null for
1385 // the @implementation w/o an @interface case. Sema should just
1386 // create one for us as it does for @implementation so everyone else
1387 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001388 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001389 const ObjCCategoryDecl *Category =
1390 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001391 std::string ExtName(Interface->getNameAsString() + "_" +
1392 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001393
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001394 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1395 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1396 e = OCD->instmeth_end(); i != e; ++i) {
1397 // Instance methods should always be defined.
1398 InstanceMethods.push_back(GetMethodConstant(*i));
1399 }
1400 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1401 e = OCD->classmeth_end(); i != e; ++i) {
1402 // Class methods should always be defined.
1403 ClassMethods.push_back(GetMethodConstant(*i));
1404 }
1405
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001406 std::vector<llvm::Constant*> Values(7);
1407 Values[0] = GetClassName(OCD->getIdentifier());
1408 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001409 Values[2] =
1410 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1411 ExtName,
1412 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001413 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001414 Values[3] =
1415 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001416 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001417 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001418 if (Category) {
1419 Values[4] =
1420 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1421 Category->protocol_begin(),
1422 Category->protocol_end());
1423 } else {
1424 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1425 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001426 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001427
1428 // If there is no category @interface then there can be no properties.
1429 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001430 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001431 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001432 } else {
1433 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1434 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001435
1436 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1437 Values);
1438
1439 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001440 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1441 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001442 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001443 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001444}
1445
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001446// FIXME: Get from somewhere?
1447enum ClassFlags {
1448 eClassFlags_Factory = 0x00001,
1449 eClassFlags_Meta = 0x00002,
1450 // <rdr://5142207>
1451 eClassFlags_HasCXXStructors = 0x02000,
1452 eClassFlags_Hidden = 0x20000,
1453 eClassFlags_ABI2_Hidden = 0x00010,
1454 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1455};
1456
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001457/*
1458 struct _objc_class {
1459 Class isa;
1460 Class super_class;
1461 const char *name;
1462 long version;
1463 long info;
1464 long instance_size;
1465 struct _objc_ivar_list *ivars;
1466 struct _objc_method_list *methods;
1467 struct _objc_cache *cache;
1468 struct _objc_protocol_list *protocols;
1469 // Objective-C 1.0 extensions (<rdr://4585769>)
1470 const char *ivar_layout;
1471 struct _objc_class_ext *ext;
1472 };
1473
1474 See EmitClassExtension();
1475 */
1476void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001477 DefinedSymbols.insert(ID->getIdentifier());
1478
Chris Lattner8ec03f52008-11-24 03:54:41 +00001479 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001480 // FIXME: Gross
1481 ObjCInterfaceDecl *Interface =
1482 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001483 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001484 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001485 Interface->protocol_begin(),
1486 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001487 const llvm::Type *InterfaceTy;
1488 if (Interface->isForwardDecl())
1489 InterfaceTy = llvm::StructType::get(NULL, NULL);
1490 else
1491 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001492 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001493 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001494 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001495
1496 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001497 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001498 Flags |= eClassFlags_Hidden;
1499
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001500 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1501 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1502 e = ID->instmeth_end(); i != e; ++i) {
1503 // Instance methods should always be defined.
1504 InstanceMethods.push_back(GetMethodConstant(*i));
1505 }
1506 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1507 e = ID->classmeth_end(); i != e; ++i) {
1508 // Class methods should always be defined.
1509 ClassMethods.push_back(GetMethodConstant(*i));
1510 }
1511
1512 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1513 e = ID->propimpl_end(); i != e; ++i) {
1514 ObjCPropertyImplDecl *PID = *i;
1515
1516 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1517 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1518
1519 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1520 if (llvm::Constant *C = GetMethodConstant(MD))
1521 InstanceMethods.push_back(C);
1522 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1523 if (llvm::Constant *C = GetMethodConstant(MD))
1524 InstanceMethods.push_back(C);
1525 }
1526 }
1527
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001528 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001529 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001530 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001531 // Record a reference to the super class.
1532 LazySymbols.insert(Super->getIdentifier());
1533
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001534 Values[ 1] =
1535 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1536 ObjCTypes.ClassPtrTy);
1537 } else {
1538 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1539 }
1540 Values[ 2] = GetClassName(ID->getIdentifier());
1541 // Version is always 0.
1542 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1543 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1544 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001545 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001546 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001547 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001548 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001549 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001550 // cache is always NULL.
1551 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1552 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001553 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001554 // Values[10] = BuildIvarLayout(ID, true);
1555 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001556 Values[11] = EmitClassExtension(ID);
1557 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1558 Values);
1559
1560 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001561 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1562 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001563 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001564 DefinedClasses.push_back(GV);
1565}
1566
1567llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1568 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001569 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001570 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001571 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001572 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001573
Daniel Dunbar04d40782009-04-14 06:00:08 +00001574 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001575 Flags |= eClassFlags_Hidden;
1576
1577 std::vector<llvm::Constant*> Values(12);
1578 // The isa for the metaclass is the root of the hierarchy.
1579 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1580 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1581 Root = Super;
1582 Values[ 0] =
1583 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1584 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001585 // The super class for the metaclass is emitted as the name of the
1586 // super class. The runtime fixes this up to point to the
1587 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001588 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1589 Values[ 1] =
1590 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1591 ObjCTypes.ClassPtrTy);
1592 } else {
1593 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1594 }
1595 Values[ 2] = GetClassName(ID->getIdentifier());
1596 // Version is always 0.
1597 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1598 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1599 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001600 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001601 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001602 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001603 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001604 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001605 // cache is always NULL.
1606 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1607 Values[ 9] = Protocols;
1608 // ivar_layout for metaclass is always NULL.
1609 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1610 // The class extension is always unused for metaclasses.
1611 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1612 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1613 Values);
1614
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001615 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001616 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001617
1618 // Check for a forward reference.
1619 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1620 if (GV) {
1621 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1622 "Forward metaclass reference has incorrect type.");
1623 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1624 GV->setInitializer(Init);
1625 } else {
1626 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1627 llvm::GlobalValue::InternalLinkage,
1628 Init, Name,
1629 &CGM.getModule());
1630 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001631 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001632 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001633 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001634
1635 return GV;
1636}
1637
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001638llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001639 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001640
1641 // FIXME: Should we look these up somewhere other than the
1642 // module. Its a bit silly since we only generate these while
1643 // processing an implementation, so exactly one pointer would work
1644 // if know when we entered/exitted an implementation block.
1645
1646 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001647 // Previously, metaclass with internal linkage may have been defined.
1648 // pass 'true' as 2nd argument so it is returned.
1649 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001650 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1651 "Forward metaclass reference has incorrect type.");
1652 return GV;
1653 } else {
1654 // Generate as an external reference to keep a consistent
1655 // module. This will be patched up when we emit the metaclass.
1656 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1657 llvm::GlobalValue::ExternalLinkage,
1658 0,
1659 Name,
1660 &CGM.getModule());
1661 }
1662}
1663
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001664/*
1665 struct objc_class_ext {
1666 uint32_t size;
1667 const char *weak_ivar_layout;
1668 struct _objc_property_list *properties;
1669 };
1670*/
1671llvm::Constant *
1672CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1673 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001674 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001675
1676 std::vector<llvm::Constant*> Values(3);
1677 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001678 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001679 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001680 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001681 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001682 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001683
1684 // Return null if no extension bits are used.
1685 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1686 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1687
1688 llvm::Constant *Init =
1689 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001690 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001691 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1692 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001693}
1694
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001695/// countInheritedIvars - count number of ivars in class and its super class(s)
1696///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001697static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1698 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001699 int count = 0;
1700 if (!OI)
1701 return 0;
1702 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1703 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001704 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001705 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1706 E = OI->ivar_end(); I != E; ++I)
1707 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001708 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001709 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1710 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001711 if ((*I)->getPropertyIvarDecl())
1712 ++count;
1713 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001714 return count;
1715}
1716
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001717/// getInterfaceDeclForIvar - Get the interface declaration node where
1718/// this ivar is declared in.
1719/// FIXME. Ideally, this info should be in the ivar node. But currently
1720/// it is not and prevailing wisdom is that ASTs should not have more
1721/// info than is absolutely needed, even though this info reflects the
1722/// source language.
1723///
1724static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1725 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001726 const ObjCIvarDecl *IVD,
1727 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001728 if (!OI)
1729 return 0;
1730 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1731 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1732 E = OI->ivar_end(); I != E; ++I)
1733 if ((*I)->getIdentifier() == IVD->getIdentifier())
1734 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001735 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001736 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1737 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001738 ObjCPropertyDecl *PDecl = (*I);
1739 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1740 if (IV->getIdentifier() == IVD->getIdentifier())
1741 return OI;
1742 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001743 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001744}
1745
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001746/*
1747 struct objc_ivar {
1748 char *ivar_name;
1749 char *ivar_type;
1750 int ivar_offset;
1751 };
1752
1753 struct objc_ivar_list {
1754 int ivar_count;
1755 struct objc_ivar list[count];
1756 };
1757 */
1758llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001759 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001760 std::vector<llvm::Constant*> Ivars, Ivar(3);
1761
1762 // When emitting the root class GCC emits ivar entries for the
1763 // actual class structure. It is not clear if we need to follow this
1764 // behavior; for now lets try and get away with not doing it. If so,
1765 // the cleanest solution would be to make up an ObjCInterfaceDecl
1766 // for the class.
1767 if (ForClass)
1768 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001769
1770 ObjCInterfaceDecl *OID =
1771 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001772 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001773
1774 RecordDecl::field_iterator ifield, pfield;
1775 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001776 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
1777 ifield != e; ++ifield) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001778 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001779 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001780 if (Field->getIdentifier())
1781 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1782 else
1783 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001784 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001785 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001786 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001787 }
1788
1789 // Return null for empty list.
1790 if (Ivars.empty())
1791 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1792
1793 std::vector<llvm::Constant*> Values(2);
1794 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1795 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1796 Ivars.size());
1797 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1798 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1799
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001800 llvm::GlobalVariable *GV;
1801 if (ForClass)
1802 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001803 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1804 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001805 else
1806 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1807 + ID->getNameAsString(),
1808 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001809 4, true);
1810 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001811}
1812
1813/*
1814 struct objc_method {
1815 SEL method_name;
1816 char *method_types;
1817 void *method;
1818 };
1819
1820 struct objc_method_list {
1821 struct objc_method_list *obsolete;
1822 int count;
1823 struct objc_method methods_list[count];
1824 };
1825*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001826
1827/// GetMethodConstant - Return a struct objc_method constant for the
1828/// given method if it has been defined. The result is null if the
1829/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001830llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001831 // FIXME: Use DenseMap::lookup
1832 llvm::Function *Fn = MethodDefinitions[MD];
1833 if (!Fn)
1834 return 0;
1835
1836 std::vector<llvm::Constant*> Method(3);
1837 Method[0] =
1838 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1839 ObjCTypes.SelectorPtrTy);
1840 Method[1] = GetMethodVarType(MD);
1841 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1842 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1843}
1844
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001845llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1846 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001847 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001848 // Return null for empty list.
1849 if (Methods.empty())
1850 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1851
1852 std::vector<llvm::Constant*> Values(3);
1853 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1854 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1855 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1856 Methods.size());
1857 Values[2] = llvm::ConstantArray::get(AT, Methods);
1858 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1859
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001860 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001861 return llvm::ConstantExpr::getBitCast(GV,
1862 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001863}
1864
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001865llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001866 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001867 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001868 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001869
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001870 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001871 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001872 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001873 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001874 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001875 llvm::GlobalValue::InternalLinkage,
1876 Name,
1877 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001878 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001879
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001880 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001881}
1882
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001883uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001884 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001885 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001886 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1887
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001888 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001889 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1890 // FIXME: The "field no" for bitfields is something completely
1891 // different; it is the offset in multiples of the base type size!
1892 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1893 const llvm::Type *Ty =
1894 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1895 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1896 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001897}
1898
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001899/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001900uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1901 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001902 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001903 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001904 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1905 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001906}
1907
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001908llvm::GlobalVariable *
1909CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1910 llvm::Constant *Init,
1911 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001912 unsigned Align,
1913 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001914 const llvm::Type *Ty = Init->getType();
1915 llvm::GlobalVariable *GV =
1916 new llvm::GlobalVariable(Ty, false,
1917 llvm::GlobalValue::InternalLinkage,
1918 Init,
1919 Name,
1920 &CGM.getModule());
1921 if (Section)
1922 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001923 if (Align)
1924 GV->setAlignment(Align);
1925 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001926 UsedGlobals.push_back(GV);
1927 return GV;
1928}
1929
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001930llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001931 // Abuse this interface function as a place to finalize.
1932 FinishModule();
1933
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001934 return NULL;
1935}
1936
Chris Lattner74391b42009-03-22 21:03:39 +00001937llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001938 return ObjCTypes.GetPropertyFn;
1939}
1940
Chris Lattner74391b42009-03-22 21:03:39 +00001941llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001942 return ObjCTypes.SetPropertyFn;
1943}
1944
Chris Lattner74391b42009-03-22 21:03:39 +00001945llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001946 return ObjCTypes.EnumerationMutationFn;
1947}
1948
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001949/*
1950
1951Objective-C setjmp-longjmp (sjlj) Exception Handling
1952--
1953
1954The basic framework for a @try-catch-finally is as follows:
1955{
1956 objc_exception_data d;
1957 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001958 bool _call_try_exit = true;
1959
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001960 objc_exception_try_enter(&d);
1961 if (!setjmp(d.jmp_buf)) {
1962 ... try body ...
1963 } else {
1964 // exception path
1965 id _caught = objc_exception_extract(&d);
1966
1967 // enter new try scope for handlers
1968 if (!setjmp(d.jmp_buf)) {
1969 ... match exception and execute catch blocks ...
1970
1971 // fell off end, rethrow.
1972 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001973 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001974 } else {
1975 // exception in catch block
1976 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001977 _call_try_exit = false;
1978 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001979 }
1980 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001981 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001982
1983finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001984 if (_call_try_exit)
1985 objc_exception_try_exit(&d);
1986
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001987 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001988 ... dispatch to finally destination ...
1989
1990finally_rethrow:
1991 objc_exception_throw(_rethrow);
1992
1993finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001994}
1995
1996This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001997uses _rethrow to determine if objc_exception_try_exit should be called
1998and if the object should be rethrown. This breaks in the face of
1999throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002000
2001We specialize this framework for a few particular circumstances:
2002
2003 - If there are no catch blocks, then we avoid emitting the second
2004 exception handling context.
2005
2006 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2007 e)) we avoid emitting the code to rethrow an uncaught exception.
2008
2009 - FIXME: If there is no @finally block we can do a few more
2010 simplifications.
2011
2012Rethrows and Jumps-Through-Finally
2013--
2014
2015Support for implicit rethrows and jumping through the finally block is
2016handled by storing the current exception-handling context in
2017ObjCEHStack.
2018
Daniel Dunbar898d5082008-09-30 01:06:03 +00002019In order to implement proper @finally semantics, we support one basic
2020mechanism for jumping through the finally block to an arbitrary
2021destination. Constructs which generate exits from a @try or @catch
2022block use this mechanism to implement the proper semantics by chaining
2023jumps, as necessary.
2024
2025This mechanism works like the one used for indirect goto: we
2026arbitrarily assign an ID to each destination and store the ID for the
2027destination in a variable prior to entering the finally block. At the
2028end of the finally block we simply create a switch to the proper
2029destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002030
2031Code gen for @synchronized(expr) stmt;
2032Effectively generating code for:
2033objc_sync_enter(expr);
2034@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002035*/
2036
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002037void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2038 const Stmt &S) {
2039 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002040 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002041 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002042 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002043 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2044 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2045 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002046
2047 // For @synchronized, call objc_sync_enter(sync.expr). The
2048 // evaluation of the expression must occur before we enter the
2049 // @synchronized. We can safely avoid a temp here because jumps into
2050 // @synchronized are illegal & this will dominate uses.
2051 llvm::Value *SyncArg = 0;
2052 if (!isTry) {
2053 SyncArg =
2054 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2055 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002056 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002057 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002058
2059 // Push an EH context entry, used for handling rethrows and jumps
2060 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002061 CGF.PushCleanupBlock(FinallyBlock);
2062
Anders Carlsson273558f2009-02-07 21:37:21 +00002063 CGF.ObjCEHValueStack.push_back(0);
2064
Daniel Dunbar898d5082008-09-30 01:06:03 +00002065 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002066 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2067 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002068 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2069 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002070 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2071 "_call_try_exit");
2072 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2073
Anders Carlsson80f25672008-09-09 17:59:25 +00002074 // Enter a new try block and call setjmp.
2075 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2076 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2077 "jmpbufarray");
2078 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2079 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2080 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002081
Daniel Dunbar55e87422008-11-11 02:29:29 +00002082 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2083 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002084 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002085 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002086
2087 // Emit the @try block.
2088 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002089 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2090 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002091 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002092
2093 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002094 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002095
2096 // Retrieve the exception object. We may emit multiple blocks but
2097 // nothing can cross this so the value is already in SSA form.
2098 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2099 ExceptionData,
2100 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002101 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002102 if (!isTry)
2103 {
2104 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002105 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002106 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002107 }
2108 else if (const ObjCAtCatchStmt* CatchStmt =
2109 cast<ObjCAtTryStmt>(S).getCatchStmts())
2110 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002111 // Enter a new exception try block (in case a @catch block throws
2112 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002113 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002114
Anders Carlsson80f25672008-09-09 17:59:25 +00002115 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2116 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002117 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002118
Daniel Dunbar55e87422008-11-11 02:29:29 +00002119 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2120 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002121 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002122
2123 CGF.EmitBlock(CatchBlock);
2124
Daniel Dunbar55e40722008-09-27 07:03:52 +00002125 // Handle catch list. As a special case we check if everything is
2126 // matched and avoid generating code for falling off the end if
2127 // so.
2128 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002129 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002130 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002131
Steve Naroff7ba138a2009-03-03 19:52:17 +00002132 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002133 const PointerType *PT = 0;
2134
Anders Carlsson80f25672008-09-09 17:59:25 +00002135 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002136 if (!CatchParam) {
2137 AllMatched = true;
2138 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002139 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002140
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002141 // catch(id e) always matches.
2142 // FIXME: For the time being we also match id<X>; this should
2143 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002144 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002145 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002146 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002147 }
2148
Daniel Dunbar55e40722008-09-27 07:03:52 +00002149 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002150 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002151 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002152 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002153 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002154 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002155
Anders Carlssondde0a942008-09-11 09:15:33 +00002156 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002157 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002158 break;
2159 }
2160
Daniel Dunbar129271a2008-09-27 07:36:24 +00002161 assert(PT && "Unexpected non-pointer type in @catch");
2162 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002163 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002164 assert(ObjCType && "Catch parameter must have Objective-C type!");
2165
2166 // Check if the @catch block matches the exception object.
2167 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2168
Anders Carlsson80f25672008-09-09 17:59:25 +00002169 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2170 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002171
Daniel Dunbar55e87422008-11-11 02:29:29 +00002172 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002173
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002174 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002175 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002176
2177 // Emit the @catch block.
2178 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002179 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002180 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002181
2182 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002183 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002184 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002185 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002186
2187 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002188 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002189
2190 CGF.EmitBlock(NextCatchBlock);
2191 }
2192
Daniel Dunbar55e40722008-09-27 07:03:52 +00002193 if (!AllMatched) {
2194 // None of the handlers caught the exception, so store it to be
2195 // rethrown at the end of the @finally block.
2196 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002197 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002198 }
2199
2200 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002201 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002202 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2203 ExceptionData),
2204 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002205 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002206 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002207 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002208 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002209 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002210 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002211 }
2212
Daniel Dunbar898d5082008-09-30 01:06:03 +00002213 // Pop the exception-handling stack entry. It is important to do
2214 // this now, because the code in the @finally block is not in this
2215 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002216 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2217
Anders Carlsson273558f2009-02-07 21:37:21 +00002218 CGF.ObjCEHValueStack.pop_back();
2219
Anders Carlsson80f25672008-09-09 17:59:25 +00002220 // Emit the @finally block.
2221 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002222 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2223
2224 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2225
2226 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002227 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002228
2229 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002230 if (isTry) {
2231 if (const ObjCAtFinallyStmt* FinallyStmt =
2232 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2233 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002234 } else {
2235 // Emit objc_sync_exit(expr); as finally's sole statement for
2236 // @synchronized.
2237 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002238 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002239
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002240 // Emit the switch block
2241 if (Info.SwitchBlock)
2242 CGF.EmitBlock(Info.SwitchBlock);
2243 if (Info.EndBlock)
2244 CGF.EmitBlock(Info.EndBlock);
2245
Daniel Dunbar898d5082008-09-30 01:06:03 +00002246 CGF.EmitBlock(FinallyRethrow);
2247 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2248 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002249 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002250
2251 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002252}
2253
2254void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002255 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002256 llvm::Value *ExceptionAsObject;
2257
2258 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2259 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2260 ExceptionAsObject =
2261 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2262 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002263 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002264 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002265 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002266 }
2267
2268 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002269 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002270
2271 // Clear the insertion point to indicate we are in unreachable code.
2272 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002273}
2274
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002275/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002276/// object: objc_read_weak (id *src)
2277///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002278llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002279 llvm::Value *AddrWeakObj)
2280{
Eli Friedman8339b352009-03-07 03:57:15 +00002281 const llvm::Type* DestTy =
2282 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002283 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002284 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002285 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002286 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002287 return read_weak;
2288}
2289
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002290/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2291/// objc_assign_weak (id src, id *dst)
2292///
2293void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2294 llvm::Value *src, llvm::Value *dst)
2295{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002296 const llvm::Type * SrcTy = src->getType();
2297 if (!isa<llvm::PointerType>(SrcTy)) {
2298 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2299 assert(Size <= 8 && "does not support size > 8");
2300 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2301 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002302 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2303 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002304 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2305 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002306 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002307 src, dst, "weakassign");
2308 return;
2309}
2310
Fariborz Jahanian58626502008-11-19 00:59:10 +00002311/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2312/// objc_assign_global (id src, id *dst)
2313///
2314void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2315 llvm::Value *src, llvm::Value *dst)
2316{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002317 const llvm::Type * SrcTy = src->getType();
2318 if (!isa<llvm::PointerType>(SrcTy)) {
2319 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2320 assert(Size <= 8 && "does not support size > 8");
2321 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2322 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002323 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2324 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002325 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2326 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002327 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2328 src, dst, "globalassign");
2329 return;
2330}
2331
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002332/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2333/// objc_assign_ivar (id src, id *dst)
2334///
2335void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2336 llvm::Value *src, llvm::Value *dst)
2337{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002338 const llvm::Type * SrcTy = src->getType();
2339 if (!isa<llvm::PointerType>(SrcTy)) {
2340 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2341 assert(Size <= 8 && "does not support size > 8");
2342 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2343 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002344 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2345 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002346 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2347 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2348 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2349 src, dst, "assignivar");
2350 return;
2351}
2352
Fariborz Jahanian58626502008-11-19 00:59:10 +00002353/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2354/// objc_assign_strongCast (id src, id *dst)
2355///
2356void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2357 llvm::Value *src, llvm::Value *dst)
2358{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002359 const llvm::Type * SrcTy = src->getType();
2360 if (!isa<llvm::PointerType>(SrcTy)) {
2361 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2362 assert(Size <= 8 && "does not support size > 8");
2363 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2364 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002365 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2366 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002367 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2368 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002369 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2370 src, dst, "weakassign");
2371 return;
2372}
2373
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002374/// EmitObjCValueForIvar - Code Gen for ivar reference.
2375///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002376LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2377 QualType ObjectTy,
2378 llvm::Value *BaseValue,
2379 const ObjCIvarDecl *Ivar,
2380 const FieldDecl *Field,
2381 unsigned CVRQualifiers) {
2382 if (Ivar->isBitField())
2383 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2384 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002385 // TODO: Add a special case for isa (index 0)
2386 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2387 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002388 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002389 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2390 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002391 LValue::SetObjCIvar(LV, true);
2392 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002393}
2394
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002395llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2396 ObjCInterfaceDecl *Interface,
2397 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002398 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002399 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002400 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002401 return llvm::ConstantInt::get(
2402 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2403 Offset);
2404}
2405
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002406/* *** Private Interface *** */
2407
2408/// EmitImageInfo - Emit the image info marker used to encode some module
2409/// level information.
2410///
2411/// See: <rdr://4810609&4810587&4810587>
2412/// struct IMAGE_INFO {
2413/// unsigned version;
2414/// unsigned flags;
2415/// };
2416enum ImageInfoFlags {
2417 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2418 eImageInfo_GarbageCollected = (1 << 1),
2419 eImageInfo_GCOnly = (1 << 2)
2420};
2421
2422void CGObjCMac::EmitImageInfo() {
2423 unsigned version = 0; // Version is unused?
2424 unsigned flags = 0;
2425
2426 // FIXME: Fix and continue?
2427 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2428 flags |= eImageInfo_GarbageCollected;
2429 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2430 flags |= eImageInfo_GCOnly;
2431
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002432 // Emitted as int[2];
2433 llvm::Constant *values[2] = {
2434 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2435 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2436 };
2437 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002438
2439 const char *Section;
2440 if (ObjCABI == 1)
2441 Section = "__OBJC, __image_info,regular";
2442 else
2443 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002444 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002445 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2446 llvm::ConstantArray::get(AT, values, 2),
2447 Section,
2448 0,
2449 true);
2450 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002451}
2452
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002453
2454// struct objc_module {
2455// unsigned long version;
2456// unsigned long size;
2457// const char *name;
2458// Symtab symtab;
2459// };
2460
2461// FIXME: Get from somewhere
2462static const int ModuleVersion = 7;
2463
2464void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002465 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002466
2467 std::vector<llvm::Constant*> Values(4);
2468 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2469 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002470 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002471 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002472 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002473 CreateMetadataVar("\01L_OBJC_MODULES",
2474 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2475 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002476 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002477}
2478
2479llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002480 unsigned NumClasses = DefinedClasses.size();
2481 unsigned NumCategories = DefinedCategories.size();
2482
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002483 // Return null if no symbols were defined.
2484 if (!NumClasses && !NumCategories)
2485 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2486
2487 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002488 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2489 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2490 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2491 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2492
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002493 // The runtime expects exactly the list of defined classes followed
2494 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002495 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002496 for (unsigned i=0; i<NumClasses; i++)
2497 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2498 ObjCTypes.Int8PtrTy);
2499 for (unsigned i=0; i<NumCategories; i++)
2500 Symbols[NumClasses + i] =
2501 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2502 ObjCTypes.Int8PtrTy);
2503
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002504 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002505 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002506 NumClasses + NumCategories),
2507 Symbols);
2508
2509 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2510
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002511 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002512 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2513 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002514 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002515 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2516}
2517
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002518llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002519 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002520 LazySymbols.insert(ID->getIdentifier());
2521
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002522 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2523
2524 if (!Entry) {
2525 llvm::Constant *Casted =
2526 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2527 ObjCTypes.ClassPtrTy);
2528 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002529 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2530 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002531 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002532 }
2533
2534 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002535}
2536
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002537llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002538 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2539
2540 if (!Entry) {
2541 llvm::Constant *Casted =
2542 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2543 ObjCTypes.SelectorPtrTy);
2544 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002545 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2546 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002547 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002548 }
2549
2550 return Builder.CreateLoad(Entry, false, "tmp");
2551}
2552
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002553llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002554 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002555
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002556 if (!Entry)
2557 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2558 llvm::ConstantArray::get(Ident->getName()),
2559 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002560 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002561
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002562 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002563}
2564
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002565/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2566/// interface declaration.
2567const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2568 const ObjCInterfaceDecl *OID) const {
Chris Lattnerb7b58b12009-04-19 06:02:28 +00002569 const llvm::Type *InterfaceTy;
2570
2571 if (OID->isForwardDecl()) {
2572 InterfaceTy = llvm::StructType::get(NULL, NULL);
2573 } else {
2574 QualType T = CGM.getContext().getObjCInterfaceType(
2575 const_cast<ObjCInterfaceDecl*>(OID));
2576 InterfaceTy = CGM.getTypes().ConvertType(T);
2577 }
2578
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002579 const llvm::StructLayout *Layout =
2580 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2581 return Layout;
2582}
2583
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002584/// GetIvarLayoutName - Returns a unique constant for the given
2585/// ivar layout bitmap.
2586llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2587 const ObjCCommonTypesHelper &ObjCTypes) {
2588 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2589}
2590
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002591void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2592 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002593 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002594 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002595 unsigned int BytePos, bool ForStrongLayout,
2596 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002597 bool IsUnion = (RD && RD->isUnion());
2598 uint64_t MaxUnionIvarSize = 0;
2599 uint64_t MaxSkippedUnionIvarSize = 0;
2600 FieldDecl *MaxField = 0;
2601 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002602 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002603 if (RecFields.empty())
2604 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002605 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002606 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002607 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2608 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2609
2610 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2611
2612 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002613 FieldDecl *Field = RecFields[i];
2614 // Skip over unnamed or bitfields
2615 if (!Field->getIdentifier() || Field->isBitField())
2616 continue;
2617 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002618 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002619 if (FQT->isUnionType())
2620 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002621 else
2622 assert(FQT->isRecordType() &&
2623 "only union/record is supported for ivar layout bitmap");
2624
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002625 const RecordType *RT = FQT->getAsRecordType();
2626 const RecordDecl *RD = RT->getDecl();
2627 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002628 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2629 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002630 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002631 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002632 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002633 ForStrongLayout, Index, SkIndex,
2634 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002635 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002636 continue;
2637 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002638
2639 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002640 const ConstantArrayType *CArray =
2641 dyn_cast_or_null<ConstantArrayType>(Array);
2642 assert(CArray && "only array with know element size is supported");
2643 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002644 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2645 const ConstantArrayType *CArray =
2646 dyn_cast_or_null<ConstantArrayType>(Array);
2647 FQT = CArray->getElementType();
2648 }
2649
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002650 assert(!FQT->isUnionType() &&
2651 "layout for array of unions not supported");
2652 if (FQT->isRecordType()) {
2653 uint64_t ElCount = CArray->getSize().getZExtValue();
2654 int OldIndex = Index;
2655 int OldSkIndex = SkIndex;
2656
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002657 // FIXME - Use a common routine with the above!
2658 const RecordType *RT = FQT->getAsRecordType();
2659 const RecordDecl *RD = RT->getDecl();
2660 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002661 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2662 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002663
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002664 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002665 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002666 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002667 ForStrongLayout, Index, SkIndex,
2668 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002669 TmpRecFields.clear();
2670
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002671 // Replicate layout information for each array element. Note that
2672 // one element is already done.
2673 uint64_t ElIx = 1;
2674 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2675 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002676 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002677 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2678 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002679 GC_IVAR gcivar;
2680 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2681 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2682 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002683 }
2684
Chris Lattnerf1690852009-03-31 08:48:01 +00002685 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002686 GC_IVAR skivar;
2687 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2688 skivar.ivar_size = SkipIvars[i].ivar_size;
2689 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002690 }
2691 }
2692 continue;
2693 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002694 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002695 // At this point, we are done with Record/Union and array there of.
2696 // For other arrays we are down to its element type.
2697 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2698 do {
2699 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2700 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2701 break;
2702 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002703 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002704 GCAttr = QualType::Strong;
2705 break;
2706 }
2707 else if (const PointerType *PT = FQT->getAsPointerType()) {
2708 FQT = PT->getPointeeType();
2709 }
2710 else {
2711 break;
2712 }
2713 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002714
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002715 if ((ForStrongLayout && GCAttr == QualType::Strong)
2716 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2717 if (IsUnion)
2718 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002719 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2720 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002721 if (UnionIvarSize > MaxUnionIvarSize)
2722 {
2723 MaxUnionIvarSize = UnionIvarSize;
2724 MaxField = Field;
2725 }
2726 }
2727 else
2728 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002729 GC_IVAR gcivar;
2730 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2731 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2732 WordSizeInBits;
2733 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002734 }
2735 }
2736 else if ((ForStrongLayout &&
2737 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2738 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2739 if (IsUnion)
2740 {
2741 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2742 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2743 {
2744 MaxSkippedUnionIvarSize = UnionIvarSize;
2745 MaxSkippedField = Field;
2746 }
2747 }
2748 else
2749 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002750 GC_IVAR skivar;
2751 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2752 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2753 WordSizeInBits;
2754 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002755 }
2756 }
2757 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002758 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002759 GC_IVAR gcivar;
2760 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2761 gcivar.ivar_size = MaxUnionIvarSize;
2762 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002763 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002764
2765 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002766 GC_IVAR skivar;
2767 skivar.ivar_bytepos = BytePos +
2768 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2769 skivar.ivar_size = MaxSkippedUnionIvarSize;
2770 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002771 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002772}
2773
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002774static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002775IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002776{
2777 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2778 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2779
2780 if (sa < sb)
2781 return -1;
2782 if (sa > sb)
2783 return 1;
2784 return 0;
2785}
2786
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002787/// BuildIvarLayout - Builds ivar layout bitmap for the class
2788/// implementation for the __strong or __weak case.
2789/// The layout map displays which words in ivar list must be skipped
2790/// and which must be scanned by GC (see below). String is built of bytes.
2791/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2792/// of words to skip and right nibble is count of words to scan. So, each
2793/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2794/// represented by a 0x00 byte which also ends the string.
2795/// 1. when ForStrongLayout is true, following ivars are scanned:
2796/// - id, Class
2797/// - object *
2798/// - __strong anything
2799///
2800/// 2. When ForStrongLayout is false, following ivars are scanned:
2801/// - __weak anything
2802///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002803llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002804 const ObjCImplementationDecl *OMD,
2805 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002806 int Index = -1;
2807 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002808 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002809 int SkipScan;
2810 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002811 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2812 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2813 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002814
Chris Lattnerf1690852009-03-31 08:48:01 +00002815 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002816 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002817 CGM.getContext().CollectObjCIvars(OI, RecFields);
2818 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002819 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002820
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002821 SkipIvars.clear();
2822 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002823
2824 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002825 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2826 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002827 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002828 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002829
2830 // Sort on byte position in case we encounterred a union nested in
2831 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002832 if (hasUnion && !IvarsInfo.empty())
2833 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2834 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002835 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2836
2837 // Build the string of skip/scan nibbles
2838 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002839 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002840 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002841 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002842 if (IvarsInfo[0].ivar_bytepos == 0) {
2843 WordsToSkip = 0;
2844 WordsToScan = IvarsInfo[0].ivar_size;
2845 }
2846 else {
2847 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2848 WordsToScan = IvarsInfo[0].ivar_size;
2849 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002850 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002851 {
2852 unsigned int TailPrevGCObjC =
2853 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2854 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2855 {
2856 // consecutive 'scanned' object pointers.
2857 WordsToScan += IvarsInfo[i].ivar_size;
2858 }
2859 else
2860 {
2861 // Skip over 'gc'able object pointer which lay over each other.
2862 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2863 continue;
2864 // Must skip over 1 or more words. We save current skip/scan values
2865 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002866 SKIP_SCAN SkScan;
2867 SkScan.skip = WordsToSkip;
2868 SkScan.scan = WordsToScan;
2869 SkipScanIvars.push_back(SkScan); ++SkipScan;
2870
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002871 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002872 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2873 SkScan.scan = 0;
2874 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002875 WordsToSkip = 0;
2876 WordsToScan = IvarsInfo[i].ivar_size;
2877 }
2878 }
2879 if (WordsToScan > 0)
2880 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002881 SKIP_SCAN SkScan;
2882 SkScan.skip = WordsToSkip;
2883 SkScan.scan = WordsToScan;
2884 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002885 }
2886
2887 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002888 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002889 {
2890 int LastByteSkipped =
2891 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2892 int LastByteScanned =
2893 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2894 BytesSkipped = (LastByteSkipped > LastByteScanned);
2895 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2896 if (BytesSkipped)
2897 {
2898 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002899 SKIP_SCAN SkScan;
2900 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2901 SkScan.scan = 0;
2902 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002903 }
2904 }
2905 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2906 // as 0xMN.
2907 for (int i = 0; i <= SkipScan; i++)
2908 {
2909 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2910 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2911 // 0xM0 followed by 0x0N detected.
2912 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2913 for (int j = i+1; j < SkipScan; j++)
2914 SkipScanIvars[j] = SkipScanIvars[j+1];
2915 --SkipScan;
2916 }
2917 }
2918
2919 // Generate the string.
2920 std::string BitMap;
2921 for (int i = 0; i <= SkipScan; i++)
2922 {
2923 unsigned char byte;
2924 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2925 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2926 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2927 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2928
2929 if (skip_small > 0 || skip_big > 0)
2930 BytesSkipped = true;
2931 // first skip big.
2932 for (unsigned int ix = 0; ix < skip_big; ix++)
2933 BitMap += (unsigned char)(0xf0);
2934
2935 // next (skip small, scan)
2936 if (skip_small)
2937 {
2938 byte = skip_small << 4;
2939 if (scan_big > 0)
2940 {
2941 byte |= 0xf;
2942 --scan_big;
2943 }
2944 else if (scan_small)
2945 {
2946 byte |= scan_small;
2947 scan_small = 0;
2948 }
2949 BitMap += byte;
2950 }
2951 // next scan big
2952 for (unsigned int ix = 0; ix < scan_big; ix++)
2953 BitMap += (unsigned char)(0x0f);
2954 // last scan small
2955 if (scan_small)
2956 {
2957 byte = scan_small;
2958 BitMap += byte;
2959 }
2960 }
2961 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002962 unsigned char zero = 0;
2963 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002964 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2965 // final layout.
2966 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002967 return llvm::Constant::getNullValue(PtrTy);
2968 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2969 llvm::ConstantArray::get(BitMap.c_str()),
2970 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002971 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002972 // FIXME. Need a commomand-line option for this eventually.
2973 if (ForStrongLayout)
2974 printf("\nstrong ivar layout: ");
2975 else
2976 printf("\nweak ivar layout: ");
2977 const unsigned char *s = (unsigned char*)BitMap.c_str();
2978 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002979 if (!(s[i] & 0xf0))
2980 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2981 else
2982 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002983 printf("\n");
2984
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002985 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002986}
2987
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002988llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002989 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2990
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002991 // FIXME: Avoid std::string copying.
2992 if (!Entry)
2993 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2994 llvm::ConstantArray::get(Sel.getAsString()),
2995 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002996 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002997
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002998 return getConstantGEP(Entry, 0, 0);
2999}
3000
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003001// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003002llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003003 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3004}
3005
3006// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003007llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003008 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3009}
3010
Devang Patel7794bb82009-03-04 18:21:39 +00003011llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
3012 std::string TypeStr;
3013 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3014
3015 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003016
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003017 if (!Entry)
3018 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3019 llvm::ConstantArray::get(TypeStr),
3020 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003021 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003022
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003023 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003024}
3025
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003026llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003027 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003028 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3029 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003030
3031 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3032
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003033 if (!Entry)
3034 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3035 llvm::ConstantArray::get(TypeStr),
3036 "__TEXT,__cstring,cstring_literals",
3037 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003038
3039 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003040}
3041
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003042// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003043llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003044 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3045
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003046 if (!Entry)
3047 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3048 llvm::ConstantArray::get(Ident->getName()),
3049 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003050 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003051
3052 return getConstantGEP(Entry, 0, 0);
3053}
3054
3055// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003056// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003057llvm::Constant *
3058 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3059 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003060 std::string TypeStr;
3061 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003062 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3063}
3064
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003065void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3066 const ObjCContainerDecl *CD,
3067 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003068 NameOut = '\01';
3069 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003070 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003071 assert (CD && "Missing container decl in GetNameForMethod");
3072 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003073 if (const ObjCCategoryImplDecl *CID =
3074 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3075 NameOut += '(';
3076 NameOut += CID->getNameAsString();
3077 NameOut+= ')';
3078 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003079 NameOut += ' ';
3080 NameOut += D->getSelector().getAsString();
3081 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003082}
3083
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003084/// GetFirstIvarInRecord - This routine returns the record for the
3085/// implementation of the fiven class OID. It also returns field
3086/// corresponding to the first ivar in the class in FIV. It also
3087/// returns the one before the first ivar.
3088///
3089const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3090 const ObjCInterfaceDecl *OID,
3091 RecordDecl::field_iterator &FIV,
3092 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003093 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3094 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003095 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003096 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3097 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003098 while (countSuperClassIvars-- > 0) {
3099 pfield = ifield;
3100 ++ifield;
3101 }
3102 FIV = ifield;
3103 PIV = pfield;
3104 return RD;
3105}
3106
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003107void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003108 EmitModuleInfo();
3109
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003110 // Emit the dummy bodies for any protocols which were referenced but
3111 // never defined.
3112 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3113 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3114 if (i->second->hasInitializer())
3115 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003116
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003117 std::vector<llvm::Constant*> Values(5);
3118 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3119 Values[1] = GetClassName(i->first);
3120 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3121 Values[3] = Values[4] =
3122 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3123 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3124 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3125 Values));
3126 }
3127
3128 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003129 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003130 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003131 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003132 }
3133
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003134 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003135 llvm::GlobalValue *GV =
3136 new llvm::GlobalVariable(AT, false,
3137 llvm::GlobalValue::AppendingLinkage,
3138 llvm::ConstantArray::get(AT, Used),
3139 "llvm.used",
3140 &CGM.getModule());
3141
3142 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003143
3144 // Add assembler directives to add lazy undefined symbol references
3145 // for classes which are referenced but not defined. This is
3146 // important for correct linker interaction.
3147
3148 // FIXME: Uh, this isn't particularly portable.
3149 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003150
3151 if (!CGM.getModule().getModuleInlineAsm().empty())
3152 s << "\n";
3153
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003154 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3155 e = LazySymbols.end(); i != e; ++i) {
3156 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3157 }
3158 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3159 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003160 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003161 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3162 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003163
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003164 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003165}
3166
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003167CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003168 : CGObjCCommonMac(cgm),
3169 ObjCTypes(cgm)
3170{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003171 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003172 ObjCABI = 2;
3173}
3174
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003175/* *** */
3176
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003177ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3178: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003179{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003180 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3181 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003182
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003183 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003184 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003185 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003186 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003187 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3188
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003189 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003190 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003191 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003192
3193 // FIXME: It would be nice to unify this with the opaque type, so
3194 // that the IR comes out a bit cleaner.
3195 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3196 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003197
3198 // I'm not sure I like this. The implicit coordination is a bit
3199 // gross. We should solve this in a reasonable fashion because this
3200 // is a pretty common task (match some runtime data structure with
3201 // an LLVM data structure).
3202
3203 // FIXME: This is leaked.
3204 // FIXME: Merge with rewriter code?
3205
3206 // struct _objc_super {
3207 // id self;
3208 // Class cls;
3209 // }
3210 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3211 SourceLocation(),
3212 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003213 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3214 Ctx.getObjCIdType(), 0, false));
3215 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3216 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003217 RD->completeDefinition(Ctx);
3218
3219 SuperCTy = Ctx.getTagDeclType(RD);
3220 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3221
3222 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003223 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3224
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003225 // struct _prop_t {
3226 // char *name;
3227 // char *attributes;
3228 // }
3229 PropertyTy = llvm::StructType::get(Int8PtrTy,
3230 Int8PtrTy,
3231 NULL);
3232 CGM.getModule().addTypeName("struct._prop_t",
3233 PropertyTy);
3234
3235 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003236 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003237 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003238 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003239 // }
3240 PropertyListTy = llvm::StructType::get(IntTy,
3241 IntTy,
3242 llvm::ArrayType::get(PropertyTy, 0),
3243 NULL);
3244 CGM.getModule().addTypeName("struct._prop_list_t",
3245 PropertyListTy);
3246 // struct _prop_list_t *
3247 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3248
3249 // struct _objc_method {
3250 // SEL _cmd;
3251 // char *method_type;
3252 // char *_imp;
3253 // }
3254 MethodTy = llvm::StructType::get(SelectorPtrTy,
3255 Int8PtrTy,
3256 Int8PtrTy,
3257 NULL);
3258 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003259
3260 // struct _objc_cache *
3261 CacheTy = llvm::OpaqueType::get();
3262 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3263 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003264
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003265 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003266
3267 QualType IdType = Ctx.getObjCIdType();
3268 QualType SelType = Ctx.getObjCSelType();
3269 llvm::SmallVector<QualType,16> Params;
3270 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003271
3272 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003273 Params.push_back(IdType);
3274 Params.push_back(SelType);
3275 Params.push_back(Ctx.LongTy);
3276 Params.push_back(Ctx.BoolTy);
3277 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3278 false);
3279 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003280
3281 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3282 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003283 Params.push_back(IdType);
3284 Params.push_back(SelType);
3285 Params.push_back(Ctx.LongTy);
3286 Params.push_back(IdType);
3287 Params.push_back(Ctx.BoolTy);
3288 Params.push_back(Ctx.BoolTy);
3289 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3290 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3291
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003292 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003293
3294 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003295 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003296 Params.push_back(IdType);
3297 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3298 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3299 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003300
3301 // gc's API
3302 // id objc_read_weak (id *)
3303 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003304 Params.push_back(Ctx.getPointerType(IdType));
3305 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3306 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3307
Chris Lattner96508e12009-04-17 22:12:36 +00003308 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003309 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003310 Params.push_back(IdType);
3311 Params.push_back(Ctx.getPointerType(IdType));
3312
3313 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003314 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3315 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3316 GcAssignStrongCastFn =
3317 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003318
3319 // void objc_exception_throw(id)
3320 Params.clear();
3321 Params.push_back(IdType);
3322
3323 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003324 ExceptionThrowFn =
3325 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003326
3327 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003328 // void objc_sync_exit (id)
3329 Params.clear();
3330 Params.push_back(IdType);
3331
3332 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003333 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003334}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003335
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003336ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3337 : ObjCCommonTypesHelper(cgm)
3338{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003339 // struct _objc_method_description {
3340 // SEL name;
3341 // char *types;
3342 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003343 MethodDescriptionTy =
3344 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003345 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003346 NULL);
3347 CGM.getModule().addTypeName("struct._objc_method_description",
3348 MethodDescriptionTy);
3349
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003350 // struct _objc_method_description_list {
3351 // int count;
3352 // struct _objc_method_description[1];
3353 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003354 MethodDescriptionListTy =
3355 llvm::StructType::get(IntTy,
3356 llvm::ArrayType::get(MethodDescriptionTy, 0),
3357 NULL);
3358 CGM.getModule().addTypeName("struct._objc_method_description_list",
3359 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003360
3361 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003362 MethodDescriptionListPtrTy =
3363 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3364
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003365 // Protocol description structures
3366
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003367 // struct _objc_protocol_extension {
3368 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3369 // struct _objc_method_description_list *optional_instance_methods;
3370 // struct _objc_method_description_list *optional_class_methods;
3371 // struct _objc_property_list *instance_properties;
3372 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003373 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003374 llvm::StructType::get(IntTy,
3375 MethodDescriptionListPtrTy,
3376 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003377 PropertyListPtrTy,
3378 NULL);
3379 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3380 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003381
3382 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003383 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3384
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003385 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003386
3387 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3388 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3389
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003390 const llvm::Type *T =
3391 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3392 LongTy,
3393 llvm::ArrayType::get(ProtocolTyHolder, 0),
3394 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003395 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3396
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003397 // struct _objc_protocol {
3398 // struct _objc_protocol_extension *isa;
3399 // char *protocol_name;
3400 // struct _objc_protocol **_objc_protocol_list;
3401 // struct _objc_method_description_list *instance_methods;
3402 // struct _objc_method_description_list *class_methods;
3403 // }
3404 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003405 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003406 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3407 MethodDescriptionListPtrTy,
3408 MethodDescriptionListPtrTy,
3409 NULL);
3410 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3411
3412 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3413 CGM.getModule().addTypeName("struct._objc_protocol_list",
3414 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003415 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003416 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3417
3418 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003419 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003420 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003421
3422 // Class description structures
3423
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003424 // struct _objc_ivar {
3425 // char *ivar_name;
3426 // char *ivar_type;
3427 // int ivar_offset;
3428 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003429 IvarTy = llvm::StructType::get(Int8PtrTy,
3430 Int8PtrTy,
3431 IntTy,
3432 NULL);
3433 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3434
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003435 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003436 IvarListTy = llvm::OpaqueType::get();
3437 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3438 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3439
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003440 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003441 MethodListTy = llvm::OpaqueType::get();
3442 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3443 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3444
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003445 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003446 ClassExtensionTy =
3447 llvm::StructType::get(IntTy,
3448 Int8PtrTy,
3449 PropertyListPtrTy,
3450 NULL);
3451 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3452 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3453
3454 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3455
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003456 // struct _objc_class {
3457 // Class isa;
3458 // Class super_class;
3459 // char *name;
3460 // long version;
3461 // long info;
3462 // long instance_size;
3463 // struct _objc_ivar_list *ivars;
3464 // struct _objc_method_list *methods;
3465 // struct _objc_cache *cache;
3466 // struct _objc_protocol_list *protocols;
3467 // char *ivar_layout;
3468 // struct _objc_class_ext *ext;
3469 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003470 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3471 llvm::PointerType::getUnqual(ClassTyHolder),
3472 Int8PtrTy,
3473 LongTy,
3474 LongTy,
3475 LongTy,
3476 IvarListPtrTy,
3477 MethodListPtrTy,
3478 CachePtrTy,
3479 ProtocolListPtrTy,
3480 Int8PtrTy,
3481 ClassExtensionPtrTy,
3482 NULL);
3483 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3484
3485 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3486 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3487 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3488
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003489 // struct _objc_category {
3490 // char *category_name;
3491 // char *class_name;
3492 // struct _objc_method_list *instance_method;
3493 // struct _objc_method_list *class_method;
3494 // uint32_t size; // sizeof(struct _objc_category)
3495 // struct _objc_property_list *instance_properties;// category's @property
3496 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003497 CategoryTy = llvm::StructType::get(Int8PtrTy,
3498 Int8PtrTy,
3499 MethodListPtrTy,
3500 MethodListPtrTy,
3501 ProtocolListPtrTy,
3502 IntTy,
3503 PropertyListPtrTy,
3504 NULL);
3505 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3506
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003507 // Global metadata structures
3508
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003509 // struct _objc_symtab {
3510 // long sel_ref_cnt;
3511 // SEL *refs;
3512 // short cls_def_cnt;
3513 // short cat_def_cnt;
3514 // char *defs[cls_def_cnt + cat_def_cnt];
3515 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003516 SymtabTy = llvm::StructType::get(LongTy,
3517 SelectorPtrTy,
3518 ShortTy,
3519 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003520 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003521 NULL);
3522 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3523 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3524
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003525 // struct _objc_module {
3526 // long version;
3527 // long size; // sizeof(struct _objc_module)
3528 // char *name;
3529 // struct _objc_symtab* symtab;
3530 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003531 ModuleTy =
3532 llvm::StructType::get(LongTy,
3533 LongTy,
3534 Int8PtrTy,
3535 SymtabPtrTy,
3536 NULL);
3537 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003538
Daniel Dunbar49f66022008-09-24 03:38:44 +00003539 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003540
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003541 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003542 std::vector<const llvm::Type*> Params;
3543 Params.push_back(ObjectPtrTy);
3544 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003545 MessageSendFn =
3546 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3547 Params,
3548 true),
3549 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003550
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003551 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003552 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003553 Params.push_back(ObjectPtrTy);
3554 Params.push_back(SelectorPtrTy);
3555 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003556 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3557 Params,
3558 true),
3559 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003560
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003561 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003562 Params.clear();
3563 Params.push_back(ObjectPtrTy);
3564 Params.push_back(SelectorPtrTy);
3565 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003566 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003567 MessageSendFpretFn =
3568 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3569 Params,
3570 true),
3571 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003572
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003573 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003574 Params.clear();
3575 Params.push_back(SuperPtrTy);
3576 Params.push_back(SelectorPtrTy);
3577 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003578 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3579 Params,
3580 true),
3581 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003582
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003583 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3584 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003585 Params.clear();
3586 Params.push_back(Int8PtrTy);
3587 Params.push_back(SuperPtrTy);
3588 Params.push_back(SelectorPtrTy);
3589 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003590 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3591 Params,
3592 true),
3593 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003594
3595 // There is no objc_msgSendSuper_fpret? How can that work?
3596 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003597
Anders Carlsson124526b2008-09-09 10:10:21 +00003598 // FIXME: This is the size of the setjmp buffer and should be
3599 // target specific. 18 is what's used on 32-bit X86.
3600 uint64_t SetJmpBufferSize = 18;
3601
3602 // Exceptions
3603 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003604 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003605
3606 ExceptionDataTy =
3607 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3608 SetJmpBufferSize),
3609 StackPtrTy, NULL);
3610 CGM.getModule().addTypeName("struct._objc_exception_data",
3611 ExceptionDataTy);
3612
3613 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003614 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3615 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003616 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3617 Params,
3618 false),
3619 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003620 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003621 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3622 Params,
3623 false),
3624 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003625 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003626 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3627 Params,
3628 false),
3629 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003630
3631 Params.clear();
3632 Params.push_back(ClassPtrTy);
3633 Params.push_back(ObjectPtrTy);
3634 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003635 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3636 Params,
3637 false),
3638 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003639
Anders Carlsson124526b2008-09-09 10:10:21 +00003640 Params.clear();
3641 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3642 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003643 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3644 Params,
3645 false),
3646 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003647
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003648}
3649
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003650ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003651: ObjCCommonTypesHelper(cgm)
3652{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003653 // struct _method_list_t {
3654 // uint32_t entsize; // sizeof(struct _objc_method)
3655 // uint32_t method_count;
3656 // struct _objc_method method_list[method_count];
3657 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003658 MethodListnfABITy = llvm::StructType::get(IntTy,
3659 IntTy,
3660 llvm::ArrayType::get(MethodTy, 0),
3661 NULL);
3662 CGM.getModule().addTypeName("struct.__method_list_t",
3663 MethodListnfABITy);
3664 // struct method_list_t *
3665 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003666
3667 // struct _protocol_t {
3668 // id isa; // NULL
3669 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003670 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003671 // const struct method_list_t * const instance_methods;
3672 // const struct method_list_t * const class_methods;
3673 // const struct method_list_t *optionalInstanceMethods;
3674 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003675 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003676 // const uint32_t size; // sizeof(struct _protocol_t)
3677 // const uint32_t flags; // = 0
3678 // }
3679
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003680 // Holder for struct _protocol_list_t *
3681 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3682
3683 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3684 Int8PtrTy,
3685 llvm::PointerType::getUnqual(
3686 ProtocolListTyHolder),
3687 MethodListnfABIPtrTy,
3688 MethodListnfABIPtrTy,
3689 MethodListnfABIPtrTy,
3690 MethodListnfABIPtrTy,
3691 PropertyListPtrTy,
3692 IntTy,
3693 IntTy,
3694 NULL);
3695 CGM.getModule().addTypeName("struct._protocol_t",
3696 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003697
3698 // struct _protocol_t*
3699 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003700
Fariborz Jahanianda320092009-01-29 19:24:30 +00003701 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003702 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003703 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003704 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003705 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3706 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003707 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003708 NULL);
3709 CGM.getModule().addTypeName("struct._objc_protocol_list",
3710 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003711 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3712 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003713
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003714 // struct _objc_protocol_list*
3715 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003716
3717 // struct _ivar_t {
3718 // unsigned long int *offset; // pointer to ivar offset location
3719 // char *name;
3720 // char *type;
3721 // uint32_t alignment;
3722 // uint32_t size;
3723 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003724 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3725 Int8PtrTy,
3726 Int8PtrTy,
3727 IntTy,
3728 IntTy,
3729 NULL);
3730 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3731
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003732 // struct _ivar_list_t {
3733 // uint32 entsize; // sizeof(struct _ivar_t)
3734 // uint32 count;
3735 // struct _iver_t list[count];
3736 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003737 IvarListnfABITy = llvm::StructType::get(IntTy,
3738 IntTy,
3739 llvm::ArrayType::get(
3740 IvarnfABITy, 0),
3741 NULL);
3742 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3743
3744 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003745
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003746 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003747 // uint32_t const flags;
3748 // uint32_t const instanceStart;
3749 // uint32_t const instanceSize;
3750 // uint32_t const reserved; // only when building for 64bit targets
3751 // const uint8_t * const ivarLayout;
3752 // const char *const name;
3753 // const struct _method_list_t * const baseMethods;
3754 // const struct _objc_protocol_list *const baseProtocols;
3755 // const struct _ivar_list_t *const ivars;
3756 // const uint8_t * const weakIvarLayout;
3757 // const struct _prop_list_t * const properties;
3758 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003759
3760 // FIXME. Add 'reserved' field in 64bit abi mode!
3761 ClassRonfABITy = llvm::StructType::get(IntTy,
3762 IntTy,
3763 IntTy,
3764 Int8PtrTy,
3765 Int8PtrTy,
3766 MethodListnfABIPtrTy,
3767 ProtocolListnfABIPtrTy,
3768 IvarListnfABIPtrTy,
3769 Int8PtrTy,
3770 PropertyListPtrTy,
3771 NULL);
3772 CGM.getModule().addTypeName("struct._class_ro_t",
3773 ClassRonfABITy);
3774
3775 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3776 std::vector<const llvm::Type*> Params;
3777 Params.push_back(ObjectPtrTy);
3778 Params.push_back(SelectorPtrTy);
3779 ImpnfABITy = llvm::PointerType::getUnqual(
3780 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3781
3782 // struct _class_t {
3783 // struct _class_t *isa;
3784 // struct _class_t * const superclass;
3785 // void *cache;
3786 // IMP *vtable;
3787 // struct class_ro_t *ro;
3788 // }
3789
3790 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3791 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3792 llvm::PointerType::getUnqual(ClassTyHolder),
3793 CachePtrTy,
3794 llvm::PointerType::getUnqual(ImpnfABITy),
3795 llvm::PointerType::getUnqual(
3796 ClassRonfABITy),
3797 NULL);
3798 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3799
3800 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3801 ClassnfABITy);
3802
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003803 // LLVM for struct _class_t *
3804 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3805
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003806 // struct _category_t {
3807 // const char * const name;
3808 // struct _class_t *const cls;
3809 // const struct _method_list_t * const instance_methods;
3810 // const struct _method_list_t * const class_methods;
3811 // const struct _protocol_list_t * const protocols;
3812 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003813 // }
3814 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003815 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003816 MethodListnfABIPtrTy,
3817 MethodListnfABIPtrTy,
3818 ProtocolListnfABIPtrTy,
3819 PropertyListPtrTy,
3820 NULL);
3821 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003822
3823 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003824 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3825 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003826
3827 // MessageRefTy - LLVM for:
3828 // struct _message_ref_t {
3829 // IMP messenger;
3830 // SEL name;
3831 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003832
3833 // First the clang type for struct _message_ref_t
3834 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3835 SourceLocation(),
3836 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003837 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3838 Ctx.VoidPtrTy, 0, false));
3839 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3840 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003841 RD->completeDefinition(Ctx);
3842
3843 MessageRefCTy = Ctx.getTagDeclType(RD);
3844 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3845 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003846
3847 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3848 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3849
3850 // SuperMessageRefTy - LLVM for:
3851 // struct _super_message_ref_t {
3852 // SUPER_IMP messenger;
3853 // SEL name;
3854 // };
3855 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3856 SelectorPtrTy,
3857 NULL);
3858 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3859
3860 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3861 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3862
3863 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3864 Params.clear();
3865 Params.push_back(ObjectPtrTy);
3866 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003867 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3868 Params,
3869 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003870 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003871 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003872 "objc_msgSend_fixup");
3873
3874 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3875 MessageSendFpretFixupFn =
3876 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3877 Params,
3878 true),
3879 "objc_msgSend_fpret_fixup");
3880
3881 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3882 MessageSendStretFixupFn =
3883 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3884 Params,
3885 true),
3886 "objc_msgSend_stret_fixup");
3887
3888 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3889 MessageSendIdFixupFn =
3890 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3891 Params,
3892 true),
3893 "objc_msgSendId_fixup");
3894
3895
3896 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3897 MessageSendIdStretFixupFn =
3898 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3899 Params,
3900 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003901 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003902
3903 // id objc_msgSendSuper2_fixup (struct objc_super *,
3904 // struct _super_message_ref_t*, ...)
3905 Params.clear();
3906 Params.push_back(SuperPtrTy);
3907 Params.push_back(SuperMessageRefPtrTy);
3908 MessageSendSuper2FixupFn =
3909 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3910 Params,
3911 true),
3912 "objc_msgSendSuper2_fixup");
3913
3914
3915 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3916 // struct _super_message_ref_t*, ...)
3917 MessageSendSuper2StretFixupFn =
3918 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3919 Params,
3920 true),
3921 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003922
3923 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003924 Params.push_back(Int8PtrTy);
3925 UnwindResumeOrRethrowFn =
3926 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3927 Params,
3928 false),
3929 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003930 ObjCBeginCatchFn =
3931 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3932 Params,
3933 false),
3934 "objc_begin_catch");
3935
3936 Params.clear();
3937 ObjCEndCatchFn =
3938 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3939 Params,
3940 false),
3941 "objc_end_catch");
3942
3943 // struct objc_typeinfo {
3944 // const void** vtable; // objc_ehtype_vtable + 2
3945 // const char* name; // c++ typeinfo string
3946 // Class cls;
3947 // };
3948 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3949 Int8PtrTy,
3950 ClassnfABIPtrTy,
3951 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003952 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003953 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003954}
3955
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003956llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3957 FinishNonFragileABIModule();
3958
3959 return NULL;
3960}
3961
3962void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3963 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003964
3965 // Build list of all implemented classe addresses in array
3966 // L_OBJC_LABEL_CLASS_$.
3967 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3968 // list of 'nonlazy' implementations (defined as those with a +load{}
3969 // method!!).
3970 unsigned NumClasses = DefinedClasses.size();
3971 if (NumClasses) {
3972 std::vector<llvm::Constant*> Symbols(NumClasses);
3973 for (unsigned i=0; i<NumClasses; i++)
3974 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3975 ObjCTypes.Int8PtrTy);
3976 llvm::Constant* Init =
3977 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3978 NumClasses),
3979 Symbols);
3980
3981 llvm::GlobalVariable *GV =
3982 new llvm::GlobalVariable(Init->getType(), false,
3983 llvm::GlobalValue::InternalLinkage,
3984 Init,
3985 "\01L_OBJC_LABEL_CLASS_$",
3986 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003987 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003988 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3989 UsedGlobals.push_back(GV);
3990 }
3991
3992 // Build list of all implemented category addresses in array
3993 // L_OBJC_LABEL_CATEGORY_$.
3994 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3995 // list of 'nonlazy' category implementations (defined as those with a +load{}
3996 // method!!).
3997 unsigned NumCategory = DefinedCategories.size();
3998 if (NumCategory) {
3999 std::vector<llvm::Constant*> Symbols(NumCategory);
4000 for (unsigned i=0; i<NumCategory; i++)
4001 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4002 ObjCTypes.Int8PtrTy);
4003 llvm::Constant* Init =
4004 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4005 NumCategory),
4006 Symbols);
4007
4008 llvm::GlobalVariable *GV =
4009 new llvm::GlobalVariable(Init->getType(), false,
4010 llvm::GlobalValue::InternalLinkage,
4011 Init,
4012 "\01L_OBJC_LABEL_CATEGORY_$",
4013 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004014 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004015 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4016 UsedGlobals.push_back(GV);
4017 }
4018
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004019 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4020 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4021 std::vector<llvm::Constant*> Values(2);
4022 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004023 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004024 // FIXME: Fix and continue?
4025 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4026 flags |= eImageInfo_GarbageCollected;
4027 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4028 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004029 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004030 llvm::Constant* Init = llvm::ConstantArray::get(
4031 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4032 Values);
4033 llvm::GlobalVariable *IMGV =
4034 new llvm::GlobalVariable(Init->getType(), false,
4035 llvm::GlobalValue::InternalLinkage,
4036 Init,
4037 "\01L_OBJC_IMAGE_INFO",
4038 &CGM.getModule());
4039 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4040 UsedGlobals.push_back(IMGV);
4041
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004042 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004043
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004044 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4045 e = UsedGlobals.end(); i != e; ++i) {
4046 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4047 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004048
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004049 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4050 llvm::GlobalValue *GV =
4051 new llvm::GlobalVariable(AT, false,
4052 llvm::GlobalValue::AppendingLinkage,
4053 llvm::ConstantArray::get(AT, Used),
4054 "llvm.used",
4055 &CGM.getModule());
4056
4057 GV->setSection("llvm.metadata");
4058
4059}
4060
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004061// Metadata flags
4062enum MetaDataDlags {
4063 CLS = 0x0,
4064 CLS_META = 0x1,
4065 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004066 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004067 CLS_EXCEPTION = 0x20
4068};
4069/// BuildClassRoTInitializer - generate meta-data for:
4070/// struct _class_ro_t {
4071/// uint32_t const flags;
4072/// uint32_t const instanceStart;
4073/// uint32_t const instanceSize;
4074/// uint32_t const reserved; // only when building for 64bit targets
4075/// const uint8_t * const ivarLayout;
4076/// const char *const name;
4077/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004078/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004079/// const struct _ivar_list_t *const ivars;
4080/// const uint8_t * const weakIvarLayout;
4081/// const struct _prop_list_t * const properties;
4082/// }
4083///
4084llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4085 unsigned flags,
4086 unsigned InstanceStart,
4087 unsigned InstanceSize,
4088 const ObjCImplementationDecl *ID) {
4089 std::string ClassName = ID->getNameAsString();
4090 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4091 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4092 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4093 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4094 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004095 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004096 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004097 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004098 // const struct _method_list_t * const baseMethods;
4099 std::vector<llvm::Constant*> Methods;
4100 std::string MethodListName("\01l_OBJC_$_");
4101 if (flags & CLS_META) {
4102 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4103 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4104 e = ID->classmeth_end(); i != e; ++i) {
4105 // Class methods should always be defined.
4106 Methods.push_back(GetMethodConstant(*i));
4107 }
4108 } else {
4109 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4110 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4111 e = ID->instmeth_end(); i != e; ++i) {
4112 // Instance methods should always be defined.
4113 Methods.push_back(GetMethodConstant(*i));
4114 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004115 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4116 e = ID->propimpl_end(); i != e; ++i) {
4117 ObjCPropertyImplDecl *PID = *i;
4118
4119 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4120 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4121
4122 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4123 if (llvm::Constant *C = GetMethodConstant(MD))
4124 Methods.push_back(C);
4125 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4126 if (llvm::Constant *C = GetMethodConstant(MD))
4127 Methods.push_back(C);
4128 }
4129 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004130 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004131 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004132 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004133
4134 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4135 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4136 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4137 + OID->getNameAsString(),
4138 OID->protocol_begin(),
4139 OID->protocol_end());
4140
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004141 if (flags & CLS_META)
4142 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4143 else
4144 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004145 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004146 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004147 if (flags & CLS_META)
4148 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4149 else
4150 Values[ 9] =
4151 EmitPropertyList(
4152 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4153 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004154 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4155 Values);
4156 llvm::GlobalVariable *CLASS_RO_GV =
4157 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4158 llvm::GlobalValue::InternalLinkage,
4159 Init,
4160 (flags & CLS_META) ?
4161 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4162 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4163 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004164 CLASS_RO_GV->setAlignment(
4165 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004166 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004167 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004168
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004169}
4170
4171/// BuildClassMetaData - This routine defines that to-level meta-data
4172/// for the given ClassName for:
4173/// struct _class_t {
4174/// struct _class_t *isa;
4175/// struct _class_t * const superclass;
4176/// void *cache;
4177/// IMP *vtable;
4178/// struct class_ro_t *ro;
4179/// }
4180///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004181llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4182 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004183 llvm::Constant *IsAGV,
4184 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004185 llvm::Constant *ClassRoGV,
4186 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004187 std::vector<llvm::Constant*> Values(5);
4188 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004189 Values[1] = SuperClassGV
4190 ? SuperClassGV
4191 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004192 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4193 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4194 Values[4] = ClassRoGV; // &CLASS_RO_GV
4195 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4196 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004197 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4198 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004199 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004200 GV->setAlignment(
4201 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004202 if (HiddenVisibility)
4203 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004204 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004205}
4206
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004207void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4208 std::string ClassName = ID->getNameAsString();
4209 if (!ObjCEmptyCacheVar) {
4210 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004211 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004212 false,
4213 llvm::GlobalValue::ExternalLinkage,
4214 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004215 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004216 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004217
4218 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004219 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004220 false,
4221 llvm::GlobalValue::ExternalLinkage,
4222 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004223 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004224 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004225 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004226 assert(ID->getClassInterface() &&
4227 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004228 uint32_t InstanceStart =
4229 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4230 uint32_t InstanceSize = InstanceStart;
4231 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004232 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4233 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004234
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004235 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004236
Daniel Dunbar04d40782009-04-14 06:00:08 +00004237 bool classIsHidden =
4238 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004239 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004240 flags |= OBJC2_CLS_HIDDEN;
4241 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004242 // class is root
4243 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004244 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004245 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004246 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004247 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004248 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4249 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4250 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004251 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004252 // work on super class metadata symbol.
4253 std::string SuperClassName =
4254 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004255 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004256 }
4257 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4258 InstanceStart,
4259 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004260 std::string TClassName = ObjCMetaClassName + ClassName;
4261 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004262 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4263 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004264
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004265 // Metadata for the class
4266 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004267 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004268 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004269
4270 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4271 flags |= CLS_EXCEPTION;
4272
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004273 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004274 flags |= CLS_ROOT;
4275 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004276 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004277 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004278 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004279 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004280 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004281 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004282 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004283 InstanceStart = InstanceSize = 0;
4284 if (ObjCInterfaceDecl *OID =
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004285 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004286 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004287 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004288
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004289 RecordDecl::field_iterator firstField, lastField;
4290 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004291
Douglas Gregor6ab35242009-04-09 21:40:53 +00004292 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004293 ifield = firstField; ifield != e; ++ifield)
4294 lastField = ifield;
4295
Douglas Gregor6ab35242009-04-09 21:40:53 +00004296 if (lastField != RD->field_end(CGM.getContext())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004297 FieldDecl *Field = *lastField;
4298 const llvm::Type *FieldTy =
4299 CGM.getTypes().ConvertTypeForMem(Field->getType());
4300 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004301 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004302 if (firstField == RD->field_end(CGM.getContext()))
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004303 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004304 else {
4305 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004306 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004307 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004308 }
4309 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004310 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004311 InstanceStart,
4312 InstanceSize,
4313 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004314
4315 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004316 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004317 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4318 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004319 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004320
4321 // Force the definition of the EHType if necessary.
4322 if (flags & CLS_EXCEPTION)
4323 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004324}
4325
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004326/// GenerateProtocolRef - This routine is called to generate code for
4327/// a protocol reference expression; as in:
4328/// @code
4329/// @protocol(Proto1);
4330/// @endcode
4331/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4332/// which will hold address of the protocol meta-data.
4333///
4334llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4335 const ObjCProtocolDecl *PD) {
4336
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004337 // This routine is called for @protocol only. So, we must build definition
4338 // of protocol's meta-data (not a reference to it!)
4339 //
4340 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004341 ObjCTypes.ExternalProtocolPtrTy);
4342
4343 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4344 ProtocolName += PD->getNameAsCString();
4345
4346 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4347 if (PTGV)
4348 return Builder.CreateLoad(PTGV, false, "tmp");
4349 PTGV = new llvm::GlobalVariable(
4350 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004351 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004352 Init,
4353 ProtocolName,
4354 &CGM.getModule());
4355 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4356 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4357 UsedGlobals.push_back(PTGV);
4358 return Builder.CreateLoad(PTGV, false, "tmp");
4359}
4360
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004361/// GenerateCategory - Build metadata for a category implementation.
4362/// struct _category_t {
4363/// const char * const name;
4364/// struct _class_t *const cls;
4365/// const struct _method_list_t * const instance_methods;
4366/// const struct _method_list_t * const class_methods;
4367/// const struct _protocol_list_t * const protocols;
4368/// const struct _prop_list_t * const properties;
4369/// }
4370///
4371void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4372{
4373 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004374 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4375 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004376 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004377 std::string ExtClassName(getClassSymbolPrefix() +
4378 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004379
4380 std::vector<llvm::Constant*> Values(6);
4381 Values[0] = GetClassName(OCD->getIdentifier());
4382 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004383 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004384 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004385 std::vector<llvm::Constant*> Methods;
4386 std::string MethodListName(Prefix);
4387 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4388 "_$_" + OCD->getNameAsString();
4389
4390 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4391 e = OCD->instmeth_end(); i != e; ++i) {
4392 // Instance methods should always be defined.
4393 Methods.push_back(GetMethodConstant(*i));
4394 }
4395
4396 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004397 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004398 Methods);
4399
4400 MethodListName = Prefix;
4401 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4402 OCD->getNameAsString();
4403 Methods.clear();
4404 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4405 e = OCD->classmeth_end(); i != e; ++i) {
4406 // Class methods should always be defined.
4407 Methods.push_back(GetMethodConstant(*i));
4408 }
4409
4410 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004411 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004412 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004413 const ObjCCategoryDecl *Category =
4414 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004415 if (Category) {
4416 std::string ExtName(Interface->getNameAsString() + "_$_" +
4417 OCD->getNameAsString());
4418 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4419 + Interface->getNameAsString() + "_$_"
4420 + Category->getNameAsString(),
4421 Category->protocol_begin(),
4422 Category->protocol_end());
4423 Values[5] =
4424 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4425 OCD, Category, ObjCTypes);
4426 }
4427 else {
4428 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4429 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4430 }
4431
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004432 llvm::Constant *Init =
4433 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4434 Values);
4435 llvm::GlobalVariable *GCATV
4436 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4437 false,
4438 llvm::GlobalValue::InternalLinkage,
4439 Init,
4440 ExtCatName,
4441 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004442 GCATV->setAlignment(
4443 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004444 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004445 UsedGlobals.push_back(GCATV);
4446 DefinedCategories.push_back(GCATV);
4447}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004448
4449/// GetMethodConstant - Return a struct objc_method constant for the
4450/// given method if it has been defined. The result is null if the
4451/// method has not been defined. The return value has type MethodPtrTy.
4452llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4453 const ObjCMethodDecl *MD) {
4454 // FIXME: Use DenseMap::lookup
4455 llvm::Function *Fn = MethodDefinitions[MD];
4456 if (!Fn)
4457 return 0;
4458
4459 std::vector<llvm::Constant*> Method(3);
4460 Method[0] =
4461 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4462 ObjCTypes.SelectorPtrTy);
4463 Method[1] = GetMethodVarType(MD);
4464 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4465 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4466}
4467
4468/// EmitMethodList - Build meta-data for method declarations
4469/// struct _method_list_t {
4470/// uint32_t entsize; // sizeof(struct _objc_method)
4471/// uint32_t method_count;
4472/// struct _objc_method method_list[method_count];
4473/// }
4474///
4475llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4476 const std::string &Name,
4477 const char *Section,
4478 const ConstantVector &Methods) {
4479 // Return null for empty list.
4480 if (Methods.empty())
4481 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4482
4483 std::vector<llvm::Constant*> Values(3);
4484 // sizeof(struct _objc_method)
4485 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4486 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4487 // method_count
4488 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4489 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4490 Methods.size());
4491 Values[2] = llvm::ConstantArray::get(AT, Methods);
4492 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4493
4494 llvm::GlobalVariable *GV =
4495 new llvm::GlobalVariable(Init->getType(), false,
4496 llvm::GlobalValue::InternalLinkage,
4497 Init,
4498 Name,
4499 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004500 GV->setAlignment(
4501 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004502 GV->setSection(Section);
4503 UsedGlobals.push_back(GV);
4504 return llvm::ConstantExpr::getBitCast(GV,
4505 ObjCTypes.MethodListnfABIPtrTy);
4506}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004507
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004508/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4509/// the given ivar.
4510///
4511llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004512 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004513 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004514 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004515 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4516 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004517 llvm::GlobalVariable *IvarOffsetGV =
4518 CGM.getModule().getGlobalVariable(Name);
4519 if (!IvarOffsetGV)
4520 IvarOffsetGV =
4521 new llvm::GlobalVariable(ObjCTypes.LongTy,
4522 false,
4523 llvm::GlobalValue::ExternalLinkage,
4524 0,
4525 Name,
4526 &CGM.getModule());
4527 return IvarOffsetGV;
4528}
4529
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004530llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004531 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004532 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004533 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004534 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4535 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4536 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004537 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004538 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004539
4540 // FIXME: This matches gcc, but shouldn't the visibility be set on
4541 // the use as well (i.e., in ObjCIvarOffsetVariable).
4542 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4543 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4544 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004545 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004546 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004547 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004548 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004549 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004550}
4551
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004552/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004553/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004554/// IvarListnfABIPtrTy.
4555/// struct _ivar_t {
4556/// unsigned long int *offset; // pointer to ivar offset location
4557/// char *name;
4558/// char *type;
4559/// uint32_t alignment;
4560/// uint32_t size;
4561/// }
4562/// struct _ivar_list_t {
4563/// uint32 entsize; // sizeof(struct _ivar_t)
4564/// uint32 count;
4565/// struct _iver_t list[count];
4566/// }
4567///
4568llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4569 const ObjCImplementationDecl *ID) {
4570
4571 std::vector<llvm::Constant*> Ivars, Ivar(5);
4572
4573 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4574 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4575
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004576 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004577 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004578
4579 RecordDecl::field_iterator i,p;
4580 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004581 // collect declared and synthesized ivars in a small vector.
4582 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4583 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4584 E = OID->ivar_end(); I != E; ++I)
4585 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004586 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4587 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004588 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4589 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004590
Fariborz Jahanian18191882009-03-31 18:11:23 +00004591 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004592 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4593 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004594 FieldDecl *Field = *i;
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004595 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++],
4596 GetIvarBaseOffset(Layout, Field));
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004597 if (Field->getIdentifier())
4598 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4599 else
4600 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004601 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004602 const llvm::Type *FieldTy =
4603 CGM.getTypes().ConvertTypeForMem(Field->getType());
4604 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4605 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4606 Field->getType().getTypePtr()) >> 3;
4607 Align = llvm::Log2_32(Align);
4608 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004609 // NOTE. Size of a bitfield does not match gcc's, because of the way
4610 // bitfields are treated special in each. But I am told that 'size'
4611 // for bitfield ivars is ignored by the runtime so it does not matter.
4612 // (even if it matters, some day, there is enough info. to get the bitfield
4613 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004614 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4615 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4616 }
4617 // Return null for empty list.
4618 if (Ivars.empty())
4619 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4620 std::vector<llvm::Constant*> Values(3);
4621 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4622 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4623 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4624 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4625 Ivars.size());
4626 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4627 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4628 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4629 llvm::GlobalVariable *GV =
4630 new llvm::GlobalVariable(Init->getType(), false,
4631 llvm::GlobalValue::InternalLinkage,
4632 Init,
4633 Prefix + OID->getNameAsString(),
4634 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004635 GV->setAlignment(
4636 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004637 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004638
4639 UsedGlobals.push_back(GV);
4640 return llvm::ConstantExpr::getBitCast(GV,
4641 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004642}
4643
4644llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4645 const ObjCProtocolDecl *PD) {
4646 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4647
4648 if (!Entry) {
4649 // We use the initializer as a marker of whether this is a forward
4650 // reference or not. At module finalization we add the empty
4651 // contents for protocols which were referenced but never defined.
4652 Entry =
4653 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4654 llvm::GlobalValue::ExternalLinkage,
4655 0,
4656 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4657 &CGM.getModule());
4658 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4659 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004660 }
4661
4662 return Entry;
4663}
4664
4665/// GetOrEmitProtocol - Generate the protocol meta-data:
4666/// @code
4667/// struct _protocol_t {
4668/// id isa; // NULL
4669/// const char * const protocol_name;
4670/// const struct _protocol_list_t * protocol_list; // super protocols
4671/// const struct method_list_t * const instance_methods;
4672/// const struct method_list_t * const class_methods;
4673/// const struct method_list_t *optionalInstanceMethods;
4674/// const struct method_list_t *optionalClassMethods;
4675/// const struct _prop_list_t * properties;
4676/// const uint32_t size; // sizeof(struct _protocol_t)
4677/// const uint32_t flags; // = 0
4678/// }
4679/// @endcode
4680///
4681
4682llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4683 const ObjCProtocolDecl *PD) {
4684 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4685
4686 // Early exit if a defining object has already been generated.
4687 if (Entry && Entry->hasInitializer())
4688 return Entry;
4689
4690 const char *ProtocolName = PD->getNameAsCString();
4691
4692 // Construct method lists.
4693 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4694 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004695 for (ObjCProtocolDecl::instmeth_iterator
4696 i = PD->instmeth_begin(CGM.getContext()),
4697 e = PD->instmeth_end(CGM.getContext());
4698 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004699 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004700 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004701 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4702 OptInstanceMethods.push_back(C);
4703 } else {
4704 InstanceMethods.push_back(C);
4705 }
4706 }
4707
Douglas Gregor6ab35242009-04-09 21:40:53 +00004708 for (ObjCProtocolDecl::classmeth_iterator
4709 i = PD->classmeth_begin(CGM.getContext()),
4710 e = PD->classmeth_end(CGM.getContext());
4711 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004712 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004713 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004714 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4715 OptClassMethods.push_back(C);
4716 } else {
4717 ClassMethods.push_back(C);
4718 }
4719 }
4720
4721 std::vector<llvm::Constant*> Values(10);
4722 // isa is NULL
4723 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4724 Values[1] = GetClassName(PD->getIdentifier());
4725 Values[2] = EmitProtocolList(
4726 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4727 PD->protocol_begin(),
4728 PD->protocol_end());
4729
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004730 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004731 + PD->getNameAsString(),
4732 "__DATA, __objc_const",
4733 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004734 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004735 + PD->getNameAsString(),
4736 "__DATA, __objc_const",
4737 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004738 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004739 + PD->getNameAsString(),
4740 "__DATA, __objc_const",
4741 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004742 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 + PD->getNameAsString(),
4744 "__DATA, __objc_const",
4745 OptClassMethods);
4746 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4747 0, PD, ObjCTypes);
4748 uint32_t Size =
4749 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4750 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4751 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4752 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4753 Values);
4754
4755 if (Entry) {
4756 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004757 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004758 Entry->setInitializer(Init);
4759 } else {
4760 Entry =
4761 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004762 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004763 Init,
4764 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4765 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004766 Entry->setAlignment(
4767 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004768 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004769 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004770 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4771
4772 // Use this protocol meta-data to build protocol list table in section
4773 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004774 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004775 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004776 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004777 Entry,
4778 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4779 +ProtocolName,
4780 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004781 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004782 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004783 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004784 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4785 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004786 return Entry;
4787}
4788
4789/// EmitProtocolList - Generate protocol list meta-data:
4790/// @code
4791/// struct _protocol_list_t {
4792/// long protocol_count; // Note, this is 32/64 bit
4793/// struct _protocol_t[protocol_count];
4794/// }
4795/// @endcode
4796///
4797llvm::Constant *
4798CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4799 ObjCProtocolDecl::protocol_iterator begin,
4800 ObjCProtocolDecl::protocol_iterator end) {
4801 std::vector<llvm::Constant*> ProtocolRefs;
4802
Fariborz Jahanianda320092009-01-29 19:24:30 +00004803 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004804 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004805 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4806
Daniel Dunbar948e2582009-02-15 07:36:20 +00004807 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004808 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4809 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004810 return llvm::ConstantExpr::getBitCast(GV,
4811 ObjCTypes.ProtocolListnfABIPtrTy);
4812
4813 for (; begin != end; ++begin)
4814 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4815
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816 // This list is null terminated.
4817 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004818 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004819
4820 std::vector<llvm::Constant*> Values(2);
4821 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4822 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004823 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004824 ProtocolRefs.size()),
4825 ProtocolRefs);
4826
4827 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4828 GV = new llvm::GlobalVariable(Init->getType(), false,
4829 llvm::GlobalValue::InternalLinkage,
4830 Init,
4831 Name,
4832 &CGM.getModule());
4833 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004834 GV->setAlignment(
4835 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004836 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004837 return llvm::ConstantExpr::getBitCast(GV,
4838 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004839}
4840
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004841/// GetMethodDescriptionConstant - This routine build following meta-data:
4842/// struct _objc_method {
4843/// SEL _cmd;
4844/// char *method_type;
4845/// char *_imp;
4846/// }
4847
4848llvm::Constant *
4849CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4850 std::vector<llvm::Constant*> Desc(3);
4851 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4852 ObjCTypes.SelectorPtrTy);
4853 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004854 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004855 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4856 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4857}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004858
4859/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4860/// This code gen. amounts to generating code for:
4861/// @code
4862/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4863/// @encode
4864///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004865LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004866 CodeGen::CodeGenFunction &CGF,
4867 QualType ObjectTy,
4868 llvm::Value *BaseValue,
4869 const ObjCIvarDecl *Ivar,
4870 const FieldDecl *Field,
4871 unsigned CVRQualifiers) {
4872 assert(ObjectTy->isObjCInterfaceType() &&
4873 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004874 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004875 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004876
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004877 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004878 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004879 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4880 // (char*)BaseValue + Offset_symbol
4881 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4882 // (type *)((char*)BaseValue + Offset_symbol)
4883 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004884 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004885 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4886 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004887
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004888 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004889 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004890 CodeGenTypes::BitFieldInfo bitFieldInfo =
4891 CGM.getTypes().getBitFieldInfo(Field);
4892 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004893 FieldTy->isSignedIntegerType(),
4894 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004895 }
4896
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004897 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004898 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4899 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004900 LValue::SetObjCIvar(LV, true);
4901 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004902}
4903
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004904llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4905 CodeGen::CodeGenFunction &CGF,
4906 ObjCInterfaceDecl *Interface,
4907 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004908 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4909 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004910}
4911
Fariborz Jahanian46551122009-02-04 00:22:57 +00004912CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4913 CodeGen::CodeGenFunction &CGF,
4914 QualType ResultType,
4915 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004916 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004917 QualType Arg0Ty,
4918 bool IsSuper,
4919 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004920 // FIXME. Even though IsSuper is passes. This function doese not
4921 // handle calls to 'super' receivers.
4922 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004923 llvm::Value *Arg0 = Receiver;
4924 if (!IsSuper)
4925 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004926
4927 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004928 // FIXME. This is too much work to get the ABI-specific result type
4929 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004930 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4931 llvm::SmallVector<QualType, 16>());
4932 llvm::Constant *Fn;
4933 std::string Name("\01l_");
4934 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004935#if 0
4936 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004937 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4938 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4939 // FIXME. Is there a better way of getting these names.
4940 // They are available in RuntimeFunctions vector pair.
4941 Name += "objc_msgSendId_stret_fixup";
4942 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004943 else
4944#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004945 if (IsSuper) {
4946 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4947 Name += "objc_msgSendSuper2_stret_fixup";
4948 }
4949 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004950 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004951 Fn = ObjCTypes.MessageSendStretFixupFn;
4952 Name += "objc_msgSend_stret_fixup";
4953 }
4954 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004955 else if (ResultType->isFloatingType() &&
4956 // Selection of frret API only happens in 32bit nonfragile ABI.
4957 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004958 Fn = ObjCTypes.MessageSendFpretFixupFn;
4959 Name += "objc_msgSend_fpret_fixup";
4960 }
4961 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004962#if 0
4963// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004964 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4965 Fn = ObjCTypes.MessageSendIdFixupFn;
4966 Name += "objc_msgSendId_fixup";
4967 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004968 else
4969#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004970 if (IsSuper) {
4971 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4972 Name += "objc_msgSendSuper2_fixup";
4973 }
4974 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004975 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004976 Fn = ObjCTypes.MessageSendFixupFn;
4977 Name += "objc_msgSend_fixup";
4978 }
4979 }
4980 Name += '_';
4981 std::string SelName(Sel.getAsString());
4982 // Replace all ':' in selector name with '_' ouch!
4983 for(unsigned i = 0; i < SelName.size(); i++)
4984 if (SelName[i] == ':')
4985 SelName[i] = '_';
4986 Name += SelName;
4987 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4988 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004989 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004990 std::vector<llvm::Constant*> Values(2);
4991 Values[0] = Fn;
4992 Values[1] = GetMethodVarName(Sel);
4993 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4994 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004995 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004996 Init,
4997 Name,
4998 &CGM.getModule());
4999 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005000 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005001 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005002 }
5003 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005004
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005005 CallArgList ActualArgs;
5006 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5007 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5008 ObjCTypes.MessageRefCPtrTy));
5009 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005010 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5011 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5012 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005013 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005014 Callee = CGF.Builder.CreateBitCast(Callee,
5015 llvm::PointerType::getUnqual(FTy));
5016 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005017}
5018
5019/// Generate code for a message send expression in the nonfragile abi.
5020CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5021 CodeGen::CodeGenFunction &CGF,
5022 QualType ResultType,
5023 Selector Sel,
5024 llvm::Value *Receiver,
5025 bool IsClassMessage,
5026 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005027 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005028 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005029 false, CallArgs);
5030}
5031
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005032llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005033CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005034 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5035
Daniel Dunbardfff2302009-03-02 05:18:14 +00005036 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005037 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5038 llvm::GlobalValue::ExternalLinkage,
5039 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005040 }
5041
5042 return GV;
5043}
5044
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005045llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005046 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005047 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5048
5049 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005050 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005051 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005052 Entry =
5053 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5054 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005055 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005056 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005057 &CGM.getModule());
5058 Entry->setAlignment(
5059 CGM.getTargetData().getPrefTypeAlignment(
5060 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005061 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5062 UsedGlobals.push_back(Entry);
5063 }
5064
5065 return Builder.CreateLoad(Entry, false, "tmp");
5066}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005067
Daniel Dunbar11394522009-04-18 08:51:00 +00005068llvm::Value *
5069CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5070 const ObjCInterfaceDecl *ID) {
5071 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5072
5073 if (!Entry) {
5074 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5075 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5076 Entry =
5077 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5078 llvm::GlobalValue::InternalLinkage,
5079 ClassGV,
5080 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5081 &CGM.getModule());
5082 Entry->setAlignment(
5083 CGM.getTargetData().getPrefTypeAlignment(
5084 ObjCTypes.ClassnfABIPtrTy));
5085 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005086 UsedGlobals.push_back(Entry);
5087 }
5088
5089 return Builder.CreateLoad(Entry, false, "tmp");
5090}
5091
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005092/// EmitMetaClassRef - Return a Value * of the address of _class_t
5093/// meta-data
5094///
5095llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5096 const ObjCInterfaceDecl *ID) {
5097 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5098 if (Entry)
5099 return Builder.CreateLoad(Entry, false, "tmp");
5100
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005101 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005102 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005103 Entry =
5104 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5105 llvm::GlobalValue::InternalLinkage,
5106 MetaClassGV,
5107 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5108 &CGM.getModule());
5109 Entry->setAlignment(
5110 CGM.getTargetData().getPrefTypeAlignment(
5111 ObjCTypes.ClassnfABIPtrTy));
5112
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005113 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005114 UsedGlobals.push_back(Entry);
5115
5116 return Builder.CreateLoad(Entry, false, "tmp");
5117}
5118
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005119/// GetClass - Return a reference to the class for the given interface
5120/// decl.
5121llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5122 const ObjCInterfaceDecl *ID) {
5123 return EmitClassRef(Builder, ID);
5124}
5125
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005126/// Generates a message send where the super is the receiver. This is
5127/// a message send to self with special delivery semantics indicating
5128/// which class's method should be called.
5129CodeGen::RValue
5130CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5131 QualType ResultType,
5132 Selector Sel,
5133 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005134 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005135 llvm::Value *Receiver,
5136 bool IsClassMessage,
5137 const CodeGen::CallArgList &CallArgs) {
5138 // ...
5139 // Create and init a super structure; this is a (receiver, class)
5140 // pair we will pass to objc_msgSendSuper.
5141 llvm::Value *ObjCSuper =
5142 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5143
5144 llvm::Value *ReceiverAsObject =
5145 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5146 CGF.Builder.CreateStore(ReceiverAsObject,
5147 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5148
5149 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005150 llvm::Value *Target;
5151 if (IsClassMessage) {
5152 if (isCategoryImpl) {
5153 // Message sent to "super' in a class method defined in
5154 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005155 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005156 Target = CGF.Builder.CreateStructGEP(Target, 0);
5157 Target = CGF.Builder.CreateLoad(Target);
5158 }
5159 else
5160 Target = EmitMetaClassRef(CGF.Builder, Class);
5161 }
5162 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005163 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005164
5165 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5166 // and ObjCTypes types.
5167 const llvm::Type *ClassTy =
5168 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5169 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5170 CGF.Builder.CreateStore(Target,
5171 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5172
5173 return EmitMessageSend(CGF, ResultType, Sel,
5174 ObjCSuper, ObjCTypes.SuperPtrCTy,
5175 true, CallArgs);
5176}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005177
5178llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5179 Selector Sel) {
5180 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5181
5182 if (!Entry) {
5183 llvm::Constant *Casted =
5184 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5185 ObjCTypes.SelectorPtrTy);
5186 Entry =
5187 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5188 llvm::GlobalValue::InternalLinkage,
5189 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5190 &CGM.getModule());
5191 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5192 UsedGlobals.push_back(Entry);
5193 }
5194
5195 return Builder.CreateLoad(Entry, false, "tmp");
5196}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005197/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5198/// objc_assign_ivar (id src, id *dst)
5199///
5200void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5201 llvm::Value *src, llvm::Value *dst)
5202{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005203 const llvm::Type * SrcTy = src->getType();
5204 if (!isa<llvm::PointerType>(SrcTy)) {
5205 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5206 assert(Size <= 8 && "does not support size > 8");
5207 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5208 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005209 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5210 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005211 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5212 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5213 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5214 src, dst, "assignivar");
5215 return;
5216}
5217
5218/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5219/// objc_assign_strongCast (id src, id *dst)
5220///
5221void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5222 CodeGen::CodeGenFunction &CGF,
5223 llvm::Value *src, llvm::Value *dst)
5224{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005225 const llvm::Type * SrcTy = src->getType();
5226 if (!isa<llvm::PointerType>(SrcTy)) {
5227 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5228 assert(Size <= 8 && "does not support size > 8");
5229 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5230 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005231 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5232 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005233 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5234 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5235 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5236 src, dst, "weakassign");
5237 return;
5238}
5239
5240/// EmitObjCWeakRead - Code gen for loading value of a __weak
5241/// object: objc_read_weak (id *src)
5242///
5243llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5244 CodeGen::CodeGenFunction &CGF,
5245 llvm::Value *AddrWeakObj)
5246{
Eli Friedman8339b352009-03-07 03:57:15 +00005247 const llvm::Type* DestTy =
5248 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005249 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5250 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5251 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005252 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005253 return read_weak;
5254}
5255
5256/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5257/// objc_assign_weak (id src, id *dst)
5258///
5259void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5260 llvm::Value *src, llvm::Value *dst)
5261{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005262 const llvm::Type * SrcTy = src->getType();
5263 if (!isa<llvm::PointerType>(SrcTy)) {
5264 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5265 assert(Size <= 8 && "does not support size > 8");
5266 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5267 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005268 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5269 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005270 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5271 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005272 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005273 src, dst, "weakassign");
5274 return;
5275}
5276
5277/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5278/// objc_assign_global (id src, id *dst)
5279///
5280void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5281 llvm::Value *src, llvm::Value *dst)
5282{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005283 const llvm::Type * SrcTy = src->getType();
5284 if (!isa<llvm::PointerType>(SrcTy)) {
5285 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5286 assert(Size <= 8 && "does not support size > 8");
5287 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5288 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005289 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5290 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005291 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5292 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5293 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5294 src, dst, "globalassign");
5295 return;
5296}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005297
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005298void
5299CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5300 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005301 bool isTry = isa<ObjCAtTryStmt>(S);
5302 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5303 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005304 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005305 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005306 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005307 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5308
5309 // For @synchronized, call objc_sync_enter(sync.expr). The
5310 // evaluation of the expression must occur before we enter the
5311 // @synchronized. We can safely avoid a temp here because jumps into
5312 // @synchronized are illegal & this will dominate uses.
5313 llvm::Value *SyncArg = 0;
5314 if (!isTry) {
5315 SyncArg =
5316 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5317 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005318 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005319 }
5320
5321 // Push an EH context entry, used for handling rethrows and jumps
5322 // through finally.
5323 CGF.PushCleanupBlock(FinallyBlock);
5324
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005325 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005326
5327 CGF.EmitBlock(TryBlock);
5328 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5329 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5330 CGF.EmitBranchThroughCleanup(FinallyEnd);
5331
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005332 // Emit the exception handler.
5333
5334 CGF.EmitBlock(TryHandler);
5335
5336 llvm::Value *llvm_eh_exception =
5337 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5338 llvm::Value *llvm_eh_selector_i64 =
5339 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5340 llvm::Value *llvm_eh_typeid_for_i64 =
5341 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5342 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5343 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5344
5345 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5346 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005347 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005348
5349 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005350 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005351 bool HasCatchAll = false;
5352 if (isTry) {
5353 if (const ObjCAtCatchStmt* CatchStmt =
5354 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5355 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005356 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005357 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005358
5359 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005360 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005361 // Use i8* null here to signal this is a catch all, not a cleanup.
5362 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5363 SelectorArgs.push_back(Null);
5364 HasCatchAll = true;
5365 break;
5366 }
5367
Daniel Dunbarede8de92009-03-06 00:01:21 +00005368 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5369 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005370 llvm::Value *IDEHType =
5371 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5372 if (!IDEHType)
5373 IDEHType =
5374 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5375 llvm::GlobalValue::ExternalLinkage,
5376 0, "OBJC_EHTYPE_id", &CGM.getModule());
5377 SelectorArgs.push_back(IDEHType);
5378 HasCatchAll = true;
5379 break;
5380 }
5381
5382 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005383 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005384 assert(PT && "Invalid @catch type.");
5385 const ObjCInterfaceType *IT =
5386 PT->getPointeeType()->getAsObjCInterfaceType();
5387 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005388 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005389 SelectorArgs.push_back(EHType);
5390 }
5391 }
5392 }
5393
5394 // We use a cleanup unless there was already a catch all.
5395 if (!HasCatchAll) {
5396 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005397 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005398 }
5399
5400 llvm::Value *Selector =
5401 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5402 SelectorArgs.begin(), SelectorArgs.end(),
5403 "selector");
5404 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005405 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005406 const Stmt *CatchBody = Handlers[i].second;
5407
5408 llvm::BasicBlock *Next = 0;
5409
5410 // The last handler always matches.
5411 if (i + 1 != e) {
5412 assert(CatchParam && "Only last handler can be a catch all.");
5413
5414 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5415 Next = CGF.createBasicBlock("catch.next");
5416 llvm::Value *Id =
5417 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5418 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5419 ObjCTypes.Int8PtrTy));
5420 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5421 Match, Next);
5422
5423 CGF.EmitBlock(Match);
5424 }
5425
5426 if (CatchBody) {
5427 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5428 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5429
5430 // Cleanups must call objc_end_catch.
5431 //
5432 // FIXME: It seems incorrect for objc_begin_catch to be inside
5433 // this context, but this matches gcc.
5434 CGF.PushCleanupBlock(MatchEnd);
5435 CGF.setInvokeDest(MatchHandler);
5436
5437 llvm::Value *ExcObject =
5438 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5439
5440 // Bind the catch parameter if it exists.
5441 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005442 ExcObject =
5443 CGF.Builder.CreateBitCast(ExcObject,
5444 CGF.ConvertType(CatchParam->getType()));
5445 // CatchParam is a ParmVarDecl because of the grammar
5446 // construction used to handle this, but for codegen purposes
5447 // we treat this as a local decl.
5448 CGF.EmitLocalBlockVarDecl(*CatchParam);
5449 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005450 }
5451
5452 CGF.ObjCEHValueStack.push_back(ExcObject);
5453 CGF.EmitStmt(CatchBody);
5454 CGF.ObjCEHValueStack.pop_back();
5455
5456 CGF.EmitBranchThroughCleanup(FinallyEnd);
5457
5458 CGF.EmitBlock(MatchHandler);
5459
5460 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5461 // We are required to emit this call to satisfy LLVM, even
5462 // though we don't use the result.
5463 llvm::SmallVector<llvm::Value*, 8> Args;
5464 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005465 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005466 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5467 0));
5468 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5469 CGF.Builder.CreateStore(Exc, RethrowPtr);
5470 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5471
5472 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5473
5474 CGF.EmitBlock(MatchEnd);
5475
5476 // Unfortunately, we also have to generate another EH frame here
5477 // in case this throws.
5478 llvm::BasicBlock *MatchEndHandler =
5479 CGF.createBasicBlock("match.end.handler");
5480 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5481 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5482 Cont, MatchEndHandler,
5483 Args.begin(), Args.begin());
5484
5485 CGF.EmitBlock(Cont);
5486 if (Info.SwitchBlock)
5487 CGF.EmitBlock(Info.SwitchBlock);
5488 if (Info.EndBlock)
5489 CGF.EmitBlock(Info.EndBlock);
5490
5491 CGF.EmitBlock(MatchEndHandler);
5492 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5493 // We are required to emit this call to satisfy LLVM, even
5494 // though we don't use the result.
5495 Args.clear();
5496 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005497 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005498 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5499 0));
5500 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5501 CGF.Builder.CreateStore(Exc, RethrowPtr);
5502 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5503
5504 if (Next)
5505 CGF.EmitBlock(Next);
5506 } else {
5507 assert(!Next && "catchup should be last handler.");
5508
5509 CGF.Builder.CreateStore(Exc, RethrowPtr);
5510 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5511 }
5512 }
5513
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005514 // Pop the cleanup entry, the @finally is outside this cleanup
5515 // scope.
5516 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5517 CGF.setInvokeDest(PrevLandingPad);
5518
5519 CGF.EmitBlock(FinallyBlock);
5520
5521 if (isTry) {
5522 if (const ObjCAtFinallyStmt* FinallyStmt =
5523 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5524 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5525 } else {
5526 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5527 // @synchronized.
5528 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005529 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005530
5531 if (Info.SwitchBlock)
5532 CGF.EmitBlock(Info.SwitchBlock);
5533 if (Info.EndBlock)
5534 CGF.EmitBlock(Info.EndBlock);
5535
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005536 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005537 CGF.EmitBranch(FinallyEnd);
5538
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005539 CGF.EmitBlock(FinallyRethrow);
5540 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5541 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005542 CGF.Builder.CreateUnreachable();
5543
5544 CGF.EmitBlock(FinallyEnd);
5545}
5546
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005547/// EmitThrowStmt - Generate code for a throw statement.
5548void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5549 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005550 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005551 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005552 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005553 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005554 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5555 "Unexpected rethrow outside @catch block.");
5556 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005557 }
5558
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005559 llvm::Value *ExceptionAsObject =
5560 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5561 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5562 if (InvokeDest) {
5563 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5564 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5565 Cont, InvokeDest,
5566 &ExceptionAsObject, &ExceptionAsObject + 1);
5567 CGF.EmitBlock(Cont);
5568 } else
5569 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5570 CGF.Builder.CreateUnreachable();
5571
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005572 // Clear the insertion point to indicate we are in unreachable code.
5573 CGF.Builder.ClearInsertionPoint();
5574}
Daniel Dunbare588b992009-03-01 04:46:24 +00005575
5576llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005577CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5578 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005579 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005580
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005581 // If we don't need a definition, return the entry if found or check
5582 // if we use an external reference.
5583 if (!ForDefinition) {
5584 if (Entry)
5585 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005586
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005587 // If this type (or a super class) has the __objc_exception__
5588 // attribute, emit an external reference.
5589 if (hasObjCExceptionAttribute(ID))
5590 return Entry =
5591 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5592 llvm::GlobalValue::ExternalLinkage,
5593 0,
5594 (std::string("OBJC_EHTYPE_$_") +
5595 ID->getIdentifier()->getName()),
5596 &CGM.getModule());
5597 }
5598
5599 // Otherwise we need to either make a new entry or fill in the
5600 // initializer.
5601 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005602 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005603 std::string VTableName = "objc_ehtype_vtable";
5604 llvm::GlobalVariable *VTableGV =
5605 CGM.getModule().getGlobalVariable(VTableName);
5606 if (!VTableGV)
5607 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5608 llvm::GlobalValue::ExternalLinkage,
5609 0, VTableName, &CGM.getModule());
5610
5611 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5612
5613 std::vector<llvm::Constant*> Values(3);
5614 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5615 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005616 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005617 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5618
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005619 if (Entry) {
5620 Entry->setInitializer(Init);
5621 } else {
5622 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5623 llvm::GlobalValue::WeakAnyLinkage,
5624 Init,
5625 (std::string("OBJC_EHTYPE_$_") +
5626 ID->getIdentifier()->getName()),
5627 &CGM.getModule());
5628 }
5629
Daniel Dunbar04d40782009-04-14 06:00:08 +00005630 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005631 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005632 Entry->setAlignment(8);
5633
5634 if (ForDefinition) {
5635 Entry->setSection("__DATA,__objc_const");
5636 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5637 } else {
5638 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5639 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005640
5641 return Entry;
5642}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005643
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005644/* *** */
5645
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005646CodeGen::CGObjCRuntime *
5647CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005648 return new CGObjCMac(CGM);
5649}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005650
5651CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005652CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005653 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005654}