blob: 3a35ea4125af7c32e92fe07f08bdd70fa9fbb10c [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 Dunbardbc933702008-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 Dunbardbc933702008-08-21 21:57:41 +00001141 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001142 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-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 Dunbardbc933702008-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 Dunbardbc933702008-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 Dunbardbc933702008-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 Dunbardbc933702008-08-21 21:57:41 +00001485 Interface->protocol_begin(),
1486 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001487 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001488 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001489 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001490 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001491
1492 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001493 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001494 Flags |= eClassFlags_Hidden;
1495
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001496 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1497 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1498 e = ID->instmeth_end(); i != e; ++i) {
1499 // Instance methods should always be defined.
1500 InstanceMethods.push_back(GetMethodConstant(*i));
1501 }
1502 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1503 e = ID->classmeth_end(); i != e; ++i) {
1504 // Class methods should always be defined.
1505 ClassMethods.push_back(GetMethodConstant(*i));
1506 }
1507
1508 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1509 e = ID->propimpl_end(); i != e; ++i) {
1510 ObjCPropertyImplDecl *PID = *i;
1511
1512 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1513 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1514
1515 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1516 if (llvm::Constant *C = GetMethodConstant(MD))
1517 InstanceMethods.push_back(C);
1518 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1519 if (llvm::Constant *C = GetMethodConstant(MD))
1520 InstanceMethods.push_back(C);
1521 }
1522 }
1523
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001524 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001525 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001526 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001527 // Record a reference to the super class.
1528 LazySymbols.insert(Super->getIdentifier());
1529
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001530 Values[ 1] =
1531 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1532 ObjCTypes.ClassPtrTy);
1533 } else {
1534 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1535 }
1536 Values[ 2] = GetClassName(ID->getIdentifier());
1537 // Version is always 0.
1538 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1539 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1540 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001541 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001542 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001543 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001544 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001545 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001546 // cache is always NULL.
1547 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1548 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001549 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001550 // Values[10] = BuildIvarLayout(ID, true);
1551 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001552 Values[11] = EmitClassExtension(ID);
1553 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1554 Values);
1555
1556 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001557 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1558 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001559 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001560 DefinedClasses.push_back(GV);
1561}
1562
1563llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1564 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001565 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001566 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001567 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001568 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001569
Daniel Dunbar04d40782009-04-14 06:00:08 +00001570 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001571 Flags |= eClassFlags_Hidden;
1572
1573 std::vector<llvm::Constant*> Values(12);
1574 // The isa for the metaclass is the root of the hierarchy.
1575 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1576 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1577 Root = Super;
1578 Values[ 0] =
1579 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1580 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001581 // The super class for the metaclass is emitted as the name of the
1582 // super class. The runtime fixes this up to point to the
1583 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001584 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1585 Values[ 1] =
1586 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1587 ObjCTypes.ClassPtrTy);
1588 } else {
1589 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1590 }
1591 Values[ 2] = GetClassName(ID->getIdentifier());
1592 // Version is always 0.
1593 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1594 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1595 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001596 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001597 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001598 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001599 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001600 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001601 // cache is always NULL.
1602 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1603 Values[ 9] = Protocols;
1604 // ivar_layout for metaclass is always NULL.
1605 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1606 // The class extension is always unused for metaclasses.
1607 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1608 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1609 Values);
1610
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001611 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001612 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001613
1614 // Check for a forward reference.
1615 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1616 if (GV) {
1617 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1618 "Forward metaclass reference has incorrect type.");
1619 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1620 GV->setInitializer(Init);
1621 } else {
1622 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1623 llvm::GlobalValue::InternalLinkage,
1624 Init, Name,
1625 &CGM.getModule());
1626 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001627 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001628 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001629 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001630
1631 return GV;
1632}
1633
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001634llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001635 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001636
1637 // FIXME: Should we look these up somewhere other than the
1638 // module. Its a bit silly since we only generate these while
1639 // processing an implementation, so exactly one pointer would work
1640 // if know when we entered/exitted an implementation block.
1641
1642 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001643 // Previously, metaclass with internal linkage may have been defined.
1644 // pass 'true' as 2nd argument so it is returned.
1645 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001646 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1647 "Forward metaclass reference has incorrect type.");
1648 return GV;
1649 } else {
1650 // Generate as an external reference to keep a consistent
1651 // module. This will be patched up when we emit the metaclass.
1652 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1653 llvm::GlobalValue::ExternalLinkage,
1654 0,
1655 Name,
1656 &CGM.getModule());
1657 }
1658}
1659
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001660/*
1661 struct objc_class_ext {
1662 uint32_t size;
1663 const char *weak_ivar_layout;
1664 struct _objc_property_list *properties;
1665 };
1666*/
1667llvm::Constant *
1668CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1669 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001670 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001671
1672 std::vector<llvm::Constant*> Values(3);
1673 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001674 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001675 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001676 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001677 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001678 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001679
1680 // Return null if no extension bits are used.
1681 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1682 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1683
1684 llvm::Constant *Init =
1685 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001686 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001687 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1688 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001689}
1690
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001691/// countInheritedIvars - count number of ivars in class and its super class(s)
1692///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001693static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1694 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001695 int count = 0;
1696 if (!OI)
1697 return 0;
1698 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1699 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001700 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001701 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1702 E = OI->ivar_end(); I != E; ++I)
1703 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001704 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001705 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1706 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001707 if ((*I)->getPropertyIvarDecl())
1708 ++count;
1709 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001710 return count;
1711}
1712
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001713/// getInterfaceDeclForIvar - Get the interface declaration node where
1714/// this ivar is declared in.
1715/// FIXME. Ideally, this info should be in the ivar node. But currently
1716/// it is not and prevailing wisdom is that ASTs should not have more
1717/// info than is absolutely needed, even though this info reflects the
1718/// source language.
1719///
1720static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1721 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001722 const ObjCIvarDecl *IVD,
1723 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001724 if (!OI)
1725 return 0;
1726 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1727 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1728 E = OI->ivar_end(); I != E; ++I)
1729 if ((*I)->getIdentifier() == IVD->getIdentifier())
1730 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001731 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001732 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1733 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001734 ObjCPropertyDecl *PDecl = (*I);
1735 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1736 if (IV->getIdentifier() == IVD->getIdentifier())
1737 return OI;
1738 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001739 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001740}
1741
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001742/*
1743 struct objc_ivar {
1744 char *ivar_name;
1745 char *ivar_type;
1746 int ivar_offset;
1747 };
1748
1749 struct objc_ivar_list {
1750 int ivar_count;
1751 struct objc_ivar list[count];
1752 };
1753 */
1754llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001755 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001756 std::vector<llvm::Constant*> Ivars, Ivar(3);
1757
1758 // When emitting the root class GCC emits ivar entries for the
1759 // actual class structure. It is not clear if we need to follow this
1760 // behavior; for now lets try and get away with not doing it. If so,
1761 // the cleanest solution would be to make up an ObjCInterfaceDecl
1762 // for the class.
1763 if (ForClass)
1764 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001765
1766 ObjCInterfaceDecl *OID =
1767 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001768 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001769
1770 RecordDecl::field_iterator ifield, pfield;
1771 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001772 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
1773 ifield != e; ++ifield) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001774 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001775 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001776 if (Field->getIdentifier())
1777 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1778 else
1779 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001780 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001781 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001782 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001783 }
1784
1785 // Return null for empty list.
1786 if (Ivars.empty())
1787 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1788
1789 std::vector<llvm::Constant*> Values(2);
1790 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1791 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1792 Ivars.size());
1793 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1794 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1795
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001796 llvm::GlobalVariable *GV;
1797 if (ForClass)
1798 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001799 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1800 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001801 else
1802 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1803 + ID->getNameAsString(),
1804 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001805 4, true);
1806 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001807}
1808
1809/*
1810 struct objc_method {
1811 SEL method_name;
1812 char *method_types;
1813 void *method;
1814 };
1815
1816 struct objc_method_list {
1817 struct objc_method_list *obsolete;
1818 int count;
1819 struct objc_method methods_list[count];
1820 };
1821*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001822
1823/// GetMethodConstant - Return a struct objc_method constant for the
1824/// given method if it has been defined. The result is null if the
1825/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001826llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001827 // FIXME: Use DenseMap::lookup
1828 llvm::Function *Fn = MethodDefinitions[MD];
1829 if (!Fn)
1830 return 0;
1831
1832 std::vector<llvm::Constant*> Method(3);
1833 Method[0] =
1834 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1835 ObjCTypes.SelectorPtrTy);
1836 Method[1] = GetMethodVarType(MD);
1837 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1838 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1839}
1840
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001841llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1842 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001843 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001844 // Return null for empty list.
1845 if (Methods.empty())
1846 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1847
1848 std::vector<llvm::Constant*> Values(3);
1849 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1850 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1851 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1852 Methods.size());
1853 Values[2] = llvm::ConstantArray::get(AT, Methods);
1854 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1855
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001856 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001857 return llvm::ConstantExpr::getBitCast(GV,
1858 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001859}
1860
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001861llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001862 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001863 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001864 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001865
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001866 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001867 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001868 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001869 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001870 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001871 llvm::GlobalValue::InternalLinkage,
1872 Name,
1873 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001874 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001875
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001876 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001877}
1878
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001879uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001880 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001881 if (!Field->isBitField())
1882 return Layout->getElementOffset(
1883 CGM.getTypes().getLLVMFieldNo(Field));
1884 // FIXME. Must be a better way of getting a bitfield base offset.
1885 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1886 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1887 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1888 offset = (offset*size)/8;
1889 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001890}
1891
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001892/// GetFieldBaseOffset - return's field byt offset.
1893uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1894 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001895 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001896 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001897 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1898 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001899}
1900
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001901llvm::GlobalVariable *
1902CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1903 llvm::Constant *Init,
1904 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001905 unsigned Align,
1906 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001907 const llvm::Type *Ty = Init->getType();
1908 llvm::GlobalVariable *GV =
1909 new llvm::GlobalVariable(Ty, false,
1910 llvm::GlobalValue::InternalLinkage,
1911 Init,
1912 Name,
1913 &CGM.getModule());
1914 if (Section)
1915 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001916 if (Align)
1917 GV->setAlignment(Align);
1918 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001919 UsedGlobals.push_back(GV);
1920 return GV;
1921}
1922
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001923llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001924 // Abuse this interface function as a place to finalize.
1925 FinishModule();
1926
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001927 return NULL;
1928}
1929
Chris Lattner74391b42009-03-22 21:03:39 +00001930llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001931 return ObjCTypes.GetPropertyFn;
1932}
1933
Chris Lattner74391b42009-03-22 21:03:39 +00001934llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001935 return ObjCTypes.SetPropertyFn;
1936}
1937
Chris Lattner74391b42009-03-22 21:03:39 +00001938llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001939 return ObjCTypes.EnumerationMutationFn;
1940}
1941
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001942/*
1943
1944Objective-C setjmp-longjmp (sjlj) Exception Handling
1945--
1946
1947The basic framework for a @try-catch-finally is as follows:
1948{
1949 objc_exception_data d;
1950 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001951 bool _call_try_exit = true;
1952
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001953 objc_exception_try_enter(&d);
1954 if (!setjmp(d.jmp_buf)) {
1955 ... try body ...
1956 } else {
1957 // exception path
1958 id _caught = objc_exception_extract(&d);
1959
1960 // enter new try scope for handlers
1961 if (!setjmp(d.jmp_buf)) {
1962 ... match exception and execute catch blocks ...
1963
1964 // fell off end, rethrow.
1965 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001966 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001967 } else {
1968 // exception in catch block
1969 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001970 _call_try_exit = false;
1971 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001972 }
1973 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001974 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001975
1976finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001977 if (_call_try_exit)
1978 objc_exception_try_exit(&d);
1979
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001980 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001981 ... dispatch to finally destination ...
1982
1983finally_rethrow:
1984 objc_exception_throw(_rethrow);
1985
1986finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001987}
1988
1989This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001990uses _rethrow to determine if objc_exception_try_exit should be called
1991and if the object should be rethrown. This breaks in the face of
1992throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001993
1994We specialize this framework for a few particular circumstances:
1995
1996 - If there are no catch blocks, then we avoid emitting the second
1997 exception handling context.
1998
1999 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2000 e)) we avoid emitting the code to rethrow an uncaught exception.
2001
2002 - FIXME: If there is no @finally block we can do a few more
2003 simplifications.
2004
2005Rethrows and Jumps-Through-Finally
2006--
2007
2008Support for implicit rethrows and jumping through the finally block is
2009handled by storing the current exception-handling context in
2010ObjCEHStack.
2011
Daniel Dunbar898d5082008-09-30 01:06:03 +00002012In order to implement proper @finally semantics, we support one basic
2013mechanism for jumping through the finally block to an arbitrary
2014destination. Constructs which generate exits from a @try or @catch
2015block use this mechanism to implement the proper semantics by chaining
2016jumps, as necessary.
2017
2018This mechanism works like the one used for indirect goto: we
2019arbitrarily assign an ID to each destination and store the ID for the
2020destination in a variable prior to entering the finally block. At the
2021end of the finally block we simply create a switch to the proper
2022destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002023
2024Code gen for @synchronized(expr) stmt;
2025Effectively generating code for:
2026objc_sync_enter(expr);
2027@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002028*/
2029
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002030void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2031 const Stmt &S) {
2032 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002033 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002034 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002035 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002036 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2037 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2038 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002039
2040 // For @synchronized, call objc_sync_enter(sync.expr). The
2041 // evaluation of the expression must occur before we enter the
2042 // @synchronized. We can safely avoid a temp here because jumps into
2043 // @synchronized are illegal & this will dominate uses.
2044 llvm::Value *SyncArg = 0;
2045 if (!isTry) {
2046 SyncArg =
2047 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2048 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002049 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002050 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002051
2052 // Push an EH context entry, used for handling rethrows and jumps
2053 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002054 CGF.PushCleanupBlock(FinallyBlock);
2055
Anders Carlsson273558f2009-02-07 21:37:21 +00002056 CGF.ObjCEHValueStack.push_back(0);
2057
Daniel Dunbar898d5082008-09-30 01:06:03 +00002058 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002059 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2060 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002061 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2062 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002063 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2064 "_call_try_exit");
2065 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2066
Anders Carlsson80f25672008-09-09 17:59:25 +00002067 // Enter a new try block and call setjmp.
2068 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2069 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2070 "jmpbufarray");
2071 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2072 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2073 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002074
Daniel Dunbar55e87422008-11-11 02:29:29 +00002075 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2076 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002077 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002078 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002079
2080 // Emit the @try block.
2081 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002082 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2083 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002084 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002085
2086 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002087 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002088
2089 // Retrieve the exception object. We may emit multiple blocks but
2090 // nothing can cross this so the value is already in SSA form.
2091 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2092 ExceptionData,
2093 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002094 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002095 if (!isTry)
2096 {
2097 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002098 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002099 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002100 }
2101 else if (const ObjCAtCatchStmt* CatchStmt =
2102 cast<ObjCAtTryStmt>(S).getCatchStmts())
2103 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002104 // Enter a new exception try block (in case a @catch block throws
2105 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002106 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002107
Anders Carlsson80f25672008-09-09 17:59:25 +00002108 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2109 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002110 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002111
Daniel Dunbar55e87422008-11-11 02:29:29 +00002112 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2113 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002114 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002115
2116 CGF.EmitBlock(CatchBlock);
2117
Daniel Dunbar55e40722008-09-27 07:03:52 +00002118 // Handle catch list. As a special case we check if everything is
2119 // matched and avoid generating code for falling off the end if
2120 // so.
2121 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002122 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002123 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002124
Steve Naroff7ba138a2009-03-03 19:52:17 +00002125 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002126 const PointerType *PT = 0;
2127
Anders Carlsson80f25672008-09-09 17:59:25 +00002128 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002129 if (!CatchParam) {
2130 AllMatched = true;
2131 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002132 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002133
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002134 // catch(id e) always matches.
2135 // FIXME: For the time being we also match id<X>; this should
2136 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002137 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002138 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002139 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002140 }
2141
Daniel Dunbar55e40722008-09-27 07:03:52 +00002142 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002143 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002144 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002145 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002146 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002147 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002148
Anders Carlssondde0a942008-09-11 09:15:33 +00002149 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002150 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002151 break;
2152 }
2153
Daniel Dunbar129271a2008-09-27 07:36:24 +00002154 assert(PT && "Unexpected non-pointer type in @catch");
2155 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002156 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002157 assert(ObjCType && "Catch parameter must have Objective-C type!");
2158
2159 // Check if the @catch block matches the exception object.
2160 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2161
Anders Carlsson80f25672008-09-09 17:59:25 +00002162 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2163 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002164
Daniel Dunbar55e87422008-11-11 02:29:29 +00002165 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002166
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002167 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002168 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002169
2170 // Emit the @catch block.
2171 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002172 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002173 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002174
2175 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002176 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002177 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002178 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002179
2180 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002181 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002182
2183 CGF.EmitBlock(NextCatchBlock);
2184 }
2185
Daniel Dunbar55e40722008-09-27 07:03:52 +00002186 if (!AllMatched) {
2187 // None of the handlers caught the exception, so store it to be
2188 // rethrown at the end of the @finally block.
2189 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002190 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002191 }
2192
2193 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002194 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002195 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2196 ExceptionData),
2197 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002198 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002199 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002200 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002201 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002202 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002203 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002204 }
2205
Daniel Dunbar898d5082008-09-30 01:06:03 +00002206 // Pop the exception-handling stack entry. It is important to do
2207 // this now, because the code in the @finally block is not in this
2208 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002209 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2210
Anders Carlsson273558f2009-02-07 21:37:21 +00002211 CGF.ObjCEHValueStack.pop_back();
2212
Anders Carlsson80f25672008-09-09 17:59:25 +00002213 // Emit the @finally block.
2214 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002215 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2216
2217 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2218
2219 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002220 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002221
2222 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002223 if (isTry) {
2224 if (const ObjCAtFinallyStmt* FinallyStmt =
2225 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2226 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002227 } else {
2228 // Emit objc_sync_exit(expr); as finally's sole statement for
2229 // @synchronized.
2230 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002231 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002232
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002233 // Emit the switch block
2234 if (Info.SwitchBlock)
2235 CGF.EmitBlock(Info.SwitchBlock);
2236 if (Info.EndBlock)
2237 CGF.EmitBlock(Info.EndBlock);
2238
Daniel Dunbar898d5082008-09-30 01:06:03 +00002239 CGF.EmitBlock(FinallyRethrow);
2240 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2241 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002242 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002243
2244 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002245}
2246
2247void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002248 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002249 llvm::Value *ExceptionAsObject;
2250
2251 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2252 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2253 ExceptionAsObject =
2254 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2255 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002256 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002257 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002258 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002259 }
2260
2261 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002262 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002263
2264 // Clear the insertion point to indicate we are in unreachable code.
2265 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002266}
2267
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002268/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002269/// object: objc_read_weak (id *src)
2270///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002271llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002272 llvm::Value *AddrWeakObj)
2273{
Eli Friedman8339b352009-03-07 03:57:15 +00002274 const llvm::Type* DestTy =
2275 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002276 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002277 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002278 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002279 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002280 return read_weak;
2281}
2282
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002283/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2284/// objc_assign_weak (id src, id *dst)
2285///
2286void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2287 llvm::Value *src, llvm::Value *dst)
2288{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002289 const llvm::Type * SrcTy = src->getType();
2290 if (!isa<llvm::PointerType>(SrcTy)) {
2291 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2292 assert(Size <= 8 && "does not support size > 8");
2293 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2294 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002295 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2296 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002297 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2298 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002299 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002300 src, dst, "weakassign");
2301 return;
2302}
2303
Fariborz Jahanian58626502008-11-19 00:59:10 +00002304/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2305/// objc_assign_global (id src, id *dst)
2306///
2307void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2308 llvm::Value *src, llvm::Value *dst)
2309{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002310 const llvm::Type * SrcTy = src->getType();
2311 if (!isa<llvm::PointerType>(SrcTy)) {
2312 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2313 assert(Size <= 8 && "does not support size > 8");
2314 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2315 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002316 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2317 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002318 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2319 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002320 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2321 src, dst, "globalassign");
2322 return;
2323}
2324
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002325/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2326/// objc_assign_ivar (id src, id *dst)
2327///
2328void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2329 llvm::Value *src, llvm::Value *dst)
2330{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002331 const llvm::Type * SrcTy = src->getType();
2332 if (!isa<llvm::PointerType>(SrcTy)) {
2333 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2334 assert(Size <= 8 && "does not support size > 8");
2335 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2336 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002337 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2338 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002339 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2340 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2341 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2342 src, dst, "assignivar");
2343 return;
2344}
2345
Fariborz Jahanian58626502008-11-19 00:59:10 +00002346/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2347/// objc_assign_strongCast (id src, id *dst)
2348///
2349void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2350 llvm::Value *src, llvm::Value *dst)
2351{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002352 const llvm::Type * SrcTy = src->getType();
2353 if (!isa<llvm::PointerType>(SrcTy)) {
2354 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2355 assert(Size <= 8 && "does not support size > 8");
2356 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2357 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002358 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2359 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002360 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2361 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002362 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2363 src, dst, "weakassign");
2364 return;
2365}
2366
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002367/// EmitObjCValueForIvar - Code Gen for ivar reference.
2368///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002369LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2370 QualType ObjectTy,
2371 llvm::Value *BaseValue,
2372 const ObjCIvarDecl *Ivar,
2373 const FieldDecl *Field,
2374 unsigned CVRQualifiers) {
2375 if (Ivar->isBitField())
2376 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2377 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002378 // TODO: Add a special case for isa (index 0)
2379 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2380 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002381 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002382 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2383 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002384 LValue::SetObjCIvar(LV, true);
2385 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002386}
2387
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002388llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2389 ObjCInterfaceDecl *Interface,
2390 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002391 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002392 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002393 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002394 return llvm::ConstantInt::get(
2395 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2396 Offset);
2397}
2398
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002399/* *** Private Interface *** */
2400
2401/// EmitImageInfo - Emit the image info marker used to encode some module
2402/// level information.
2403///
2404/// See: <rdr://4810609&4810587&4810587>
2405/// struct IMAGE_INFO {
2406/// unsigned version;
2407/// unsigned flags;
2408/// };
2409enum ImageInfoFlags {
2410 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2411 eImageInfo_GarbageCollected = (1 << 1),
2412 eImageInfo_GCOnly = (1 << 2)
2413};
2414
2415void CGObjCMac::EmitImageInfo() {
2416 unsigned version = 0; // Version is unused?
2417 unsigned flags = 0;
2418
2419 // FIXME: Fix and continue?
2420 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2421 flags |= eImageInfo_GarbageCollected;
2422 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2423 flags |= eImageInfo_GCOnly;
2424
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002425 // Emitted as int[2];
2426 llvm::Constant *values[2] = {
2427 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2428 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2429 };
2430 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002431
2432 const char *Section;
2433 if (ObjCABI == 1)
2434 Section = "__OBJC, __image_info,regular";
2435 else
2436 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002437 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002438 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2439 llvm::ConstantArray::get(AT, values, 2),
2440 Section,
2441 0,
2442 true);
2443 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002444}
2445
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002446
2447// struct objc_module {
2448// unsigned long version;
2449// unsigned long size;
2450// const char *name;
2451// Symtab symtab;
2452// };
2453
2454// FIXME: Get from somewhere
2455static const int ModuleVersion = 7;
2456
2457void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002458 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002459
2460 std::vector<llvm::Constant*> Values(4);
2461 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2462 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002463 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002464 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002465 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002466 CreateMetadataVar("\01L_OBJC_MODULES",
2467 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2468 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002469 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002470}
2471
2472llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002473 unsigned NumClasses = DefinedClasses.size();
2474 unsigned NumCategories = DefinedCategories.size();
2475
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002476 // Return null if no symbols were defined.
2477 if (!NumClasses && !NumCategories)
2478 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2479
2480 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002481 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2482 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2483 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2484 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2485
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002486 // The runtime expects exactly the list of defined classes followed
2487 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002488 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002489 for (unsigned i=0; i<NumClasses; i++)
2490 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2491 ObjCTypes.Int8PtrTy);
2492 for (unsigned i=0; i<NumCategories; i++)
2493 Symbols[NumClasses + i] =
2494 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2495 ObjCTypes.Int8PtrTy);
2496
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002497 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002498 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002499 NumClasses + NumCategories),
2500 Symbols);
2501
2502 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2503
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002504 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002505 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2506 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002507 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002508 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2509}
2510
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002511llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002512 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002513 LazySymbols.insert(ID->getIdentifier());
2514
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002515 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2516
2517 if (!Entry) {
2518 llvm::Constant *Casted =
2519 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2520 ObjCTypes.ClassPtrTy);
2521 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002522 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2523 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002524 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002525 }
2526
2527 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002528}
2529
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002530llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002531 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2532
2533 if (!Entry) {
2534 llvm::Constant *Casted =
2535 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2536 ObjCTypes.SelectorPtrTy);
2537 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002538 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2539 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002540 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002541 }
2542
2543 return Builder.CreateLoad(Entry, false, "tmp");
2544}
2545
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002546llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002547 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002548
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002549 if (!Entry)
2550 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2551 llvm::ConstantArray::get(Ident->getName()),
2552 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002553 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002554
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002555 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002556}
2557
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002558/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2559/// interface declaration.
2560const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2561 const ObjCInterfaceDecl *OID) const {
2562 const llvm::Type *InterfaceTy =
2563 CGM.getTypes().ConvertType(
2564 CGM.getContext().getObjCInterfaceType(
2565 const_cast<ObjCInterfaceDecl*>(OID)));
2566 const llvm::StructLayout *Layout =
2567 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2568 return Layout;
2569}
2570
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002571/// GetIvarLayoutName - Returns a unique constant for the given
2572/// ivar layout bitmap.
2573llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2574 const ObjCCommonTypesHelper &ObjCTypes) {
2575 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2576}
2577
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002578void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2579 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002580 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002581 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002582 unsigned int BytePos, bool ForStrongLayout,
2583 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002584 bool IsUnion = (RD && RD->isUnion());
2585 uint64_t MaxUnionIvarSize = 0;
2586 uint64_t MaxSkippedUnionIvarSize = 0;
2587 FieldDecl *MaxField = 0;
2588 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002589 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002590 if (RecFields.empty())
2591 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002592 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002593 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002594 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2595 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2596
2597 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2598
2599 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002600 FieldDecl *Field = RecFields[i];
2601 // Skip over unnamed or bitfields
2602 if (!Field->getIdentifier() || Field->isBitField())
2603 continue;
2604 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002605 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002606 if (FQT->isUnionType())
2607 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002608 else
2609 assert(FQT->isRecordType() &&
2610 "only union/record is supported for ivar layout bitmap");
2611
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002612 const RecordType *RT = FQT->getAsRecordType();
2613 const RecordDecl *RD = RT->getDecl();
2614 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002615 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2616 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002617 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002618 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002619 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002620 ForStrongLayout, Index, SkIndex,
2621 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002622 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002623 continue;
2624 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002625
2626 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002627 const ConstantArrayType *CArray =
2628 dyn_cast_or_null<ConstantArrayType>(Array);
2629 assert(CArray && "only array with know element size is supported");
2630 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002631 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2632 const ConstantArrayType *CArray =
2633 dyn_cast_or_null<ConstantArrayType>(Array);
2634 FQT = CArray->getElementType();
2635 }
2636
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002637 assert(!FQT->isUnionType() &&
2638 "layout for array of unions not supported");
2639 if (FQT->isRecordType()) {
2640 uint64_t ElCount = CArray->getSize().getZExtValue();
2641 int OldIndex = Index;
2642 int OldSkIndex = SkIndex;
2643
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002644 // FIXME - Use a common routine with the above!
2645 const RecordType *RT = FQT->getAsRecordType();
2646 const RecordDecl *RD = RT->getDecl();
2647 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002648 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2649 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002650
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002651 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002652 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002653 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002654 ForStrongLayout, Index, SkIndex,
2655 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002656 TmpRecFields.clear();
2657
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002658 // Replicate layout information for each array element. Note that
2659 // one element is already done.
2660 uint64_t ElIx = 1;
2661 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2662 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002663 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002664 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2665 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002666 GC_IVAR gcivar;
2667 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2668 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2669 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002670 }
2671
Chris Lattnerf1690852009-03-31 08:48:01 +00002672 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002673 GC_IVAR skivar;
2674 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2675 skivar.ivar_size = SkipIvars[i].ivar_size;
2676 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002677 }
2678 }
2679 continue;
2680 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002681 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002682 // At this point, we are done with Record/Union and array there of.
2683 // For other arrays we are down to its element type.
2684 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2685 do {
2686 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2687 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2688 break;
2689 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002690 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002691 GCAttr = QualType::Strong;
2692 break;
2693 }
2694 else if (const PointerType *PT = FQT->getAsPointerType()) {
2695 FQT = PT->getPointeeType();
2696 }
2697 else {
2698 break;
2699 }
2700 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002701
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002702 if ((ForStrongLayout && GCAttr == QualType::Strong)
2703 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2704 if (IsUnion)
2705 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002706 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2707 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002708 if (UnionIvarSize > MaxUnionIvarSize)
2709 {
2710 MaxUnionIvarSize = UnionIvarSize;
2711 MaxField = Field;
2712 }
2713 }
2714 else
2715 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002716 GC_IVAR gcivar;
2717 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2718 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2719 WordSizeInBits;
2720 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002721 }
2722 }
2723 else if ((ForStrongLayout &&
2724 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2725 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2726 if (IsUnion)
2727 {
2728 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2729 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2730 {
2731 MaxSkippedUnionIvarSize = UnionIvarSize;
2732 MaxSkippedField = Field;
2733 }
2734 }
2735 else
2736 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002737 GC_IVAR skivar;
2738 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2739 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2740 WordSizeInBits;
2741 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002742 }
2743 }
2744 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002745 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002746 GC_IVAR gcivar;
2747 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2748 gcivar.ivar_size = MaxUnionIvarSize;
2749 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002750 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002751
2752 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002753 GC_IVAR skivar;
2754 skivar.ivar_bytepos = BytePos +
2755 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2756 skivar.ivar_size = MaxSkippedUnionIvarSize;
2757 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002758 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002759}
2760
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002761static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002762IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002763{
2764 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2765 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2766
2767 if (sa < sb)
2768 return -1;
2769 if (sa > sb)
2770 return 1;
2771 return 0;
2772}
2773
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002774/// BuildIvarLayout - Builds ivar layout bitmap for the class
2775/// implementation for the __strong or __weak case.
2776/// The layout map displays which words in ivar list must be skipped
2777/// and which must be scanned by GC (see below). String is built of bytes.
2778/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2779/// of words to skip and right nibble is count of words to scan. So, each
2780/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2781/// represented by a 0x00 byte which also ends the string.
2782/// 1. when ForStrongLayout is true, following ivars are scanned:
2783/// - id, Class
2784/// - object *
2785/// - __strong anything
2786///
2787/// 2. When ForStrongLayout is false, following ivars are scanned:
2788/// - __weak anything
2789///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002790llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002791 const ObjCImplementationDecl *OMD,
2792 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002793 int Index = -1;
2794 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002795 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002796 int SkipScan;
2797 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002798 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2799 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2800 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002801
Chris Lattnerf1690852009-03-31 08:48:01 +00002802 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002803 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002804 CGM.getContext().CollectObjCIvars(OI, RecFields);
2805 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002806 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002807
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002808 SkipIvars.clear();
2809 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002810
2811 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002812 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2813 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002814 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002815 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002816
2817 // Sort on byte position in case we encounterred a union nested in
2818 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002819 if (hasUnion && !IvarsInfo.empty())
2820 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2821 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002822 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2823
2824 // Build the string of skip/scan nibbles
2825 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002826 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002827 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002828 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002829 if (IvarsInfo[0].ivar_bytepos == 0) {
2830 WordsToSkip = 0;
2831 WordsToScan = IvarsInfo[0].ivar_size;
2832 }
2833 else {
2834 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2835 WordsToScan = IvarsInfo[0].ivar_size;
2836 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002837 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002838 {
2839 unsigned int TailPrevGCObjC =
2840 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2841 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2842 {
2843 // consecutive 'scanned' object pointers.
2844 WordsToScan += IvarsInfo[i].ivar_size;
2845 }
2846 else
2847 {
2848 // Skip over 'gc'able object pointer which lay over each other.
2849 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2850 continue;
2851 // Must skip over 1 or more words. We save current skip/scan values
2852 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002853 SKIP_SCAN SkScan;
2854 SkScan.skip = WordsToSkip;
2855 SkScan.scan = WordsToScan;
2856 SkipScanIvars.push_back(SkScan); ++SkipScan;
2857
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002858 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002859 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2860 SkScan.scan = 0;
2861 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002862 WordsToSkip = 0;
2863 WordsToScan = IvarsInfo[i].ivar_size;
2864 }
2865 }
2866 if (WordsToScan > 0)
2867 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002868 SKIP_SCAN SkScan;
2869 SkScan.skip = WordsToSkip;
2870 SkScan.scan = WordsToScan;
2871 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002872 }
2873
2874 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002875 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002876 {
2877 int LastByteSkipped =
2878 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2879 int LastByteScanned =
2880 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2881 BytesSkipped = (LastByteSkipped > LastByteScanned);
2882 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2883 if (BytesSkipped)
2884 {
2885 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002886 SKIP_SCAN SkScan;
2887 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2888 SkScan.scan = 0;
2889 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002890 }
2891 }
2892 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2893 // as 0xMN.
2894 for (int i = 0; i <= SkipScan; i++)
2895 {
2896 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2897 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2898 // 0xM0 followed by 0x0N detected.
2899 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2900 for (int j = i+1; j < SkipScan; j++)
2901 SkipScanIvars[j] = SkipScanIvars[j+1];
2902 --SkipScan;
2903 }
2904 }
2905
2906 // Generate the string.
2907 std::string BitMap;
2908 for (int i = 0; i <= SkipScan; i++)
2909 {
2910 unsigned char byte;
2911 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2912 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2913 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2914 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2915
2916 if (skip_small > 0 || skip_big > 0)
2917 BytesSkipped = true;
2918 // first skip big.
2919 for (unsigned int ix = 0; ix < skip_big; ix++)
2920 BitMap += (unsigned char)(0xf0);
2921
2922 // next (skip small, scan)
2923 if (skip_small)
2924 {
2925 byte = skip_small << 4;
2926 if (scan_big > 0)
2927 {
2928 byte |= 0xf;
2929 --scan_big;
2930 }
2931 else if (scan_small)
2932 {
2933 byte |= scan_small;
2934 scan_small = 0;
2935 }
2936 BitMap += byte;
2937 }
2938 // next scan big
2939 for (unsigned int ix = 0; ix < scan_big; ix++)
2940 BitMap += (unsigned char)(0x0f);
2941 // last scan small
2942 if (scan_small)
2943 {
2944 byte = scan_small;
2945 BitMap += byte;
2946 }
2947 }
2948 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002949 unsigned char zero = 0;
2950 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002951 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2952 // final layout.
2953 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002954 return llvm::Constant::getNullValue(PtrTy);
2955 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2956 llvm::ConstantArray::get(BitMap.c_str()),
2957 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002958 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002959 // FIXME. Need a commomand-line option for this eventually.
2960 if (ForStrongLayout)
2961 printf("\nstrong ivar layout: ");
2962 else
2963 printf("\nweak ivar layout: ");
2964 const unsigned char *s = (unsigned char*)BitMap.c_str();
2965 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002966 if (!(s[i] & 0xf0))
2967 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2968 else
2969 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002970 printf("\n");
2971
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002972 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002973}
2974
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002975llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002976 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2977
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002978 // FIXME: Avoid std::string copying.
2979 if (!Entry)
2980 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2981 llvm::ConstantArray::get(Sel.getAsString()),
2982 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002983 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002984
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002985 return getConstantGEP(Entry, 0, 0);
2986}
2987
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002988// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002989llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002990 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2991}
2992
2993// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002994llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002995 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2996}
2997
Devang Patel7794bb82009-03-04 18:21:39 +00002998llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2999 std::string TypeStr;
3000 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3001
3002 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003003
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003004 if (!Entry)
3005 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3006 llvm::ConstantArray::get(TypeStr),
3007 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003008 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003009
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003010 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003011}
3012
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003013llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003014 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003015 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3016 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003017
3018 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3019
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003020 if (!Entry)
3021 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3022 llvm::ConstantArray::get(TypeStr),
3023 "__TEXT,__cstring,cstring_literals",
3024 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003025
3026 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003027}
3028
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003029// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003030llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003031 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3032
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003033 if (!Entry)
3034 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3035 llvm::ConstantArray::get(Ident->getName()),
3036 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003037 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003038
3039 return getConstantGEP(Entry, 0, 0);
3040}
3041
3042// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003043// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003044llvm::Constant *
3045 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3046 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003047 std::string TypeStr;
3048 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003049 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3050}
3051
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003052void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3053 const ObjCContainerDecl *CD,
3054 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003055 NameOut = '\01';
3056 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003057 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003058 assert (CD && "Missing container decl in GetNameForMethod");
3059 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003060 if (const ObjCCategoryImplDecl *CID =
3061 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3062 NameOut += '(';
3063 NameOut += CID->getNameAsString();
3064 NameOut+= ')';
3065 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003066 NameOut += ' ';
3067 NameOut += D->getSelector().getAsString();
3068 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003069}
3070
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003071/// GetFirstIvarInRecord - This routine returns the record for the
3072/// implementation of the fiven class OID. It also returns field
3073/// corresponding to the first ivar in the class in FIV. It also
3074/// returns the one before the first ivar.
3075///
3076const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3077 const ObjCInterfaceDecl *OID,
3078 RecordDecl::field_iterator &FIV,
3079 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003080 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3081 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003082 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003083 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3084 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003085 while (countSuperClassIvars-- > 0) {
3086 pfield = ifield;
3087 ++ifield;
3088 }
3089 FIV = ifield;
3090 PIV = pfield;
3091 return RD;
3092}
3093
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003094void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003095 EmitModuleInfo();
3096
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003097 // Emit the dummy bodies for any protocols which were referenced but
3098 // never defined.
3099 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3100 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3101 if (i->second->hasInitializer())
3102 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003103
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003104 std::vector<llvm::Constant*> Values(5);
3105 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3106 Values[1] = GetClassName(i->first);
3107 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3108 Values[3] = Values[4] =
3109 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3110 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3111 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3112 Values));
3113 }
3114
3115 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003116 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003117 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003118 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003119 }
3120
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003121 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003122 llvm::GlobalValue *GV =
3123 new llvm::GlobalVariable(AT, false,
3124 llvm::GlobalValue::AppendingLinkage,
3125 llvm::ConstantArray::get(AT, Used),
3126 "llvm.used",
3127 &CGM.getModule());
3128
3129 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003130
3131 // Add assembler directives to add lazy undefined symbol references
3132 // for classes which are referenced but not defined. This is
3133 // important for correct linker interaction.
3134
3135 // FIXME: Uh, this isn't particularly portable.
3136 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003137
3138 if (!CGM.getModule().getModuleInlineAsm().empty())
3139 s << "\n";
3140
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003141 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3142 e = LazySymbols.end(); i != e; ++i) {
3143 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3144 }
3145 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3146 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003147 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003148 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3149 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003150
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003151 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003152}
3153
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003154CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003155 : CGObjCCommonMac(cgm),
3156 ObjCTypes(cgm)
3157{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003158 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003159 ObjCABI = 2;
3160}
3161
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003162/* *** */
3163
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003164ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3165: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003166{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003167 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3168 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003169
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003170 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003171 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003172 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003173 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003174 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3175
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003176 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003177 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003178 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003179
3180 // FIXME: It would be nice to unify this with the opaque type, so
3181 // that the IR comes out a bit cleaner.
3182 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3183 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003184
3185 // I'm not sure I like this. The implicit coordination is a bit
3186 // gross. We should solve this in a reasonable fashion because this
3187 // is a pretty common task (match some runtime data structure with
3188 // an LLVM data structure).
3189
3190 // FIXME: This is leaked.
3191 // FIXME: Merge with rewriter code?
3192
3193 // struct _objc_super {
3194 // id self;
3195 // Class cls;
3196 // }
3197 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3198 SourceLocation(),
3199 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003200 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3201 Ctx.getObjCIdType(), 0, false));
3202 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3203 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003204 RD->completeDefinition(Ctx);
3205
3206 SuperCTy = Ctx.getTagDeclType(RD);
3207 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3208
3209 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003210 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3211
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003212 // struct _prop_t {
3213 // char *name;
3214 // char *attributes;
3215 // }
3216 PropertyTy = llvm::StructType::get(Int8PtrTy,
3217 Int8PtrTy,
3218 NULL);
3219 CGM.getModule().addTypeName("struct._prop_t",
3220 PropertyTy);
3221
3222 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003223 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003224 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003225 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003226 // }
3227 PropertyListTy = llvm::StructType::get(IntTy,
3228 IntTy,
3229 llvm::ArrayType::get(PropertyTy, 0),
3230 NULL);
3231 CGM.getModule().addTypeName("struct._prop_list_t",
3232 PropertyListTy);
3233 // struct _prop_list_t *
3234 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3235
3236 // struct _objc_method {
3237 // SEL _cmd;
3238 // char *method_type;
3239 // char *_imp;
3240 // }
3241 MethodTy = llvm::StructType::get(SelectorPtrTy,
3242 Int8PtrTy,
3243 Int8PtrTy,
3244 NULL);
3245 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003246
3247 // struct _objc_cache *
3248 CacheTy = llvm::OpaqueType::get();
3249 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3250 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003251
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003252 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003253
3254 QualType IdType = Ctx.getObjCIdType();
3255 QualType SelType = Ctx.getObjCSelType();
3256 llvm::SmallVector<QualType,16> Params;
3257 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003258
3259 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003260 Params.push_back(IdType);
3261 Params.push_back(SelType);
3262 Params.push_back(Ctx.LongTy);
3263 Params.push_back(Ctx.BoolTy);
3264 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3265 false);
3266 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003267
3268 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3269 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003270 Params.push_back(IdType);
3271 Params.push_back(SelType);
3272 Params.push_back(Ctx.LongTy);
3273 Params.push_back(IdType);
3274 Params.push_back(Ctx.BoolTy);
3275 Params.push_back(Ctx.BoolTy);
3276 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3277 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3278
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003279 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003280
3281 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003282 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003283 Params.push_back(IdType);
3284 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3285 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3286 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003287
3288 // gc's API
3289 // id objc_read_weak (id *)
3290 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003291 Params.push_back(Ctx.getPointerType(IdType));
3292 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3293 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3294
Chris Lattner96508e12009-04-17 22:12:36 +00003295 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003296 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003297 Params.push_back(IdType);
3298 Params.push_back(Ctx.getPointerType(IdType));
3299
3300 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003301 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3302 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3303 GcAssignStrongCastFn =
3304 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003305
3306 // void objc_exception_throw(id)
3307 Params.clear();
3308 Params.push_back(IdType);
3309
3310 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003311 ExceptionThrowFn =
3312 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003313
3314 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003315 // void objc_sync_exit (id)
3316 Params.clear();
3317 Params.push_back(IdType);
3318
3319 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003320 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003321}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003322
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003323ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3324 : ObjCCommonTypesHelper(cgm)
3325{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003326 // struct _objc_method_description {
3327 // SEL name;
3328 // char *types;
3329 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003330 MethodDescriptionTy =
3331 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003332 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003333 NULL);
3334 CGM.getModule().addTypeName("struct._objc_method_description",
3335 MethodDescriptionTy);
3336
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003337 // struct _objc_method_description_list {
3338 // int count;
3339 // struct _objc_method_description[1];
3340 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003341 MethodDescriptionListTy =
3342 llvm::StructType::get(IntTy,
3343 llvm::ArrayType::get(MethodDescriptionTy, 0),
3344 NULL);
3345 CGM.getModule().addTypeName("struct._objc_method_description_list",
3346 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003347
3348 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003349 MethodDescriptionListPtrTy =
3350 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3351
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003352 // Protocol description structures
3353
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003354 // struct _objc_protocol_extension {
3355 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3356 // struct _objc_method_description_list *optional_instance_methods;
3357 // struct _objc_method_description_list *optional_class_methods;
3358 // struct _objc_property_list *instance_properties;
3359 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003360 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003361 llvm::StructType::get(IntTy,
3362 MethodDescriptionListPtrTy,
3363 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003364 PropertyListPtrTy,
3365 NULL);
3366 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3367 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003368
3369 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003370 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3371
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003372 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003373
3374 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3375 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3376
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003377 const llvm::Type *T =
3378 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3379 LongTy,
3380 llvm::ArrayType::get(ProtocolTyHolder, 0),
3381 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003382 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3383
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003384 // struct _objc_protocol {
3385 // struct _objc_protocol_extension *isa;
3386 // char *protocol_name;
3387 // struct _objc_protocol **_objc_protocol_list;
3388 // struct _objc_method_description_list *instance_methods;
3389 // struct _objc_method_description_list *class_methods;
3390 // }
3391 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003392 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003393 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3394 MethodDescriptionListPtrTy,
3395 MethodDescriptionListPtrTy,
3396 NULL);
3397 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3398
3399 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3400 CGM.getModule().addTypeName("struct._objc_protocol_list",
3401 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003402 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003403 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3404
3405 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003406 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003407 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003408
3409 // Class description structures
3410
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003411 // struct _objc_ivar {
3412 // char *ivar_name;
3413 // char *ivar_type;
3414 // int ivar_offset;
3415 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003416 IvarTy = llvm::StructType::get(Int8PtrTy,
3417 Int8PtrTy,
3418 IntTy,
3419 NULL);
3420 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3421
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003422 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003423 IvarListTy = llvm::OpaqueType::get();
3424 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3425 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3426
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003427 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003428 MethodListTy = llvm::OpaqueType::get();
3429 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3430 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3431
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003432 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003433 ClassExtensionTy =
3434 llvm::StructType::get(IntTy,
3435 Int8PtrTy,
3436 PropertyListPtrTy,
3437 NULL);
3438 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3439 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3440
3441 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3442
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003443 // struct _objc_class {
3444 // Class isa;
3445 // Class super_class;
3446 // char *name;
3447 // long version;
3448 // long info;
3449 // long instance_size;
3450 // struct _objc_ivar_list *ivars;
3451 // struct _objc_method_list *methods;
3452 // struct _objc_cache *cache;
3453 // struct _objc_protocol_list *protocols;
3454 // char *ivar_layout;
3455 // struct _objc_class_ext *ext;
3456 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003457 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3458 llvm::PointerType::getUnqual(ClassTyHolder),
3459 Int8PtrTy,
3460 LongTy,
3461 LongTy,
3462 LongTy,
3463 IvarListPtrTy,
3464 MethodListPtrTy,
3465 CachePtrTy,
3466 ProtocolListPtrTy,
3467 Int8PtrTy,
3468 ClassExtensionPtrTy,
3469 NULL);
3470 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3471
3472 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3473 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3474 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3475
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003476 // struct _objc_category {
3477 // char *category_name;
3478 // char *class_name;
3479 // struct _objc_method_list *instance_method;
3480 // struct _objc_method_list *class_method;
3481 // uint32_t size; // sizeof(struct _objc_category)
3482 // struct _objc_property_list *instance_properties;// category's @property
3483 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003484 CategoryTy = llvm::StructType::get(Int8PtrTy,
3485 Int8PtrTy,
3486 MethodListPtrTy,
3487 MethodListPtrTy,
3488 ProtocolListPtrTy,
3489 IntTy,
3490 PropertyListPtrTy,
3491 NULL);
3492 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3493
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003494 // Global metadata structures
3495
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003496 // struct _objc_symtab {
3497 // long sel_ref_cnt;
3498 // SEL *refs;
3499 // short cls_def_cnt;
3500 // short cat_def_cnt;
3501 // char *defs[cls_def_cnt + cat_def_cnt];
3502 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003503 SymtabTy = llvm::StructType::get(LongTy,
3504 SelectorPtrTy,
3505 ShortTy,
3506 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003507 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003508 NULL);
3509 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3510 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3511
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003512 // struct _objc_module {
3513 // long version;
3514 // long size; // sizeof(struct _objc_module)
3515 // char *name;
3516 // struct _objc_symtab* symtab;
3517 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003518 ModuleTy =
3519 llvm::StructType::get(LongTy,
3520 LongTy,
3521 Int8PtrTy,
3522 SymtabPtrTy,
3523 NULL);
3524 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003525
Daniel Dunbar49f66022008-09-24 03:38:44 +00003526 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003527
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003528 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003529 std::vector<const llvm::Type*> Params;
3530 Params.push_back(ObjectPtrTy);
3531 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003532 MessageSendFn =
3533 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3534 Params,
3535 true),
3536 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003537
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003538 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003539 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003540 Params.push_back(ObjectPtrTy);
3541 Params.push_back(SelectorPtrTy);
3542 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003543 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3544 Params,
3545 true),
3546 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003547
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003548 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003549 Params.clear();
3550 Params.push_back(ObjectPtrTy);
3551 Params.push_back(SelectorPtrTy);
3552 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003553 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003554 MessageSendFpretFn =
3555 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3556 Params,
3557 true),
3558 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003559
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003560 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003561 Params.clear();
3562 Params.push_back(SuperPtrTy);
3563 Params.push_back(SelectorPtrTy);
3564 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003565 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3566 Params,
3567 true),
3568 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003569
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003570 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3571 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003572 Params.clear();
3573 Params.push_back(Int8PtrTy);
3574 Params.push_back(SuperPtrTy);
3575 Params.push_back(SelectorPtrTy);
3576 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003577 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3578 Params,
3579 true),
3580 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003581
3582 // There is no objc_msgSendSuper_fpret? How can that work?
3583 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003584
Anders Carlsson124526b2008-09-09 10:10:21 +00003585 // FIXME: This is the size of the setjmp buffer and should be
3586 // target specific. 18 is what's used on 32-bit X86.
3587 uint64_t SetJmpBufferSize = 18;
3588
3589 // Exceptions
3590 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003591 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003592
3593 ExceptionDataTy =
3594 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3595 SetJmpBufferSize),
3596 StackPtrTy, NULL);
3597 CGM.getModule().addTypeName("struct._objc_exception_data",
3598 ExceptionDataTy);
3599
3600 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003601 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3602 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003603 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3604 Params,
3605 false),
3606 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003607 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003608 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3609 Params,
3610 false),
3611 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003612 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003613 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3614 Params,
3615 false),
3616 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003617
3618 Params.clear();
3619 Params.push_back(ClassPtrTy);
3620 Params.push_back(ObjectPtrTy);
3621 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003622 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3623 Params,
3624 false),
3625 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003626
Anders Carlsson124526b2008-09-09 10:10:21 +00003627 Params.clear();
3628 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3629 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003630 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3631 Params,
3632 false),
3633 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003634
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003635}
3636
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003637ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003638: ObjCCommonTypesHelper(cgm)
3639{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003640 // struct _method_list_t {
3641 // uint32_t entsize; // sizeof(struct _objc_method)
3642 // uint32_t method_count;
3643 // struct _objc_method method_list[method_count];
3644 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003645 MethodListnfABITy = llvm::StructType::get(IntTy,
3646 IntTy,
3647 llvm::ArrayType::get(MethodTy, 0),
3648 NULL);
3649 CGM.getModule().addTypeName("struct.__method_list_t",
3650 MethodListnfABITy);
3651 // struct method_list_t *
3652 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003653
3654 // struct _protocol_t {
3655 // id isa; // NULL
3656 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003657 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003658 // const struct method_list_t * const instance_methods;
3659 // const struct method_list_t * const class_methods;
3660 // const struct method_list_t *optionalInstanceMethods;
3661 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003662 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003663 // const uint32_t size; // sizeof(struct _protocol_t)
3664 // const uint32_t flags; // = 0
3665 // }
3666
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003667 // Holder for struct _protocol_list_t *
3668 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3669
3670 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3671 Int8PtrTy,
3672 llvm::PointerType::getUnqual(
3673 ProtocolListTyHolder),
3674 MethodListnfABIPtrTy,
3675 MethodListnfABIPtrTy,
3676 MethodListnfABIPtrTy,
3677 MethodListnfABIPtrTy,
3678 PropertyListPtrTy,
3679 IntTy,
3680 IntTy,
3681 NULL);
3682 CGM.getModule().addTypeName("struct._protocol_t",
3683 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003684
3685 // struct _protocol_t*
3686 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003687
Fariborz Jahanianda320092009-01-29 19:24:30 +00003688 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003689 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003690 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003691 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003692 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3693 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003694 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003695 NULL);
3696 CGM.getModule().addTypeName("struct._objc_protocol_list",
3697 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003698 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3699 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003700
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003701 // struct _objc_protocol_list*
3702 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003703
3704 // struct _ivar_t {
3705 // unsigned long int *offset; // pointer to ivar offset location
3706 // char *name;
3707 // char *type;
3708 // uint32_t alignment;
3709 // uint32_t size;
3710 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003711 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3712 Int8PtrTy,
3713 Int8PtrTy,
3714 IntTy,
3715 IntTy,
3716 NULL);
3717 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3718
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003719 // struct _ivar_list_t {
3720 // uint32 entsize; // sizeof(struct _ivar_t)
3721 // uint32 count;
3722 // struct _iver_t list[count];
3723 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003724 IvarListnfABITy = llvm::StructType::get(IntTy,
3725 IntTy,
3726 llvm::ArrayType::get(
3727 IvarnfABITy, 0),
3728 NULL);
3729 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3730
3731 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003732
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003733 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003734 // uint32_t const flags;
3735 // uint32_t const instanceStart;
3736 // uint32_t const instanceSize;
3737 // uint32_t const reserved; // only when building for 64bit targets
3738 // const uint8_t * const ivarLayout;
3739 // const char *const name;
3740 // const struct _method_list_t * const baseMethods;
3741 // const struct _objc_protocol_list *const baseProtocols;
3742 // const struct _ivar_list_t *const ivars;
3743 // const uint8_t * const weakIvarLayout;
3744 // const struct _prop_list_t * const properties;
3745 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003746
3747 // FIXME. Add 'reserved' field in 64bit abi mode!
3748 ClassRonfABITy = llvm::StructType::get(IntTy,
3749 IntTy,
3750 IntTy,
3751 Int8PtrTy,
3752 Int8PtrTy,
3753 MethodListnfABIPtrTy,
3754 ProtocolListnfABIPtrTy,
3755 IvarListnfABIPtrTy,
3756 Int8PtrTy,
3757 PropertyListPtrTy,
3758 NULL);
3759 CGM.getModule().addTypeName("struct._class_ro_t",
3760 ClassRonfABITy);
3761
3762 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3763 std::vector<const llvm::Type*> Params;
3764 Params.push_back(ObjectPtrTy);
3765 Params.push_back(SelectorPtrTy);
3766 ImpnfABITy = llvm::PointerType::getUnqual(
3767 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3768
3769 // struct _class_t {
3770 // struct _class_t *isa;
3771 // struct _class_t * const superclass;
3772 // void *cache;
3773 // IMP *vtable;
3774 // struct class_ro_t *ro;
3775 // }
3776
3777 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3778 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3779 llvm::PointerType::getUnqual(ClassTyHolder),
3780 CachePtrTy,
3781 llvm::PointerType::getUnqual(ImpnfABITy),
3782 llvm::PointerType::getUnqual(
3783 ClassRonfABITy),
3784 NULL);
3785 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3786
3787 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3788 ClassnfABITy);
3789
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003790 // LLVM for struct _class_t *
3791 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3792
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003793 // struct _category_t {
3794 // const char * const name;
3795 // struct _class_t *const cls;
3796 // const struct _method_list_t * const instance_methods;
3797 // const struct _method_list_t * const class_methods;
3798 // const struct _protocol_list_t * const protocols;
3799 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003800 // }
3801 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003802 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003803 MethodListnfABIPtrTy,
3804 MethodListnfABIPtrTy,
3805 ProtocolListnfABIPtrTy,
3806 PropertyListPtrTy,
3807 NULL);
3808 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003809
3810 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003811 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3812 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003813
3814 // MessageRefTy - LLVM for:
3815 // struct _message_ref_t {
3816 // IMP messenger;
3817 // SEL name;
3818 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003819
3820 // First the clang type for struct _message_ref_t
3821 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3822 SourceLocation(),
3823 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003824 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3825 Ctx.VoidPtrTy, 0, false));
3826 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3827 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003828 RD->completeDefinition(Ctx);
3829
3830 MessageRefCTy = Ctx.getTagDeclType(RD);
3831 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3832 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003833
3834 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3835 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3836
3837 // SuperMessageRefTy - LLVM for:
3838 // struct _super_message_ref_t {
3839 // SUPER_IMP messenger;
3840 // SEL name;
3841 // };
3842 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3843 SelectorPtrTy,
3844 NULL);
3845 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3846
3847 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3848 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3849
3850 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3851 Params.clear();
3852 Params.push_back(ObjectPtrTy);
3853 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003854 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3855 Params,
3856 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003857 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003858 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003859 "objc_msgSend_fixup");
3860
3861 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3862 MessageSendFpretFixupFn =
3863 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3864 Params,
3865 true),
3866 "objc_msgSend_fpret_fixup");
3867
3868 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3869 MessageSendStretFixupFn =
3870 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3871 Params,
3872 true),
3873 "objc_msgSend_stret_fixup");
3874
3875 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3876 MessageSendIdFixupFn =
3877 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3878 Params,
3879 true),
3880 "objc_msgSendId_fixup");
3881
3882
3883 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3884 MessageSendIdStretFixupFn =
3885 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3886 Params,
3887 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003888 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003889
3890 // id objc_msgSendSuper2_fixup (struct objc_super *,
3891 // struct _super_message_ref_t*, ...)
3892 Params.clear();
3893 Params.push_back(SuperPtrTy);
3894 Params.push_back(SuperMessageRefPtrTy);
3895 MessageSendSuper2FixupFn =
3896 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3897 Params,
3898 true),
3899 "objc_msgSendSuper2_fixup");
3900
3901
3902 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3903 // struct _super_message_ref_t*, ...)
3904 MessageSendSuper2StretFixupFn =
3905 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3906 Params,
3907 true),
3908 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003909
3910 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003911 Params.push_back(Int8PtrTy);
3912 UnwindResumeOrRethrowFn =
3913 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3914 Params,
3915 false),
3916 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003917 ObjCBeginCatchFn =
3918 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3919 Params,
3920 false),
3921 "objc_begin_catch");
3922
3923 Params.clear();
3924 ObjCEndCatchFn =
3925 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3926 Params,
3927 false),
3928 "objc_end_catch");
3929
3930 // struct objc_typeinfo {
3931 // const void** vtable; // objc_ehtype_vtable + 2
3932 // const char* name; // c++ typeinfo string
3933 // Class cls;
3934 // };
3935 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3936 Int8PtrTy,
3937 ClassnfABIPtrTy,
3938 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003939 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003940 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003941}
3942
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003943llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3944 FinishNonFragileABIModule();
3945
3946 return NULL;
3947}
3948
3949void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3950 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003951
3952 // Build list of all implemented classe addresses in array
3953 // L_OBJC_LABEL_CLASS_$.
3954 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3955 // list of 'nonlazy' implementations (defined as those with a +load{}
3956 // method!!).
3957 unsigned NumClasses = DefinedClasses.size();
3958 if (NumClasses) {
3959 std::vector<llvm::Constant*> Symbols(NumClasses);
3960 for (unsigned i=0; i<NumClasses; i++)
3961 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3962 ObjCTypes.Int8PtrTy);
3963 llvm::Constant* Init =
3964 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3965 NumClasses),
3966 Symbols);
3967
3968 llvm::GlobalVariable *GV =
3969 new llvm::GlobalVariable(Init->getType(), false,
3970 llvm::GlobalValue::InternalLinkage,
3971 Init,
3972 "\01L_OBJC_LABEL_CLASS_$",
3973 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003974 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003975 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3976 UsedGlobals.push_back(GV);
3977 }
3978
3979 // Build list of all implemented category addresses in array
3980 // L_OBJC_LABEL_CATEGORY_$.
3981 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3982 // list of 'nonlazy' category implementations (defined as those with a +load{}
3983 // method!!).
3984 unsigned NumCategory = DefinedCategories.size();
3985 if (NumCategory) {
3986 std::vector<llvm::Constant*> Symbols(NumCategory);
3987 for (unsigned i=0; i<NumCategory; i++)
3988 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3989 ObjCTypes.Int8PtrTy);
3990 llvm::Constant* Init =
3991 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3992 NumCategory),
3993 Symbols);
3994
3995 llvm::GlobalVariable *GV =
3996 new llvm::GlobalVariable(Init->getType(), false,
3997 llvm::GlobalValue::InternalLinkage,
3998 Init,
3999 "\01L_OBJC_LABEL_CATEGORY_$",
4000 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004001 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004002 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4003 UsedGlobals.push_back(GV);
4004 }
4005
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004006 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4007 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4008 std::vector<llvm::Constant*> Values(2);
4009 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004010 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004011 // FIXME: Fix and continue?
4012 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4013 flags |= eImageInfo_GarbageCollected;
4014 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4015 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004016 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004017 llvm::Constant* Init = llvm::ConstantArray::get(
4018 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4019 Values);
4020 llvm::GlobalVariable *IMGV =
4021 new llvm::GlobalVariable(Init->getType(), false,
4022 llvm::GlobalValue::InternalLinkage,
4023 Init,
4024 "\01L_OBJC_IMAGE_INFO",
4025 &CGM.getModule());
4026 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4027 UsedGlobals.push_back(IMGV);
4028
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004029 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004030
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004031 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4032 e = UsedGlobals.end(); i != e; ++i) {
4033 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4034 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004035
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004036 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4037 llvm::GlobalValue *GV =
4038 new llvm::GlobalVariable(AT, false,
4039 llvm::GlobalValue::AppendingLinkage,
4040 llvm::ConstantArray::get(AT, Used),
4041 "llvm.used",
4042 &CGM.getModule());
4043
4044 GV->setSection("llvm.metadata");
4045
4046}
4047
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004048// Metadata flags
4049enum MetaDataDlags {
4050 CLS = 0x0,
4051 CLS_META = 0x1,
4052 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004053 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004054 CLS_EXCEPTION = 0x20
4055};
4056/// BuildClassRoTInitializer - generate meta-data for:
4057/// struct _class_ro_t {
4058/// uint32_t const flags;
4059/// uint32_t const instanceStart;
4060/// uint32_t const instanceSize;
4061/// uint32_t const reserved; // only when building for 64bit targets
4062/// const uint8_t * const ivarLayout;
4063/// const char *const name;
4064/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004065/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004066/// const struct _ivar_list_t *const ivars;
4067/// const uint8_t * const weakIvarLayout;
4068/// const struct _prop_list_t * const properties;
4069/// }
4070///
4071llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4072 unsigned flags,
4073 unsigned InstanceStart,
4074 unsigned InstanceSize,
4075 const ObjCImplementationDecl *ID) {
4076 std::string ClassName = ID->getNameAsString();
4077 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4078 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4079 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4080 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4081 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004082 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004083 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004084 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004085 // const struct _method_list_t * const baseMethods;
4086 std::vector<llvm::Constant*> Methods;
4087 std::string MethodListName("\01l_OBJC_$_");
4088 if (flags & CLS_META) {
4089 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4090 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4091 e = ID->classmeth_end(); i != e; ++i) {
4092 // Class methods should always be defined.
4093 Methods.push_back(GetMethodConstant(*i));
4094 }
4095 } else {
4096 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4097 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4098 e = ID->instmeth_end(); i != e; ++i) {
4099 // Instance methods should always be defined.
4100 Methods.push_back(GetMethodConstant(*i));
4101 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004102 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4103 e = ID->propimpl_end(); i != e; ++i) {
4104 ObjCPropertyImplDecl *PID = *i;
4105
4106 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4107 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4108
4109 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4110 if (llvm::Constant *C = GetMethodConstant(MD))
4111 Methods.push_back(C);
4112 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4113 if (llvm::Constant *C = GetMethodConstant(MD))
4114 Methods.push_back(C);
4115 }
4116 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004117 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004118 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004119 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004120
4121 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4122 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4123 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4124 + OID->getNameAsString(),
4125 OID->protocol_begin(),
4126 OID->protocol_end());
4127
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004128 if (flags & CLS_META)
4129 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4130 else
4131 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004132 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004133 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004134 if (flags & CLS_META)
4135 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4136 else
4137 Values[ 9] =
4138 EmitPropertyList(
4139 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4140 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004141 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4142 Values);
4143 llvm::GlobalVariable *CLASS_RO_GV =
4144 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4145 llvm::GlobalValue::InternalLinkage,
4146 Init,
4147 (flags & CLS_META) ?
4148 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4149 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4150 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004151 CLASS_RO_GV->setAlignment(
4152 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004153 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004154 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004155
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004156}
4157
4158/// BuildClassMetaData - This routine defines that to-level meta-data
4159/// for the given ClassName for:
4160/// struct _class_t {
4161/// struct _class_t *isa;
4162/// struct _class_t * const superclass;
4163/// void *cache;
4164/// IMP *vtable;
4165/// struct class_ro_t *ro;
4166/// }
4167///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004168llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4169 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004170 llvm::Constant *IsAGV,
4171 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004172 llvm::Constant *ClassRoGV,
4173 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004174 std::vector<llvm::Constant*> Values(5);
4175 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004176 Values[1] = SuperClassGV
4177 ? SuperClassGV
4178 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004179 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4180 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4181 Values[4] = ClassRoGV; // &CLASS_RO_GV
4182 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4183 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004184 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4185 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004186 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004187 GV->setAlignment(
4188 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004189 if (HiddenVisibility)
4190 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004191 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004192}
4193
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004194void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4195 std::string ClassName = ID->getNameAsString();
4196 if (!ObjCEmptyCacheVar) {
4197 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004198 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004199 false,
4200 llvm::GlobalValue::ExternalLinkage,
4201 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004202 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004203 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204
4205 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004206 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004207 false,
4208 llvm::GlobalValue::ExternalLinkage,
4209 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004210 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004211 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004212 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004213 assert(ID->getClassInterface() &&
4214 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004215 uint32_t InstanceStart =
4216 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4217 uint32_t InstanceSize = InstanceStart;
4218 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004219 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4220 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004221
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004222 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004223
Daniel Dunbar04d40782009-04-14 06:00:08 +00004224 bool classIsHidden =
4225 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004226 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004227 flags |= OBJC2_CLS_HIDDEN;
4228 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004229 // class is root
4230 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004231 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004232 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004233 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004234 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004235 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4236 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4237 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004238 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004239 // work on super class metadata symbol.
4240 std::string SuperClassName =
4241 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004242 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004243 }
4244 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4245 InstanceStart,
4246 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004247 std::string TClassName = ObjCMetaClassName + ClassName;
4248 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004249 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4250 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004251
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004252 // Metadata for the class
4253 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004254 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004255 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004256
4257 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4258 flags |= CLS_EXCEPTION;
4259
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004260 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004261 flags |= CLS_ROOT;
4262 SuperClassGV = 0;
4263 }
4264 else {
4265 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004266 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004267 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004268 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004269 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004270 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004271 InstanceStart = InstanceSize = 0;
4272 if (ObjCInterfaceDecl *OID =
4273 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4274 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004275 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004276
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004277 RecordDecl::field_iterator firstField, lastField;
4278 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004279
Douglas Gregor6ab35242009-04-09 21:40:53 +00004280 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004281 ifield = firstField; ifield != e; ++ifield)
4282 lastField = ifield;
4283
Douglas Gregor6ab35242009-04-09 21:40:53 +00004284 if (lastField != RD->field_end(CGM.getContext())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004285 FieldDecl *Field = *lastField;
4286 const llvm::Type *FieldTy =
4287 CGM.getTypes().ConvertTypeForMem(Field->getType());
4288 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004289 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004290 if (firstField == RD->field_end(CGM.getContext()))
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004291 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004292 else {
4293 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004294 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004295 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004296 }
4297 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004298 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004299 InstanceStart,
4300 InstanceSize,
4301 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004302
4303 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004304 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004305 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4306 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004307 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004308
4309 // Force the definition of the EHType if necessary.
4310 if (flags & CLS_EXCEPTION)
4311 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004312}
4313
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004314/// GenerateProtocolRef - This routine is called to generate code for
4315/// a protocol reference expression; as in:
4316/// @code
4317/// @protocol(Proto1);
4318/// @endcode
4319/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4320/// which will hold address of the protocol meta-data.
4321///
4322llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4323 const ObjCProtocolDecl *PD) {
4324
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004325 // This routine is called for @protocol only. So, we must build definition
4326 // of protocol's meta-data (not a reference to it!)
4327 //
4328 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004329 ObjCTypes.ExternalProtocolPtrTy);
4330
4331 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4332 ProtocolName += PD->getNameAsCString();
4333
4334 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4335 if (PTGV)
4336 return Builder.CreateLoad(PTGV, false, "tmp");
4337 PTGV = new llvm::GlobalVariable(
4338 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004339 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004340 Init,
4341 ProtocolName,
4342 &CGM.getModule());
4343 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4344 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4345 UsedGlobals.push_back(PTGV);
4346 return Builder.CreateLoad(PTGV, false, "tmp");
4347}
4348
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004349/// GenerateCategory - Build metadata for a category implementation.
4350/// struct _category_t {
4351/// const char * const name;
4352/// struct _class_t *const cls;
4353/// const struct _method_list_t * const instance_methods;
4354/// const struct _method_list_t * const class_methods;
4355/// const struct _protocol_list_t * const protocols;
4356/// const struct _prop_list_t * const properties;
4357/// }
4358///
4359void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4360{
4361 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004362 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4363 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004364 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004365 std::string ExtClassName(getClassSymbolPrefix() +
4366 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004367
4368 std::vector<llvm::Constant*> Values(6);
4369 Values[0] = GetClassName(OCD->getIdentifier());
4370 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004371 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004372 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004373 std::vector<llvm::Constant*> Methods;
4374 std::string MethodListName(Prefix);
4375 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4376 "_$_" + OCD->getNameAsString();
4377
4378 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4379 e = OCD->instmeth_end(); i != e; ++i) {
4380 // Instance methods should always be defined.
4381 Methods.push_back(GetMethodConstant(*i));
4382 }
4383
4384 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004385 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004386 Methods);
4387
4388 MethodListName = Prefix;
4389 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4390 OCD->getNameAsString();
4391 Methods.clear();
4392 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4393 e = OCD->classmeth_end(); i != e; ++i) {
4394 // Class methods should always be defined.
4395 Methods.push_back(GetMethodConstant(*i));
4396 }
4397
4398 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004399 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004400 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004401 const ObjCCategoryDecl *Category =
4402 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004403 if (Category) {
4404 std::string ExtName(Interface->getNameAsString() + "_$_" +
4405 OCD->getNameAsString());
4406 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4407 + Interface->getNameAsString() + "_$_"
4408 + Category->getNameAsString(),
4409 Category->protocol_begin(),
4410 Category->protocol_end());
4411 Values[5] =
4412 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4413 OCD, Category, ObjCTypes);
4414 }
4415 else {
4416 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4417 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4418 }
4419
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004420 llvm::Constant *Init =
4421 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4422 Values);
4423 llvm::GlobalVariable *GCATV
4424 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4425 false,
4426 llvm::GlobalValue::InternalLinkage,
4427 Init,
4428 ExtCatName,
4429 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004430 GCATV->setAlignment(
4431 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004432 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004433 UsedGlobals.push_back(GCATV);
4434 DefinedCategories.push_back(GCATV);
4435}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004436
4437/// GetMethodConstant - Return a struct objc_method constant for the
4438/// given method if it has been defined. The result is null if the
4439/// method has not been defined. The return value has type MethodPtrTy.
4440llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4441 const ObjCMethodDecl *MD) {
4442 // FIXME: Use DenseMap::lookup
4443 llvm::Function *Fn = MethodDefinitions[MD];
4444 if (!Fn)
4445 return 0;
4446
4447 std::vector<llvm::Constant*> Method(3);
4448 Method[0] =
4449 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4450 ObjCTypes.SelectorPtrTy);
4451 Method[1] = GetMethodVarType(MD);
4452 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4453 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4454}
4455
4456/// EmitMethodList - Build meta-data for method declarations
4457/// struct _method_list_t {
4458/// uint32_t entsize; // sizeof(struct _objc_method)
4459/// uint32_t method_count;
4460/// struct _objc_method method_list[method_count];
4461/// }
4462///
4463llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4464 const std::string &Name,
4465 const char *Section,
4466 const ConstantVector &Methods) {
4467 // Return null for empty list.
4468 if (Methods.empty())
4469 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4470
4471 std::vector<llvm::Constant*> Values(3);
4472 // sizeof(struct _objc_method)
4473 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4474 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4475 // method_count
4476 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4477 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4478 Methods.size());
4479 Values[2] = llvm::ConstantArray::get(AT, Methods);
4480 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4481
4482 llvm::GlobalVariable *GV =
4483 new llvm::GlobalVariable(Init->getType(), false,
4484 llvm::GlobalValue::InternalLinkage,
4485 Init,
4486 Name,
4487 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004488 GV->setAlignment(
4489 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004490 GV->setSection(Section);
4491 UsedGlobals.push_back(GV);
4492 return llvm::ConstantExpr::getBitCast(GV,
4493 ObjCTypes.MethodListnfABIPtrTy);
4494}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004495
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004496/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4497/// the given ivar.
4498///
4499llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004500 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004501 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004502 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004503 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4504 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004505 llvm::GlobalVariable *IvarOffsetGV =
4506 CGM.getModule().getGlobalVariable(Name);
4507 if (!IvarOffsetGV)
4508 IvarOffsetGV =
4509 new llvm::GlobalVariable(ObjCTypes.LongTy,
4510 false,
4511 llvm::GlobalValue::ExternalLinkage,
4512 0,
4513 Name,
4514 &CGM.getModule());
4515 return IvarOffsetGV;
4516}
4517
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004518llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004519 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004520 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004521 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004522 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4523 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4524 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004525 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004526 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004527
4528 // FIXME: This matches gcc, but shouldn't the visibility be set on
4529 // the use as well (i.e., in ObjCIvarOffsetVariable).
4530 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4531 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4532 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004533 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004534 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004535 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004536 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004537 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004538}
4539
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004540/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004541/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004542/// IvarListnfABIPtrTy.
4543/// struct _ivar_t {
4544/// unsigned long int *offset; // pointer to ivar offset location
4545/// char *name;
4546/// char *type;
4547/// uint32_t alignment;
4548/// uint32_t size;
4549/// }
4550/// struct _ivar_list_t {
4551/// uint32 entsize; // sizeof(struct _ivar_t)
4552/// uint32 count;
4553/// struct _iver_t list[count];
4554/// }
4555///
4556llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4557 const ObjCImplementationDecl *ID) {
4558
4559 std::vector<llvm::Constant*> Ivars, Ivar(5);
4560
4561 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4562 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4563
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004564 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004565 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004566
4567 RecordDecl::field_iterator i,p;
4568 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004569 // collect declared and synthesized ivars in a small vector.
4570 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4571 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4572 E = OID->ivar_end(); I != E; ++I)
4573 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004574 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4575 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004576 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4577 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004578
Fariborz Jahanian18191882009-03-31 18:11:23 +00004579 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004580 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4581 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004582 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004583 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004584 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004585 if (Field->getIdentifier())
4586 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4587 else
4588 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004589 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004590 const llvm::Type *FieldTy =
4591 CGM.getTypes().ConvertTypeForMem(Field->getType());
4592 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4593 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4594 Field->getType().getTypePtr()) >> 3;
4595 Align = llvm::Log2_32(Align);
4596 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004597 // NOTE. Size of a bitfield does not match gcc's, because of the way
4598 // bitfields are treated special in each. But I am told that 'size'
4599 // for bitfield ivars is ignored by the runtime so it does not matter.
4600 // (even if it matters, some day, there is enough info. to get the bitfield
4601 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004602 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4603 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4604 }
4605 // Return null for empty list.
4606 if (Ivars.empty())
4607 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4608 std::vector<llvm::Constant*> Values(3);
4609 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4610 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4611 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4612 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4613 Ivars.size());
4614 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4615 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4616 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4617 llvm::GlobalVariable *GV =
4618 new llvm::GlobalVariable(Init->getType(), false,
4619 llvm::GlobalValue::InternalLinkage,
4620 Init,
4621 Prefix + OID->getNameAsString(),
4622 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004623 GV->setAlignment(
4624 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004625 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004626
4627 UsedGlobals.push_back(GV);
4628 return llvm::ConstantExpr::getBitCast(GV,
4629 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004630}
4631
4632llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4633 const ObjCProtocolDecl *PD) {
4634 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4635
4636 if (!Entry) {
4637 // We use the initializer as a marker of whether this is a forward
4638 // reference or not. At module finalization we add the empty
4639 // contents for protocols which were referenced but never defined.
4640 Entry =
4641 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4642 llvm::GlobalValue::ExternalLinkage,
4643 0,
4644 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4645 &CGM.getModule());
4646 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4647 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004648 }
4649
4650 return Entry;
4651}
4652
4653/// GetOrEmitProtocol - Generate the protocol meta-data:
4654/// @code
4655/// struct _protocol_t {
4656/// id isa; // NULL
4657/// const char * const protocol_name;
4658/// const struct _protocol_list_t * protocol_list; // super protocols
4659/// const struct method_list_t * const instance_methods;
4660/// const struct method_list_t * const class_methods;
4661/// const struct method_list_t *optionalInstanceMethods;
4662/// const struct method_list_t *optionalClassMethods;
4663/// const struct _prop_list_t * properties;
4664/// const uint32_t size; // sizeof(struct _protocol_t)
4665/// const uint32_t flags; // = 0
4666/// }
4667/// @endcode
4668///
4669
4670llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4671 const ObjCProtocolDecl *PD) {
4672 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4673
4674 // Early exit if a defining object has already been generated.
4675 if (Entry && Entry->hasInitializer())
4676 return Entry;
4677
4678 const char *ProtocolName = PD->getNameAsCString();
4679
4680 // Construct method lists.
4681 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4682 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004683 for (ObjCProtocolDecl::instmeth_iterator
4684 i = PD->instmeth_begin(CGM.getContext()),
4685 e = PD->instmeth_end(CGM.getContext());
4686 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004687 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004688 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004689 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4690 OptInstanceMethods.push_back(C);
4691 } else {
4692 InstanceMethods.push_back(C);
4693 }
4694 }
4695
Douglas Gregor6ab35242009-04-09 21:40:53 +00004696 for (ObjCProtocolDecl::classmeth_iterator
4697 i = PD->classmeth_begin(CGM.getContext()),
4698 e = PD->classmeth_end(CGM.getContext());
4699 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004700 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004701 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004702 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4703 OptClassMethods.push_back(C);
4704 } else {
4705 ClassMethods.push_back(C);
4706 }
4707 }
4708
4709 std::vector<llvm::Constant*> Values(10);
4710 // isa is NULL
4711 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4712 Values[1] = GetClassName(PD->getIdentifier());
4713 Values[2] = EmitProtocolList(
4714 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4715 PD->protocol_begin(),
4716 PD->protocol_end());
4717
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004718 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004719 + PD->getNameAsString(),
4720 "__DATA, __objc_const",
4721 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004722 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004723 + PD->getNameAsString(),
4724 "__DATA, __objc_const",
4725 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004726 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004727 + PD->getNameAsString(),
4728 "__DATA, __objc_const",
4729 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004730 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004731 + PD->getNameAsString(),
4732 "__DATA, __objc_const",
4733 OptClassMethods);
4734 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4735 0, PD, ObjCTypes);
4736 uint32_t Size =
4737 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4738 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4739 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4740 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4741 Values);
4742
4743 if (Entry) {
4744 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004745 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004746 Entry->setInitializer(Init);
4747 } else {
4748 Entry =
4749 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004750 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004751 Init,
4752 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4753 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004754 Entry->setAlignment(
4755 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004756 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004757 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004758 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4759
4760 // Use this protocol meta-data to build protocol list table in section
4761 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004762 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004763 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004764 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004765 Entry,
4766 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4767 +ProtocolName,
4768 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004769 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004770 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004771 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004772 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4773 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004774 return Entry;
4775}
4776
4777/// EmitProtocolList - Generate protocol list meta-data:
4778/// @code
4779/// struct _protocol_list_t {
4780/// long protocol_count; // Note, this is 32/64 bit
4781/// struct _protocol_t[protocol_count];
4782/// }
4783/// @endcode
4784///
4785llvm::Constant *
4786CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4787 ObjCProtocolDecl::protocol_iterator begin,
4788 ObjCProtocolDecl::protocol_iterator end) {
4789 std::vector<llvm::Constant*> ProtocolRefs;
4790
Fariborz Jahanianda320092009-01-29 19:24:30 +00004791 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004792 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4794
Daniel Dunbar948e2582009-02-15 07:36:20 +00004795 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004796 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4797 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004798 return llvm::ConstantExpr::getBitCast(GV,
4799 ObjCTypes.ProtocolListnfABIPtrTy);
4800
4801 for (; begin != end; ++begin)
4802 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4803
Fariborz Jahanianda320092009-01-29 19:24:30 +00004804 // This list is null terminated.
4805 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004806 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004807
4808 std::vector<llvm::Constant*> Values(2);
4809 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4810 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004811 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004812 ProtocolRefs.size()),
4813 ProtocolRefs);
4814
4815 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4816 GV = new llvm::GlobalVariable(Init->getType(), false,
4817 llvm::GlobalValue::InternalLinkage,
4818 Init,
4819 Name,
4820 &CGM.getModule());
4821 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004822 GV->setAlignment(
4823 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004824 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004825 return llvm::ConstantExpr::getBitCast(GV,
4826 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004827}
4828
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004829/// GetMethodDescriptionConstant - This routine build following meta-data:
4830/// struct _objc_method {
4831/// SEL _cmd;
4832/// char *method_type;
4833/// char *_imp;
4834/// }
4835
4836llvm::Constant *
4837CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4838 std::vector<llvm::Constant*> Desc(3);
4839 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4840 ObjCTypes.SelectorPtrTy);
4841 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004842 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004843 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4844 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4845}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004846
4847/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4848/// This code gen. amounts to generating code for:
4849/// @code
4850/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4851/// @encode
4852///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004853LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004854 CodeGen::CodeGenFunction &CGF,
4855 QualType ObjectTy,
4856 llvm::Value *BaseValue,
4857 const ObjCIvarDecl *Ivar,
4858 const FieldDecl *Field,
4859 unsigned CVRQualifiers) {
4860 assert(ObjectTy->isObjCInterfaceType() &&
4861 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004862 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004863 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004864
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004865 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004866 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004867 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4868 // (char*)BaseValue + Offset_symbol
4869 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4870 // (type *)((char*)BaseValue + Offset_symbol)
4871 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004872 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004873 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4874 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004875
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004876 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004877 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004878 CodeGenTypes::BitFieldInfo bitFieldInfo =
4879 CGM.getTypes().getBitFieldInfo(Field);
4880 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004881 FieldTy->isSignedIntegerType(),
4882 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004883 }
4884
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004885 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004886 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4887 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004888 LValue::SetObjCIvar(LV, true);
4889 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004890}
4891
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004892llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4893 CodeGen::CodeGenFunction &CGF,
4894 ObjCInterfaceDecl *Interface,
4895 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004896 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4897 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004898}
4899
Fariborz Jahanian46551122009-02-04 00:22:57 +00004900CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4901 CodeGen::CodeGenFunction &CGF,
4902 QualType ResultType,
4903 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004904 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004905 QualType Arg0Ty,
4906 bool IsSuper,
4907 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004908 // FIXME. Even though IsSuper is passes. This function doese not
4909 // handle calls to 'super' receivers.
4910 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004911 llvm::Value *Arg0 = Receiver;
4912 if (!IsSuper)
4913 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004914
4915 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004916 // FIXME. This is too much work to get the ABI-specific result type
4917 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004918 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4919 llvm::SmallVector<QualType, 16>());
4920 llvm::Constant *Fn;
4921 std::string Name("\01l_");
4922 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004923#if 0
4924 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004925 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4926 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4927 // FIXME. Is there a better way of getting these names.
4928 // They are available in RuntimeFunctions vector pair.
4929 Name += "objc_msgSendId_stret_fixup";
4930 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004931 else
4932#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004933 if (IsSuper) {
4934 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4935 Name += "objc_msgSendSuper2_stret_fixup";
4936 }
4937 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004938 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004939 Fn = ObjCTypes.MessageSendStretFixupFn;
4940 Name += "objc_msgSend_stret_fixup";
4941 }
4942 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004943 else if (ResultType->isFloatingType() &&
4944 // Selection of frret API only happens in 32bit nonfragile ABI.
4945 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004946 Fn = ObjCTypes.MessageSendFpretFixupFn;
4947 Name += "objc_msgSend_fpret_fixup";
4948 }
4949 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004950#if 0
4951// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004952 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4953 Fn = ObjCTypes.MessageSendIdFixupFn;
4954 Name += "objc_msgSendId_fixup";
4955 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004956 else
4957#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004958 if (IsSuper) {
4959 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4960 Name += "objc_msgSendSuper2_fixup";
4961 }
4962 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004963 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004964 Fn = ObjCTypes.MessageSendFixupFn;
4965 Name += "objc_msgSend_fixup";
4966 }
4967 }
4968 Name += '_';
4969 std::string SelName(Sel.getAsString());
4970 // Replace all ':' in selector name with '_' ouch!
4971 for(unsigned i = 0; i < SelName.size(); i++)
4972 if (SelName[i] == ':')
4973 SelName[i] = '_';
4974 Name += SelName;
4975 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4976 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004977 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004978 std::vector<llvm::Constant*> Values(2);
4979 Values[0] = Fn;
4980 Values[1] = GetMethodVarName(Sel);
4981 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4982 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004983 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004984 Init,
4985 Name,
4986 &CGM.getModule());
4987 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00004988 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004989 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004990 }
4991 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004992
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004993 CallArgList ActualArgs;
4994 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4995 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4996 ObjCTypes.MessageRefCPtrTy));
4997 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004998 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4999 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5000 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005001 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005002 Callee = CGF.Builder.CreateBitCast(Callee,
5003 llvm::PointerType::getUnqual(FTy));
5004 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005005}
5006
5007/// Generate code for a message send expression in the nonfragile abi.
5008CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5009 CodeGen::CodeGenFunction &CGF,
5010 QualType ResultType,
5011 Selector Sel,
5012 llvm::Value *Receiver,
5013 bool IsClassMessage,
5014 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005015 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005017 false, CallArgs);
5018}
5019
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005020llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005021CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005022 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5023
Daniel Dunbardfff2302009-03-02 05:18:14 +00005024 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005025 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5026 llvm::GlobalValue::ExternalLinkage,
5027 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005028 }
5029
5030 return GV;
5031}
5032
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005033llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005034 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005035 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5036
5037 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005038 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005039 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005040 Entry =
5041 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5042 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005043 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005044 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005045 &CGM.getModule());
5046 Entry->setAlignment(
5047 CGM.getTargetData().getPrefTypeAlignment(
5048 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005049 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5050 UsedGlobals.push_back(Entry);
5051 }
5052
5053 return Builder.CreateLoad(Entry, false, "tmp");
5054}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005055
Daniel Dunbar11394522009-04-18 08:51:00 +00005056llvm::Value *
5057CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5058 const ObjCInterfaceDecl *ID) {
5059 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5060
5061 if (!Entry) {
5062 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5063 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5064 Entry =
5065 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5066 llvm::GlobalValue::InternalLinkage,
5067 ClassGV,
5068 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5069 &CGM.getModule());
5070 Entry->setAlignment(
5071 CGM.getTargetData().getPrefTypeAlignment(
5072 ObjCTypes.ClassnfABIPtrTy));
5073 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005074 UsedGlobals.push_back(Entry);
5075 }
5076
5077 return Builder.CreateLoad(Entry, false, "tmp");
5078}
5079
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005080/// EmitMetaClassRef - Return a Value * of the address of _class_t
5081/// meta-data
5082///
5083llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5084 const ObjCInterfaceDecl *ID) {
5085 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5086 if (Entry)
5087 return Builder.CreateLoad(Entry, false, "tmp");
5088
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005089 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005090 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005091 Entry =
5092 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5093 llvm::GlobalValue::InternalLinkage,
5094 MetaClassGV,
5095 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5096 &CGM.getModule());
5097 Entry->setAlignment(
5098 CGM.getTargetData().getPrefTypeAlignment(
5099 ObjCTypes.ClassnfABIPtrTy));
5100
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005101 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005102 UsedGlobals.push_back(Entry);
5103
5104 return Builder.CreateLoad(Entry, false, "tmp");
5105}
5106
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005107/// GetClass - Return a reference to the class for the given interface
5108/// decl.
5109llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5110 const ObjCInterfaceDecl *ID) {
5111 return EmitClassRef(Builder, ID);
5112}
5113
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005114/// Generates a message send where the super is the receiver. This is
5115/// a message send to self with special delivery semantics indicating
5116/// which class's method should be called.
5117CodeGen::RValue
5118CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5119 QualType ResultType,
5120 Selector Sel,
5121 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005122 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005123 llvm::Value *Receiver,
5124 bool IsClassMessage,
5125 const CodeGen::CallArgList &CallArgs) {
5126 // ...
5127 // Create and init a super structure; this is a (receiver, class)
5128 // pair we will pass to objc_msgSendSuper.
5129 llvm::Value *ObjCSuper =
5130 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5131
5132 llvm::Value *ReceiverAsObject =
5133 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5134 CGF.Builder.CreateStore(ReceiverAsObject,
5135 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5136
5137 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005138 llvm::Value *Target;
5139 if (IsClassMessage) {
5140 if (isCategoryImpl) {
5141 // Message sent to "super' in a class method defined in
5142 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005143 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005144 Target = CGF.Builder.CreateStructGEP(Target, 0);
5145 Target = CGF.Builder.CreateLoad(Target);
5146 }
5147 else
5148 Target = EmitMetaClassRef(CGF.Builder, Class);
5149 }
5150 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005151 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005152
5153 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5154 // and ObjCTypes types.
5155 const llvm::Type *ClassTy =
5156 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5157 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5158 CGF.Builder.CreateStore(Target,
5159 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5160
5161 return EmitMessageSend(CGF, ResultType, Sel,
5162 ObjCSuper, ObjCTypes.SuperPtrCTy,
5163 true, CallArgs);
5164}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005165
5166llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5167 Selector Sel) {
5168 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5169
5170 if (!Entry) {
5171 llvm::Constant *Casted =
5172 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5173 ObjCTypes.SelectorPtrTy);
5174 Entry =
5175 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5176 llvm::GlobalValue::InternalLinkage,
5177 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5178 &CGM.getModule());
5179 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5180 UsedGlobals.push_back(Entry);
5181 }
5182
5183 return Builder.CreateLoad(Entry, false, "tmp");
5184}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005185/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5186/// objc_assign_ivar (id src, id *dst)
5187///
5188void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5189 llvm::Value *src, llvm::Value *dst)
5190{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005191 const llvm::Type * SrcTy = src->getType();
5192 if (!isa<llvm::PointerType>(SrcTy)) {
5193 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5194 assert(Size <= 8 && "does not support size > 8");
5195 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5196 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005197 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5198 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005199 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5200 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5201 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5202 src, dst, "assignivar");
5203 return;
5204}
5205
5206/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5207/// objc_assign_strongCast (id src, id *dst)
5208///
5209void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5210 CodeGen::CodeGenFunction &CGF,
5211 llvm::Value *src, llvm::Value *dst)
5212{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005213 const llvm::Type * SrcTy = src->getType();
5214 if (!isa<llvm::PointerType>(SrcTy)) {
5215 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5216 assert(Size <= 8 && "does not support size > 8");
5217 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5218 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005219 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5220 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005221 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5222 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5223 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5224 src, dst, "weakassign");
5225 return;
5226}
5227
5228/// EmitObjCWeakRead - Code gen for loading value of a __weak
5229/// object: objc_read_weak (id *src)
5230///
5231llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5232 CodeGen::CodeGenFunction &CGF,
5233 llvm::Value *AddrWeakObj)
5234{
Eli Friedman8339b352009-03-07 03:57:15 +00005235 const llvm::Type* DestTy =
5236 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005237 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5238 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5239 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005240 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005241 return read_weak;
5242}
5243
5244/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5245/// objc_assign_weak (id src, id *dst)
5246///
5247void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5248 llvm::Value *src, llvm::Value *dst)
5249{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005250 const llvm::Type * SrcTy = src->getType();
5251 if (!isa<llvm::PointerType>(SrcTy)) {
5252 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5253 assert(Size <= 8 && "does not support size > 8");
5254 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5255 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005256 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5257 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005258 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5259 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005260 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005261 src, dst, "weakassign");
5262 return;
5263}
5264
5265/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5266/// objc_assign_global (id src, id *dst)
5267///
5268void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5269 llvm::Value *src, llvm::Value *dst)
5270{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005271 const llvm::Type * SrcTy = src->getType();
5272 if (!isa<llvm::PointerType>(SrcTy)) {
5273 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5274 assert(Size <= 8 && "does not support size > 8");
5275 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5276 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005277 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5278 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005279 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5280 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5281 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5282 src, dst, "globalassign");
5283 return;
5284}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005285
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005286void
5287CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5288 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005289 bool isTry = isa<ObjCAtTryStmt>(S);
5290 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5291 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005292 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005293 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005294 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005295 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5296
5297 // For @synchronized, call objc_sync_enter(sync.expr). The
5298 // evaluation of the expression must occur before we enter the
5299 // @synchronized. We can safely avoid a temp here because jumps into
5300 // @synchronized are illegal & this will dominate uses.
5301 llvm::Value *SyncArg = 0;
5302 if (!isTry) {
5303 SyncArg =
5304 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5305 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005306 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005307 }
5308
5309 // Push an EH context entry, used for handling rethrows and jumps
5310 // through finally.
5311 CGF.PushCleanupBlock(FinallyBlock);
5312
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005313 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005314
5315 CGF.EmitBlock(TryBlock);
5316 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5317 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5318 CGF.EmitBranchThroughCleanup(FinallyEnd);
5319
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005320 // Emit the exception handler.
5321
5322 CGF.EmitBlock(TryHandler);
5323
5324 llvm::Value *llvm_eh_exception =
5325 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5326 llvm::Value *llvm_eh_selector_i64 =
5327 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5328 llvm::Value *llvm_eh_typeid_for_i64 =
5329 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5330 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5331 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5332
5333 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5334 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005335 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005336
5337 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005338 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005339 bool HasCatchAll = false;
5340 if (isTry) {
5341 if (const ObjCAtCatchStmt* CatchStmt =
5342 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5343 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005344 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005345 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005346
5347 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005348 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005349 // Use i8* null here to signal this is a catch all, not a cleanup.
5350 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5351 SelectorArgs.push_back(Null);
5352 HasCatchAll = true;
5353 break;
5354 }
5355
Daniel Dunbarede8de92009-03-06 00:01:21 +00005356 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5357 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005358 llvm::Value *IDEHType =
5359 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5360 if (!IDEHType)
5361 IDEHType =
5362 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5363 llvm::GlobalValue::ExternalLinkage,
5364 0, "OBJC_EHTYPE_id", &CGM.getModule());
5365 SelectorArgs.push_back(IDEHType);
5366 HasCatchAll = true;
5367 break;
5368 }
5369
5370 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005371 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005372 assert(PT && "Invalid @catch type.");
5373 const ObjCInterfaceType *IT =
5374 PT->getPointeeType()->getAsObjCInterfaceType();
5375 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005376 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005377 SelectorArgs.push_back(EHType);
5378 }
5379 }
5380 }
5381
5382 // We use a cleanup unless there was already a catch all.
5383 if (!HasCatchAll) {
5384 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005385 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005386 }
5387
5388 llvm::Value *Selector =
5389 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5390 SelectorArgs.begin(), SelectorArgs.end(),
5391 "selector");
5392 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005393 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005394 const Stmt *CatchBody = Handlers[i].second;
5395
5396 llvm::BasicBlock *Next = 0;
5397
5398 // The last handler always matches.
5399 if (i + 1 != e) {
5400 assert(CatchParam && "Only last handler can be a catch all.");
5401
5402 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5403 Next = CGF.createBasicBlock("catch.next");
5404 llvm::Value *Id =
5405 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5406 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5407 ObjCTypes.Int8PtrTy));
5408 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5409 Match, Next);
5410
5411 CGF.EmitBlock(Match);
5412 }
5413
5414 if (CatchBody) {
5415 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5416 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5417
5418 // Cleanups must call objc_end_catch.
5419 //
5420 // FIXME: It seems incorrect for objc_begin_catch to be inside
5421 // this context, but this matches gcc.
5422 CGF.PushCleanupBlock(MatchEnd);
5423 CGF.setInvokeDest(MatchHandler);
5424
5425 llvm::Value *ExcObject =
5426 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5427
5428 // Bind the catch parameter if it exists.
5429 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005430 ExcObject =
5431 CGF.Builder.CreateBitCast(ExcObject,
5432 CGF.ConvertType(CatchParam->getType()));
5433 // CatchParam is a ParmVarDecl because of the grammar
5434 // construction used to handle this, but for codegen purposes
5435 // we treat this as a local decl.
5436 CGF.EmitLocalBlockVarDecl(*CatchParam);
5437 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005438 }
5439
5440 CGF.ObjCEHValueStack.push_back(ExcObject);
5441 CGF.EmitStmt(CatchBody);
5442 CGF.ObjCEHValueStack.pop_back();
5443
5444 CGF.EmitBranchThroughCleanup(FinallyEnd);
5445
5446 CGF.EmitBlock(MatchHandler);
5447
5448 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5449 // We are required to emit this call to satisfy LLVM, even
5450 // though we don't use the result.
5451 llvm::SmallVector<llvm::Value*, 8> Args;
5452 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005453 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005454 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5455 0));
5456 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5457 CGF.Builder.CreateStore(Exc, RethrowPtr);
5458 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5459
5460 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5461
5462 CGF.EmitBlock(MatchEnd);
5463
5464 // Unfortunately, we also have to generate another EH frame here
5465 // in case this throws.
5466 llvm::BasicBlock *MatchEndHandler =
5467 CGF.createBasicBlock("match.end.handler");
5468 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5469 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5470 Cont, MatchEndHandler,
5471 Args.begin(), Args.begin());
5472
5473 CGF.EmitBlock(Cont);
5474 if (Info.SwitchBlock)
5475 CGF.EmitBlock(Info.SwitchBlock);
5476 if (Info.EndBlock)
5477 CGF.EmitBlock(Info.EndBlock);
5478
5479 CGF.EmitBlock(MatchEndHandler);
5480 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5481 // We are required to emit this call to satisfy LLVM, even
5482 // though we don't use the result.
5483 Args.clear();
5484 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005485 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005486 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5487 0));
5488 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5489 CGF.Builder.CreateStore(Exc, RethrowPtr);
5490 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5491
5492 if (Next)
5493 CGF.EmitBlock(Next);
5494 } else {
5495 assert(!Next && "catchup should be last handler.");
5496
5497 CGF.Builder.CreateStore(Exc, RethrowPtr);
5498 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5499 }
5500 }
5501
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005502 // Pop the cleanup entry, the @finally is outside this cleanup
5503 // scope.
5504 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5505 CGF.setInvokeDest(PrevLandingPad);
5506
5507 CGF.EmitBlock(FinallyBlock);
5508
5509 if (isTry) {
5510 if (const ObjCAtFinallyStmt* FinallyStmt =
5511 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5512 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5513 } else {
5514 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5515 // @synchronized.
5516 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005517 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005518
5519 if (Info.SwitchBlock)
5520 CGF.EmitBlock(Info.SwitchBlock);
5521 if (Info.EndBlock)
5522 CGF.EmitBlock(Info.EndBlock);
5523
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005524 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005525 CGF.EmitBranch(FinallyEnd);
5526
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005527 CGF.EmitBlock(FinallyRethrow);
5528 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5529 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005530 CGF.Builder.CreateUnreachable();
5531
5532 CGF.EmitBlock(FinallyEnd);
5533}
5534
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005535/// EmitThrowStmt - Generate code for a throw statement.
5536void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5537 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005538 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005539 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005540 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005541 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005542 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5543 "Unexpected rethrow outside @catch block.");
5544 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005545 }
5546
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005547 llvm::Value *ExceptionAsObject =
5548 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5549 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5550 if (InvokeDest) {
5551 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5552 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5553 Cont, InvokeDest,
5554 &ExceptionAsObject, &ExceptionAsObject + 1);
5555 CGF.EmitBlock(Cont);
5556 } else
5557 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5558 CGF.Builder.CreateUnreachable();
5559
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005560 // Clear the insertion point to indicate we are in unreachable code.
5561 CGF.Builder.ClearInsertionPoint();
5562}
Daniel Dunbare588b992009-03-01 04:46:24 +00005563
5564llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005565CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5566 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005567 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005568
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005569 // If we don't need a definition, return the entry if found or check
5570 // if we use an external reference.
5571 if (!ForDefinition) {
5572 if (Entry)
5573 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005574
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005575 // If this type (or a super class) has the __objc_exception__
5576 // attribute, emit an external reference.
5577 if (hasObjCExceptionAttribute(ID))
5578 return Entry =
5579 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5580 llvm::GlobalValue::ExternalLinkage,
5581 0,
5582 (std::string("OBJC_EHTYPE_$_") +
5583 ID->getIdentifier()->getName()),
5584 &CGM.getModule());
5585 }
5586
5587 // Otherwise we need to either make a new entry or fill in the
5588 // initializer.
5589 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005590 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005591 std::string VTableName = "objc_ehtype_vtable";
5592 llvm::GlobalVariable *VTableGV =
5593 CGM.getModule().getGlobalVariable(VTableName);
5594 if (!VTableGV)
5595 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5596 llvm::GlobalValue::ExternalLinkage,
5597 0, VTableName, &CGM.getModule());
5598
5599 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5600
5601 std::vector<llvm::Constant*> Values(3);
5602 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5603 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005604 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005605 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5606
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005607 if (Entry) {
5608 Entry->setInitializer(Init);
5609 } else {
5610 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5611 llvm::GlobalValue::WeakAnyLinkage,
5612 Init,
5613 (std::string("OBJC_EHTYPE_$_") +
5614 ID->getIdentifier()->getName()),
5615 &CGM.getModule());
5616 }
5617
Daniel Dunbar04d40782009-04-14 06:00:08 +00005618 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005619 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005620 Entry->setAlignment(8);
5621
5622 if (ForDefinition) {
5623 Entry->setSection("__DATA,__objc_const");
5624 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5625 } else {
5626 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5627 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005628
5629 return Entry;
5630}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005631
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005632/* *** */
5633
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005634CodeGen::CGObjCRuntime *
5635CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005636 return new CGObjCMac(CGM);
5637}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005638
5639CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005640CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005641 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005642}