blob: 0d6dd6aa776f6fd5605220dba75f90fbe2acd062 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +000095 llvm::Constant *getGcAssignWeakFn() {
96 // id objc_assign_weak (id, id *)
97 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
98 Args.push_back(ObjectPtrTy->getPointerTo());
99 llvm::FunctionType *FTy =
100 llvm::FunctionType::get(ObjectPtrTy, Args, false);
101 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
102 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000115
Daniel Dunbar1c566672009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000117 llvm::Constant *getSyncEnterFn() {
118 // void objc_sync_enter (id)
119 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
120 llvm::FunctionType *FTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
122 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
123 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000127
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000131
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132/// ObjCTypesHelper - Helper class that encapsulates lazy
133/// construction of varies types used during ObjC generation.
134class ObjCTypesHelper : public ObjCCommonTypesHelper {
135private:
136
Chris Lattner74391b42009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000148
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000149 /// ProtocolTy - LLVM type for struct objc_protocol.
150 const llvm::StructType *ProtocolTy;
151 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
152 const llvm::Type *ProtocolPtrTy;
153 /// ProtocolExtensionTy - LLVM type for struct
154 /// objc_protocol_extension.
155 const llvm::StructType *ProtocolExtensionTy;
156 /// ProtocolExtensionTy - LLVM type for struct
157 /// objc_protocol_extension *.
158 const llvm::Type *ProtocolExtensionPtrTy;
159 /// MethodDescriptionTy - LLVM type for struct
160 /// objc_method_description.
161 const llvm::StructType *MethodDescriptionTy;
162 /// MethodDescriptionListTy - LLVM type for struct
163 /// objc_method_description_list.
164 const llvm::StructType *MethodDescriptionListTy;
165 /// MethodDescriptionListPtrTy - LLVM type for struct
166 /// objc_method_description_list *.
167 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000168 /// ProtocolListTy - LLVM type for struct objc_property_list.
169 const llvm::Type *ProtocolListTy;
170 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
171 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000174 /// ClassTy - LLVM type for struct objc_class.
175 const llvm::StructType *ClassTy;
176 /// ClassPtrTy - LLVM type for struct objc_class *.
177 const llvm::Type *ClassPtrTy;
178 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
179 const llvm::StructType *ClassExtensionTy;
180 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
181 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000182 // IvarTy - LLVM type for struct objc_ivar.
183 const llvm::StructType *IvarTy;
184 /// IvarListTy - LLVM type for struct objc_ivar_list.
185 const llvm::Type *IvarListTy;
186 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
187 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000188 /// MethodListTy - LLVM type for struct objc_method_list.
189 const llvm::Type *MethodListTy;
190 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
191 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson124526b2008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000210
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214
215
Chris Lattner74391b42009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattner74391b42009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattner74391b42009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000227};
228
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000232public:
Chris Lattner74391b42009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000238 // MethodListnfABITy - LLVM for struct _method_list_t
239 const llvm::StructType *MethodListnfABITy;
240
241 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
242 const llvm::Type *MethodListnfABIPtrTy;
243
244 // ProtocolnfABITy = LLVM for struct _protocol_t
245 const llvm::StructType *ProtocolnfABITy;
246
Daniel Dunbar948e2582009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000250 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
251 const llvm::StructType *ProtocolListnfABITy;
252
253 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
254 const llvm::Type *ProtocolListnfABIPtrTy;
255
256 // ClassnfABITy - LLVM for struct _class_t
257 const llvm::StructType *ClassnfABITy;
258
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000262 // IvarnfABITy - LLVM for struct _ivar_t
263 const llvm::StructType *IvarnfABITy;
264
265 // IvarListnfABITy - LLVM for struct _ivar_list_t
266 const llvm::StructType *IvarListnfABITy;
267
268 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
269 const llvm::Type *IvarListnfABIPtrTy;
270
271 // ClassRonfABITy - LLVM for struct _class_ro_t
272 const llvm::StructType *ClassRonfABITy;
273
274 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
275 const llvm::Type *ImpnfABITy;
276
277 // CategorynfABITy - LLVM for struct _category_t
278 const llvm::StructType *CategorynfABITy;
279
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000280 // New types for nonfragile abi messaging.
281
282 // MessageRefTy - LLVM for:
283 // struct _message_ref_t {
284 // IMP messenger;
285 // SEL name;
286 // };
287 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000295
Fariborz Jahanianef163782009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000299 // SuperMessageRefTy - LLVM for:
300 // struct _super_message_ref_t {
301 // SUPER_IMP messenger;
302 // SEL name;
303 // };
304 const llvm::StructType *SuperMessageRefTy;
305
306 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
307 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000311 llvm::Value *getEHPersonalityPtr() {
312 llvm::Constant *Personality =
313 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
314 std::vector<const llvm::Type*>(),
315 true),
316 "__objc_personality_v0");
317 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
318 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000319
Chris Lattner74391b42009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000324
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000333 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000334 unsigned int ivar_bytepos;
335 unsigned int ivar_size;
336 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
337 };
338
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000339 class SKIP_SCAN {
340 public:
341 unsigned int skip;
342 unsigned int scan;
343 SKIP_SCAN() : skip(0), scan(0) {}
344 };
345
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000350
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000351 // gc ivar layout bitmap calculation helper caches.
352 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
353 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
354 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000355
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000356 /// LazySymbols - Symbols to generate a lazy reference for. See
357 /// DefinedSymbols and FinishModule().
358 std::set<IdentifierInfo*> LazySymbols;
359
360 /// DefinedSymbols - External symbols which are defined by this
361 /// module. The symbols in this list and LazySymbols are used to add
362 /// special linker symbols which ensure that Objective-C modules are
363 /// linked properly.
364 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000371
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000372 /// MethodVarTypes - uniqued method type signatures. We have to use
373 /// a StringMap here because have no other unique reference.
374 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000376 /// MethodDefinitions - map of methods which have been defined in
377 /// this translation unit.
378 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000379
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000385
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000388
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000389 /// Protocols - Protocols for which an objc_protocol structure has
390 /// been emitted. Forward declarations are handled by creating an
391 /// empty structure whose initializer is filled in when/if defined.
392 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000394 /// DefinedProtocols - Protocols which have actually been
395 /// defined. We should not need this, see FIXME in GenerateProtocol.
396 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000400
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000403
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000407
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 const ObjCContainerDecl *CD,
412 std::string &NameOut);
413
414 /// GetMethodVarName - Return a unique constant for the given
415 /// selector's name. The return value has type char *.
416 llvm::Constant *GetMethodVarName(Selector Sel);
417 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
418 llvm::Constant *GetMethodVarName(const std::string &Name);
419
420 /// GetMethodVarType - Return a unique constant for the given
421 /// selector's name. The return value has type char *.
422
423 // FIXME: This is a horrible name.
424 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000425 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000426
427 /// GetPropertyName - Return a unique constant for the given
428 /// name. The return value has type char *.
429 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
430
431 // FIXME: This can be dropped once string functions are unified.
432 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
433 const Decl *Container);
434
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000435 /// GetClassName - Return a unique constant for the given selector's
436 /// name. The return value has type char *.
437 llvm::Constant *GetClassName(IdentifierInfo *Ident);
438
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000439 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
440 /// interface declaration.
441 const llvm::StructLayout *GetInterfaceDeclStructLayout(
442 const ObjCInterfaceDecl *ID) const;
443
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000456
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000457 /// GetIvarLayoutName - Returns a unique constant for the given
458 /// ivar layout bitmap.
459 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
460 const ObjCCommonTypesHelper &ObjCTypes);
461
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000462 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
463 RecordDecl::field_iterator &FIV,
464 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000465 /// EmitPropertyList - Emit the given property list. The return
466 /// value has type PropertyListPtrTy.
467 llvm::Constant *EmitPropertyList(const std::string &Name,
468 const Decl *Container,
469 const ObjCContainerDecl *OCD,
470 const ObjCCommonTypesHelper &ObjCTypes);
471
Fariborz Jahanianda320092009-01-29 19:24:30 +0000472 /// GetProtocolRef - Return a reference to the internal protocol
473 /// description, creating an empty one if it has not been
474 /// defined. The return value has type ProtocolPtrTy.
475 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000476
477 /// GetIvarBaseOffset - returns ivars byte offset.
478 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000479 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000480
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
483 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000484 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000485
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000486 /// CreateMetadataVar - Create a global variable with internal
487 /// linkage for use by the Objective-C runtime.
488 ///
489 /// This is a convenience wrapper which not only creates the
490 /// variable, but also sets the section and alignment and adds the
491 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000492 ///
493 /// \param Name - The variable name.
494 /// \param Init - The variable initializer; this is also used to
495 /// define the type of the variable.
496 /// \param Section - The section the variable should go into, or 0.
497 /// \param Align - The alignment for the variable, or 0.
498 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000499 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000500 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
501 llvm::Constant *Init,
502 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000503 unsigned Align,
504 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000505
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000506public:
507 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
508 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000509
Steve Naroff33fdb732009-03-31 16:53:37 +0000510 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000511
512 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
513 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000514
515 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
516
517 /// GetOrEmitProtocol - Get the protocol object for the given
518 /// declaration, emitting it if necessary. The return value has type
519 /// ProtocolPtrTy.
520 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
521
522 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
523 /// object for the given declaration, emitting it if needed. These
524 /// forward references will be filled in with empty bodies if no
525 /// definition is seen. The return value has type ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000527};
528
529class CGObjCMac : public CGObjCCommonMac {
530private:
531 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000532 /// EmitImageInfo - Emit the image info marker used to encode some module
533 /// level information.
534 void EmitImageInfo();
535
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000536 /// EmitModuleInfo - Another marker encoding module level
537 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000538 void EmitModuleInfo();
539
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000540 /// EmitModuleSymols - Emit module symbols, the list of defined
541 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000542 llvm::Constant *EmitModuleSymbols();
543
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000544 /// FinishModule - Write out global data structures at the end of
545 /// processing a translation unit.
546 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000547
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000548 /// EmitClassExtension - Generate the class extension structure used
549 /// to store the weak ivar layout and properties. The return value
550 /// has type ClassExtensionPtrTy.
551 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
552
553 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
554 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000555 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000556 const ObjCInterfaceDecl *ID);
557
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000558 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000559 QualType ResultType,
560 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000561 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000562 QualType Arg0Ty,
563 bool IsSuper,
564 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000565
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000566 /// EmitIvarList - Emit the ivar list for the given
567 /// implementation. If ForClass is true the list of class ivars
568 /// (i.e. metaclass ivars) is emitted, otherwise the list of
569 /// interface ivars will be emitted. The return value has type
570 /// IvarListPtrTy.
571 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000572 bool ForClass);
573
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000574 /// EmitMetaClass - Emit a forward reference to the class structure
575 /// for the metaclass of the given interface. The return value has
576 /// type ClassPtrTy.
577 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
578
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000579 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000581 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
582 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000583 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000584 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000585
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000586 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000587
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000588 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000589
590 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000591 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000592 llvm::Constant *EmitMethodList(const std::string &Name,
593 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000594 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000595
596 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000597 /// method declarations.
598 /// - TypeName: The name for the type containing the methods.
599 /// - IsProtocol: True iff these methods are for a protocol.
600 /// - ClassMethds: True iff these are class methods.
601 /// - Required: When true, only "required" methods are
602 /// listed. Similarly, when false only "optional" methods are
603 /// listed. For classes this should always be true.
604 /// - begin, end: The method list to output.
605 ///
606 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000607 llvm::Constant *EmitMethodDescList(const std::string &Name,
608 const char *Section,
609 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000610
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000611 /// GetOrEmitProtocol - Get the protocol object for the given
612 /// declaration, emitting it if necessary. The return value has type
613 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000614 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000615
616 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
617 /// object for the given declaration, emitting it if needed. These
618 /// forward references will be filled in with empty bodies if no
619 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000621
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000622 /// EmitProtocolExtension - Generate the protocol extension
623 /// structure used to store optional instance and class methods, and
624 /// protocol properties. The return value has type
625 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000626 llvm::Constant *
627 EmitProtocolExtension(const ObjCProtocolDecl *PD,
628 const ConstantVector &OptInstanceMethods,
629 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000630
631 /// EmitProtocolList - Generate the list of referenced
632 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +0000633 llvm::Constant *EmitProtocolList(const std::string &Name,
634 ObjCProtocolDecl::protocol_iterator begin,
635 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000636
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000637 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
638 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000639 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000640
Fariborz Jahanianda320092009-01-29 19:24:30 +0000641 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000642 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000643
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000644 virtual llvm::Function *ModuleInitFunction();
645
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000646 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000647 QualType ResultType,
648 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000649 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000650 bool IsClassMessage,
651 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000652
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000653 virtual CodeGen::RValue
654 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000655 QualType ResultType,
656 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000657 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000658 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000659 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000660 bool IsClassMessage,
661 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000662
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000663 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000664 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000665
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000666 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000667
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000668 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000669
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000670 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000673 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000674
Chris Lattner74391b42009-03-22 21:03:39 +0000675 virtual llvm::Constant *GetPropertyGetFunction();
676 virtual llvm::Constant *GetPropertySetFunction();
677 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000678
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000679 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
680 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000681 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
682 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000683 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000684 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000685 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
686 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000687 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
688 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000689 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
690 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000691 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000693
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000694 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
695 QualType ObjectTy,
696 llvm::Value *BaseValue,
697 const ObjCIvarDecl *Ivar,
698 const FieldDecl *Field,
699 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000700 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
701 ObjCInterfaceDecl *Interface,
702 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000703};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000704
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000705class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000706private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000707 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000708 llvm::GlobalVariable* ObjCEmptyCacheVar;
709 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000710
Daniel Dunbar11394522009-04-18 08:51:00 +0000711 /// SuperClassReferences - uniqued super class references.
712 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
713
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000714 /// MetaClassReferences - uniqued meta class references.
715 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000716
717 /// EHTypeReferences - uniqued class ehtype references.
718 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000719
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000720 /// FinishNonFragileABIModule - Write out global data structures at the end of
721 /// processing a translation unit.
722 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000723
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000724 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
725 unsigned InstanceStart,
726 unsigned InstanceSize,
727 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000728 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
729 llvm::Constant *IsAGV,
730 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000731 llvm::Constant *ClassRoGV,
732 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000733
734 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
735
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000736 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
737
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000738 /// EmitMethodList - Emit the method list for the given
739 /// implementation. The return value has type MethodListnfABITy.
740 llvm::Constant *EmitMethodList(const std::string &Name,
741 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000742 const ConstantVector &Methods);
743 /// EmitIvarList - Emit the ivar list for the given
744 /// implementation. If ForClass is true the list of class ivars
745 /// (i.e. metaclass ivars) is emitted, otherwise the list of
746 /// interface ivars will be emitted. The return value has type
747 /// IvarListnfABIPtrTy.
748 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000749
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000750 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000751 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000752 unsigned long int offset);
753
Fariborz Jahanianda320092009-01-29 19:24:30 +0000754 /// GetOrEmitProtocol - Get the protocol object for the given
755 /// declaration, emitting it if necessary. The return value has type
756 /// ProtocolPtrTy.
757 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
758
759 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
760 /// object for the given declaration, emitting it if needed. These
761 /// forward references will be filled in with empty bodies if no
762 /// definition is seen. The return value has type ProtocolPtrTy.
763 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
764
765 /// EmitProtocolList - Generate the list of referenced
766 /// protocols. The return value has type ProtocolListPtrTy.
767 llvm::Constant *EmitProtocolList(const std::string &Name,
768 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000769 ObjCProtocolDecl::protocol_iterator end);
770
771 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
772 QualType ResultType,
773 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000774 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000775 QualType Arg0Ty,
776 bool IsSuper,
777 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000778
779 /// GetClassGlobal - Return the global variable for the Objective-C
780 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000781 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
782
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000783 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000784 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000785 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000786 const ObjCInterfaceDecl *ID);
787
788 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
789 /// for the given super class reference.
790 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
791 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000792
793 /// EmitMetaClassRef - Return a Value * of the address of _class_t
794 /// meta-data
795 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
796 const ObjCInterfaceDecl *ID);
797
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000798 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
799 /// the given ivar.
800 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000801 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000802 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000803 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000804
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000805 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
806 /// for the given selector.
807 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000808
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000809 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000810 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000811 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
812 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000813
814 const char *getMetaclassSymbolPrefix() const {
815 return "OBJC_METACLASS_$_";
816 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000817
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000818 const char *getClassSymbolPrefix() const {
819 return "OBJC_CLASS_$_";
820 }
821
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000822public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000823 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000824 // FIXME. All stubs for now!
825 virtual llvm::Function *ModuleInitFunction();
826
827 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
828 QualType ResultType,
829 Selector Sel,
830 llvm::Value *Receiver,
831 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000832 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000833
834 virtual CodeGen::RValue
835 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
836 QualType ResultType,
837 Selector Sel,
838 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000839 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000840 llvm::Value *Receiver,
841 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000842 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000843
844 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000845 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000846
847 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000848 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000849
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000850 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000851
852 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000853 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000854 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000855
Chris Lattner74391b42009-03-22 21:03:39 +0000856 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000857 return ObjCTypes.GetPropertyFn;
858 }
Chris Lattner74391b42009-03-22 21:03:39 +0000859 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000860 return ObjCTypes.SetPropertyFn;
861 }
Chris Lattner74391b42009-03-22 21:03:39 +0000862 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000863 return ObjCTypes.EnumerationMutationFn;
864 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000865
866 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000867 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000868 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000869 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000870 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000871 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000872 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000873 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000874 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000875 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000876 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000877 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000878 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000879 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000880 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
881 QualType ObjectTy,
882 llvm::Value *BaseValue,
883 const ObjCIvarDecl *Ivar,
884 const FieldDecl *Field,
885 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000886 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
887 ObjCInterfaceDecl *Interface,
888 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000889};
890
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000891} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000892
893/* *** Helper Functions *** */
894
895/// getConstantGEP() - Help routine to construct simple GEPs.
896static llvm::Constant *getConstantGEP(llvm::Constant *C,
897 unsigned idx0,
898 unsigned idx1) {
899 llvm::Value *Idxs[] = {
900 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
901 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
902 };
903 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
904}
905
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000906/// hasObjCExceptionAttribute - Return true if this class or any super
907/// class has the __objc_exception__ attribute.
908static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000909 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000910 return true;
911 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
912 return hasObjCExceptionAttribute(Super);
913 return false;
914}
915
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000916/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000917
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000918CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
919 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000920{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000921 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000922 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000923}
924
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000925/// GetClass - Return a reference to the class for the given interface
926/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000927llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000928 const ObjCInterfaceDecl *ID) {
929 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000930}
931
932/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000933llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000934 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000935}
936
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000937/// Generate a constant CFString object.
938/*
939 struct __builtin_CFString {
940 const int *isa; // point to __CFConstantStringClassReference
941 int flags;
942 const char *str;
943 long length;
944 };
945*/
946
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000947llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000948 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000949 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000950}
951
952/// Generates a message send where the super is the receiver. This is
953/// a message send to self with special delivery semantics indicating
954/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000955CodeGen::RValue
956CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000957 QualType ResultType,
958 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000959 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000960 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000961 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000962 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000963 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000964 // Create and init a super structure; this is a (receiver, class)
965 // pair we will pass to objc_msgSendSuper.
966 llvm::Value *ObjCSuper =
967 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
968 llvm::Value *ReceiverAsObject =
969 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
970 CGF.Builder.CreateStore(ReceiverAsObject,
971 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000972
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000973 // If this is a class message the metaclass is passed as the target.
974 llvm::Value *Target;
975 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000976 if (isCategoryImpl) {
977 // Message sent to 'super' in a class method defined in a category
978 // implementation requires an odd treatment.
979 // If we are in a class method, we must retrieve the
980 // _metaclass_ for the current class, pointed at by
981 // the class's "isa" pointer. The following assumes that
982 // isa" is the first ivar in a class (which it must be).
983 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
984 Target = CGF.Builder.CreateStructGEP(Target, 0);
985 Target = CGF.Builder.CreateLoad(Target);
986 }
987 else {
988 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
989 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
990 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
991 Target = Super;
992 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000993 } else {
994 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
995 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000996 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
997 // and ObjCTypes types.
998 const llvm::Type *ClassTy =
999 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001000 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001001 CGF.Builder.CreateStore(Target,
1002 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1003
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001004 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001005 ObjCSuper, ObjCTypes.SuperPtrCTy,
1006 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001007}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001008
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001009/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001010CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001011 QualType ResultType,
1012 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001013 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001014 bool IsClassMessage,
1015 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001016 llvm::Value *Arg0 =
1017 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001018 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001019 Arg0, CGF.getContext().getObjCIdType(),
1020 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001021}
1022
1023CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001024 QualType ResultType,
1025 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001026 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001027 QualType Arg0Ty,
1028 bool IsSuper,
1029 const CallArgList &CallArgs) {
1030 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001031 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1032 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1033 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001034 CGF.getContext().getObjCSelType()));
1035 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001036
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001037 CodeGenTypes &Types = CGM.getTypes();
1038 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1039 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001040
1041 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001042 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001043 Fn = ObjCTypes.getSendStretFn(IsSuper);
1044 } else if (ResultType->isFloatingType()) {
1045 // FIXME: Sadly, this is wrong. This actually depends on the
1046 // architecture. This happens to be right for x86-32 though.
1047 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1048 } else {
1049 Fn = ObjCTypes.getSendFn(IsSuper);
1050 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001051 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001052 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001053}
1054
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001055llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001056 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001057 // FIXME: I don't understand why gcc generates this, or where it is
1058 // resolved. Investigate. Its also wasteful to look this up over and
1059 // over.
1060 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1061
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001062 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1063 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001064}
1065
Fariborz Jahanianda320092009-01-29 19:24:30 +00001066void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001067 // FIXME: We shouldn't need this, the protocol decl should contain
1068 // enough information to tell us whether this was a declaration or a
1069 // definition.
1070 DefinedProtocols.insert(PD->getIdentifier());
1071
1072 // If we have generated a forward reference to this protocol, emit
1073 // it now. Otherwise do nothing, the protocol objects are lazily
1074 // emitted.
1075 if (Protocols.count(PD->getIdentifier()))
1076 GetOrEmitProtocol(PD);
1077}
1078
Fariborz Jahanianda320092009-01-29 19:24:30 +00001079llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001080 if (DefinedProtocols.count(PD->getIdentifier()))
1081 return GetOrEmitProtocol(PD);
1082 return GetOrEmitProtocolRef(PD);
1083}
1084
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001085/*
1086 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1087 struct _objc_protocol {
1088 struct _objc_protocol_extension *isa;
1089 char *protocol_name;
1090 struct _objc_protocol_list *protocol_list;
1091 struct _objc__method_prototype_list *instance_methods;
1092 struct _objc__method_prototype_list *class_methods
1093 };
1094
1095 See EmitProtocolExtension().
1096*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001097llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1098 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1099
1100 // Early exit if a defining object has already been generated.
1101 if (Entry && Entry->hasInitializer())
1102 return Entry;
1103
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001104 // FIXME: I don't understand why gcc generates this, or where it is
1105 // resolved. Investigate. Its also wasteful to look this up over and
1106 // over.
1107 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1108
Chris Lattner8ec03f52008-11-24 03:54:41 +00001109 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001110
1111 // Construct method lists.
1112 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1113 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001114 for (ObjCProtocolDecl::instmeth_iterator
1115 i = PD->instmeth_begin(CGM.getContext()),
1116 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001117 ObjCMethodDecl *MD = *i;
1118 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1119 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1120 OptInstanceMethods.push_back(C);
1121 } else {
1122 InstanceMethods.push_back(C);
1123 }
1124 }
1125
Douglas Gregor6ab35242009-04-09 21:40:53 +00001126 for (ObjCProtocolDecl::classmeth_iterator
1127 i = PD->classmeth_begin(CGM.getContext()),
1128 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001129 ObjCMethodDecl *MD = *i;
1130 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1131 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1132 OptClassMethods.push_back(C);
1133 } else {
1134 ClassMethods.push_back(C);
1135 }
1136 }
1137
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001138 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001139 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001140 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001141 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001142 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001143 PD->protocol_begin(),
1144 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001145 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001146 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1147 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001148 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1149 InstanceMethods);
1150 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001151 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1152 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001153 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1154 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001155 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1156 Values);
1157
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001158 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001159 // Already created, fix the linkage and update the initializer.
1160 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001161 Entry->setInitializer(Init);
1162 } else {
1163 Entry =
1164 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1165 llvm::GlobalValue::InternalLinkage,
1166 Init,
1167 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1168 &CGM.getModule());
1169 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001170 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001171 UsedGlobals.push_back(Entry);
1172 // FIXME: Is this necessary? Why only for protocol?
1173 Entry->setAlignment(4);
1174 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001175
1176 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001177}
1178
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001179llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001180 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1181
1182 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001183 // We use the initializer as a marker of whether this is a forward
1184 // reference or not. At module finalization we add the empty
1185 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001186 Entry =
1187 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001188 llvm::GlobalValue::ExternalLinkage,
1189 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001190 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001191 &CGM.getModule());
1192 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001193 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001194 UsedGlobals.push_back(Entry);
1195 // FIXME: Is this necessary? Why only for protocol?
1196 Entry->setAlignment(4);
1197 }
1198
1199 return Entry;
1200}
1201
1202/*
1203 struct _objc_protocol_extension {
1204 uint32_t size;
1205 struct objc_method_description_list *optional_instance_methods;
1206 struct objc_method_description_list *optional_class_methods;
1207 struct objc_property_list *instance_properties;
1208 };
1209*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001210llvm::Constant *
1211CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1212 const ConstantVector &OptInstanceMethods,
1213 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001214 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001215 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001216 std::vector<llvm::Constant*> Values(4);
1217 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001218 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001219 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1220 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001221 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1222 OptInstanceMethods);
1223 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001224 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1225 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001226 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1227 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001228 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1229 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001230 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001231
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001232 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001233 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1234 Values[3]->isNullValue())
1235 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1236
1237 llvm::Constant *Init =
1238 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001239
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001240 // No special section, but goes in llvm.used
1241 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1242 Init,
1243 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001244}
1245
1246/*
1247 struct objc_protocol_list {
1248 struct objc_protocol_list *next;
1249 long count;
1250 Protocol *list[];
1251 };
1252*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001253llvm::Constant *
1254CGObjCMac::EmitProtocolList(const std::string &Name,
1255 ObjCProtocolDecl::protocol_iterator begin,
1256 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257 std::vector<llvm::Constant*> ProtocolRefs;
1258
Daniel Dunbardbc93372008-08-21 21:57:41 +00001259 for (; begin != end; ++begin)
1260 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261
1262 // Just return null for empty protocol lists
1263 if (ProtocolRefs.empty())
1264 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1265
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001266 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001267 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1268
1269 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001270 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001271 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1272 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1273 Values[2] =
1274 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1275 ProtocolRefs.size()),
1276 ProtocolRefs);
1277
1278 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1279 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001280 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001281 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001282 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1283}
1284
1285/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001286 struct _objc_property {
1287 const char * const name;
1288 const char * const attributes;
1289 };
1290
1291 struct _objc_property_list {
1292 uint32_t entsize; // sizeof (struct _objc_property)
1293 uint32_t prop_count;
1294 struct _objc_property[prop_count];
1295 };
1296*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001297llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1298 const Decl *Container,
1299 const ObjCContainerDecl *OCD,
1300 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001301 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001302 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1303 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001304 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001305 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001306 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001307 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1308 Prop));
1309 }
1310
1311 // Return null for empty list.
1312 if (Properties.empty())
1313 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1314
1315 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001316 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001317 std::vector<llvm::Constant*> Values(3);
1318 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1319 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1320 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1321 Properties.size());
1322 Values[2] = llvm::ConstantArray::get(AT, Properties);
1323 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1324
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001325 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001326 CreateMetadataVar(Name, Init,
1327 (ObjCABI == 2) ? "__DATA, __objc_const" :
1328 "__OBJC,__property,regular,no_dead_strip",
1329 (ObjCABI == 2) ? 8 : 4,
1330 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001331 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001332}
1333
1334/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001335 struct objc_method_description_list {
1336 int count;
1337 struct objc_method_description list[];
1338 };
1339*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001340llvm::Constant *
1341CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1342 std::vector<llvm::Constant*> Desc(2);
1343 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1344 ObjCTypes.SelectorPtrTy);
1345 Desc[1] = GetMethodVarType(MD);
1346 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1347 Desc);
1348}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001349
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001350llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1351 const char *Section,
1352 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001353 // Return null for empty list.
1354 if (Methods.empty())
1355 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1356
1357 std::vector<llvm::Constant*> Values(2);
1358 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1359 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1360 Methods.size());
1361 Values[1] = llvm::ConstantArray::get(AT, Methods);
1362 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1363
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001364 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001365 return llvm::ConstantExpr::getBitCast(GV,
1366 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001367}
1368
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001369/*
1370 struct _objc_category {
1371 char *category_name;
1372 char *class_name;
1373 struct _objc_method_list *instance_methods;
1374 struct _objc_method_list *class_methods;
1375 struct _objc_protocol_list *protocols;
1376 uint32_t size; // <rdar://4585769>
1377 struct _objc_property_list *instance_properties;
1378 };
1379 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001380void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001381 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001382
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001383 // FIXME: This is poor design, the OCD should have a pointer to the
1384 // category decl. Additionally, note that Category can be null for
1385 // the @implementation w/o an @interface case. Sema should just
1386 // create one for us as it does for @implementation so everyone else
1387 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001388 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001389 const ObjCCategoryDecl *Category =
1390 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001391 std::string ExtName(Interface->getNameAsString() + "_" +
1392 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001393
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001394 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1395 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1396 e = OCD->instmeth_end(); i != e; ++i) {
1397 // Instance methods should always be defined.
1398 InstanceMethods.push_back(GetMethodConstant(*i));
1399 }
1400 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1401 e = OCD->classmeth_end(); i != e; ++i) {
1402 // Class methods should always be defined.
1403 ClassMethods.push_back(GetMethodConstant(*i));
1404 }
1405
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001406 std::vector<llvm::Constant*> Values(7);
1407 Values[0] = GetClassName(OCD->getIdentifier());
1408 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001409 Values[2] =
1410 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1411 ExtName,
1412 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001413 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001414 Values[3] =
1415 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001416 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001417 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001418 if (Category) {
1419 Values[4] =
1420 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1421 Category->protocol_begin(),
1422 Category->protocol_end());
1423 } else {
1424 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1425 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001426 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001427
1428 // If there is no category @interface then there can be no properties.
1429 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001430 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001431 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001432 } else {
1433 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1434 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001435
1436 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1437 Values);
1438
1439 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001440 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1441 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001442 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001443 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001444}
1445
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001446// FIXME: Get from somewhere?
1447enum ClassFlags {
1448 eClassFlags_Factory = 0x00001,
1449 eClassFlags_Meta = 0x00002,
1450 // <rdr://5142207>
1451 eClassFlags_HasCXXStructors = 0x02000,
1452 eClassFlags_Hidden = 0x20000,
1453 eClassFlags_ABI2_Hidden = 0x00010,
1454 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1455};
1456
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001457/*
1458 struct _objc_class {
1459 Class isa;
1460 Class super_class;
1461 const char *name;
1462 long version;
1463 long info;
1464 long instance_size;
1465 struct _objc_ivar_list *ivars;
1466 struct _objc_method_list *methods;
1467 struct _objc_cache *cache;
1468 struct _objc_protocol_list *protocols;
1469 // Objective-C 1.0 extensions (<rdr://4585769>)
1470 const char *ivar_layout;
1471 struct _objc_class_ext *ext;
1472 };
1473
1474 See EmitClassExtension();
1475 */
1476void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001477 DefinedSymbols.insert(ID->getIdentifier());
1478
Chris Lattner8ec03f52008-11-24 03:54:41 +00001479 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001480 // FIXME: Gross
1481 ObjCInterfaceDecl *Interface =
1482 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001483 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001484 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001485 Interface->protocol_begin(),
1486 Interface->protocol_end());
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())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001882 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1883
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001884 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001885 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1886 // FIXME: The "field no" for bitfields is something completely
1887 // different; it is the offset in multiples of the base type size!
1888 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1889 const llvm::Type *Ty =
1890 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1891 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1892 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001893}
1894
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001895/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001896uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1897 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001898 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001899 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001900 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1901 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001902}
1903
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001904llvm::GlobalVariable *
1905CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1906 llvm::Constant *Init,
1907 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001908 unsigned Align,
1909 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001910 const llvm::Type *Ty = Init->getType();
1911 llvm::GlobalVariable *GV =
1912 new llvm::GlobalVariable(Ty, false,
1913 llvm::GlobalValue::InternalLinkage,
1914 Init,
1915 Name,
1916 &CGM.getModule());
1917 if (Section)
1918 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001919 if (Align)
1920 GV->setAlignment(Align);
1921 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001922 UsedGlobals.push_back(GV);
1923 return GV;
1924}
1925
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001926llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001927 // Abuse this interface function as a place to finalize.
1928 FinishModule();
1929
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001930 return NULL;
1931}
1932
Chris Lattner74391b42009-03-22 21:03:39 +00001933llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001934 return ObjCTypes.GetPropertyFn;
1935}
1936
Chris Lattner74391b42009-03-22 21:03:39 +00001937llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001938 return ObjCTypes.SetPropertyFn;
1939}
1940
Chris Lattner74391b42009-03-22 21:03:39 +00001941llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001942 return ObjCTypes.EnumerationMutationFn;
1943}
1944
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001945/*
1946
1947Objective-C setjmp-longjmp (sjlj) Exception Handling
1948--
1949
1950The basic framework for a @try-catch-finally is as follows:
1951{
1952 objc_exception_data d;
1953 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001954 bool _call_try_exit = true;
1955
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001956 objc_exception_try_enter(&d);
1957 if (!setjmp(d.jmp_buf)) {
1958 ... try body ...
1959 } else {
1960 // exception path
1961 id _caught = objc_exception_extract(&d);
1962
1963 // enter new try scope for handlers
1964 if (!setjmp(d.jmp_buf)) {
1965 ... match exception and execute catch blocks ...
1966
1967 // fell off end, rethrow.
1968 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001969 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001970 } else {
1971 // exception in catch block
1972 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001973 _call_try_exit = false;
1974 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001975 }
1976 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001977 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001978
1979finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001980 if (_call_try_exit)
1981 objc_exception_try_exit(&d);
1982
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001983 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001984 ... dispatch to finally destination ...
1985
1986finally_rethrow:
1987 objc_exception_throw(_rethrow);
1988
1989finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001990}
1991
1992This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001993uses _rethrow to determine if objc_exception_try_exit should be called
1994and if the object should be rethrown. This breaks in the face of
1995throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001996
1997We specialize this framework for a few particular circumstances:
1998
1999 - If there are no catch blocks, then we avoid emitting the second
2000 exception handling context.
2001
2002 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2003 e)) we avoid emitting the code to rethrow an uncaught exception.
2004
2005 - FIXME: If there is no @finally block we can do a few more
2006 simplifications.
2007
2008Rethrows and Jumps-Through-Finally
2009--
2010
2011Support for implicit rethrows and jumping through the finally block is
2012handled by storing the current exception-handling context in
2013ObjCEHStack.
2014
Daniel Dunbar898d5082008-09-30 01:06:03 +00002015In order to implement proper @finally semantics, we support one basic
2016mechanism for jumping through the finally block to an arbitrary
2017destination. Constructs which generate exits from a @try or @catch
2018block use this mechanism to implement the proper semantics by chaining
2019jumps, as necessary.
2020
2021This mechanism works like the one used for indirect goto: we
2022arbitrarily assign an ID to each destination and store the ID for the
2023destination in a variable prior to entering the finally block. At the
2024end of the finally block we simply create a switch to the proper
2025destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002026
2027Code gen for @synchronized(expr) stmt;
2028Effectively generating code for:
2029objc_sync_enter(expr);
2030@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002031*/
2032
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002033void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2034 const Stmt &S) {
2035 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002036 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002037 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002038 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002039 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2040 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2041 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002042
2043 // For @synchronized, call objc_sync_enter(sync.expr). The
2044 // evaluation of the expression must occur before we enter the
2045 // @synchronized. We can safely avoid a temp here because jumps into
2046 // @synchronized are illegal & this will dominate uses.
2047 llvm::Value *SyncArg = 0;
2048 if (!isTry) {
2049 SyncArg =
2050 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2051 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002052 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002053 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002054
2055 // Push an EH context entry, used for handling rethrows and jumps
2056 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002057 CGF.PushCleanupBlock(FinallyBlock);
2058
Anders Carlsson273558f2009-02-07 21:37:21 +00002059 CGF.ObjCEHValueStack.push_back(0);
2060
Daniel Dunbar898d5082008-09-30 01:06:03 +00002061 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002062 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2063 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002064 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2065 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002066 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2067 "_call_try_exit");
2068 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2069
Anders Carlsson80f25672008-09-09 17:59:25 +00002070 // Enter a new try block and call setjmp.
2071 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2072 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2073 "jmpbufarray");
2074 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2075 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2076 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002077
Daniel Dunbar55e87422008-11-11 02:29:29 +00002078 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2079 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002080 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002081 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002082
2083 // Emit the @try block.
2084 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002085 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2086 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002087 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002088
2089 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002090 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002091
2092 // Retrieve the exception object. We may emit multiple blocks but
2093 // nothing can cross this so the value is already in SSA form.
2094 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2095 ExceptionData,
2096 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002097 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002098 if (!isTry)
2099 {
2100 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002101 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002102 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002103 }
2104 else if (const ObjCAtCatchStmt* CatchStmt =
2105 cast<ObjCAtTryStmt>(S).getCatchStmts())
2106 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002107 // Enter a new exception try block (in case a @catch block throws
2108 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002109 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002110
Anders Carlsson80f25672008-09-09 17:59:25 +00002111 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2112 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002113 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002114
Daniel Dunbar55e87422008-11-11 02:29:29 +00002115 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2116 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002117 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002118
2119 CGF.EmitBlock(CatchBlock);
2120
Daniel Dunbar55e40722008-09-27 07:03:52 +00002121 // Handle catch list. As a special case we check if everything is
2122 // matched and avoid generating code for falling off the end if
2123 // so.
2124 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002125 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002126 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002127
Steve Naroff7ba138a2009-03-03 19:52:17 +00002128 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002129 const PointerType *PT = 0;
2130
Anders Carlsson80f25672008-09-09 17:59:25 +00002131 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002132 if (!CatchParam) {
2133 AllMatched = true;
2134 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002135 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002136
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002137 // catch(id e) always matches.
2138 // FIXME: For the time being we also match id<X>; this should
2139 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002140 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002141 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002142 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002143 }
2144
Daniel Dunbar55e40722008-09-27 07:03:52 +00002145 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002146 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002147 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002148 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002149 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002150 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002151
Anders Carlssondde0a942008-09-11 09:15:33 +00002152 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002153 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002154 break;
2155 }
2156
Daniel Dunbar129271a2008-09-27 07:36:24 +00002157 assert(PT && "Unexpected non-pointer type in @catch");
2158 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002159 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002160 assert(ObjCType && "Catch parameter must have Objective-C type!");
2161
2162 // Check if the @catch block matches the exception object.
2163 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2164
Anders Carlsson80f25672008-09-09 17:59:25 +00002165 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2166 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002167
Daniel Dunbar55e87422008-11-11 02:29:29 +00002168 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002169
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002170 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002171 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002172
2173 // Emit the @catch block.
2174 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002175 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002176 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002177
2178 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002179 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002180 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002181 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002182
2183 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002184 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002185
2186 CGF.EmitBlock(NextCatchBlock);
2187 }
2188
Daniel Dunbar55e40722008-09-27 07:03:52 +00002189 if (!AllMatched) {
2190 // None of the handlers caught the exception, so store it to be
2191 // rethrown at the end of the @finally block.
2192 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002193 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002194 }
2195
2196 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002197 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002198 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2199 ExceptionData),
2200 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002201 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002202 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002203 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002204 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002205 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002206 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002207 }
2208
Daniel Dunbar898d5082008-09-30 01:06:03 +00002209 // Pop the exception-handling stack entry. It is important to do
2210 // this now, because the code in the @finally block is not in this
2211 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002212 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2213
Anders Carlsson273558f2009-02-07 21:37:21 +00002214 CGF.ObjCEHValueStack.pop_back();
2215
Anders Carlsson80f25672008-09-09 17:59:25 +00002216 // Emit the @finally block.
2217 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002218 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2219
2220 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2221
2222 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002223 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002224
2225 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002226 if (isTry) {
2227 if (const ObjCAtFinallyStmt* FinallyStmt =
2228 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2229 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002230 } else {
2231 // Emit objc_sync_exit(expr); as finally's sole statement for
2232 // @synchronized.
2233 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002234 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002235
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002236 // Emit the switch block
2237 if (Info.SwitchBlock)
2238 CGF.EmitBlock(Info.SwitchBlock);
2239 if (Info.EndBlock)
2240 CGF.EmitBlock(Info.EndBlock);
2241
Daniel Dunbar898d5082008-09-30 01:06:03 +00002242 CGF.EmitBlock(FinallyRethrow);
2243 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2244 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002245 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002246
2247 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002248}
2249
2250void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002251 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002252 llvm::Value *ExceptionAsObject;
2253
2254 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2255 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2256 ExceptionAsObject =
2257 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2258 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002259 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002260 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002261 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002262 }
2263
2264 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002265 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002266
2267 // Clear the insertion point to indicate we are in unreachable code.
2268 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002269}
2270
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002271/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002272/// object: objc_read_weak (id *src)
2273///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002274llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002275 llvm::Value *AddrWeakObj)
2276{
Eli Friedman8339b352009-03-07 03:57:15 +00002277 const llvm::Type* DestTy =
2278 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002279 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002280 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002281 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002282 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002283 return read_weak;
2284}
2285
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002286/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2287/// objc_assign_weak (id src, id *dst)
2288///
2289void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2290 llvm::Value *src, llvm::Value *dst)
2291{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002292 const llvm::Type * SrcTy = src->getType();
2293 if (!isa<llvm::PointerType>(SrcTy)) {
2294 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2295 assert(Size <= 8 && "does not support size > 8");
2296 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2297 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002298 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2299 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002300 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2301 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002302 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002303 src, dst, "weakassign");
2304 return;
2305}
2306
Fariborz Jahanian58626502008-11-19 00:59:10 +00002307/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2308/// objc_assign_global (id src, id *dst)
2309///
2310void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2311 llvm::Value *src, llvm::Value *dst)
2312{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002313 const llvm::Type * SrcTy = src->getType();
2314 if (!isa<llvm::PointerType>(SrcTy)) {
2315 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2316 assert(Size <= 8 && "does not support size > 8");
2317 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2318 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002319 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2320 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002321 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2322 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002323 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2324 src, dst, "globalassign");
2325 return;
2326}
2327
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002328/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2329/// objc_assign_ivar (id src, id *dst)
2330///
2331void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2332 llvm::Value *src, llvm::Value *dst)
2333{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002334 const llvm::Type * SrcTy = src->getType();
2335 if (!isa<llvm::PointerType>(SrcTy)) {
2336 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2337 assert(Size <= 8 && "does not support size > 8");
2338 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2339 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002340 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2341 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002342 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2343 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2344 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2345 src, dst, "assignivar");
2346 return;
2347}
2348
Fariborz Jahanian58626502008-11-19 00:59:10 +00002349/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2350/// objc_assign_strongCast (id src, id *dst)
2351///
2352void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2353 llvm::Value *src, llvm::Value *dst)
2354{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002355 const llvm::Type * SrcTy = src->getType();
2356 if (!isa<llvm::PointerType>(SrcTy)) {
2357 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2358 assert(Size <= 8 && "does not support size > 8");
2359 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2360 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002361 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2362 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002363 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2364 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002365 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2366 src, dst, "weakassign");
2367 return;
2368}
2369
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002370/// EmitObjCValueForIvar - Code Gen for ivar reference.
2371///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002372LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2373 QualType ObjectTy,
2374 llvm::Value *BaseValue,
2375 const ObjCIvarDecl *Ivar,
2376 const FieldDecl *Field,
2377 unsigned CVRQualifiers) {
2378 if (Ivar->isBitField())
2379 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2380 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002381 // TODO: Add a special case for isa (index 0)
2382 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2383 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002384 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002385 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2386 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002387 LValue::SetObjCIvar(LV, true);
2388 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002389}
2390
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002391llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2392 ObjCInterfaceDecl *Interface,
2393 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002394 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002395 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002396 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002397 return llvm::ConstantInt::get(
2398 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2399 Offset);
2400}
2401
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002402/* *** Private Interface *** */
2403
2404/// EmitImageInfo - Emit the image info marker used to encode some module
2405/// level information.
2406///
2407/// See: <rdr://4810609&4810587&4810587>
2408/// struct IMAGE_INFO {
2409/// unsigned version;
2410/// unsigned flags;
2411/// };
2412enum ImageInfoFlags {
2413 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2414 eImageInfo_GarbageCollected = (1 << 1),
2415 eImageInfo_GCOnly = (1 << 2)
2416};
2417
2418void CGObjCMac::EmitImageInfo() {
2419 unsigned version = 0; // Version is unused?
2420 unsigned flags = 0;
2421
2422 // FIXME: Fix and continue?
2423 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2424 flags |= eImageInfo_GarbageCollected;
2425 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2426 flags |= eImageInfo_GCOnly;
2427
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002428 // Emitted as int[2];
2429 llvm::Constant *values[2] = {
2430 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2431 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2432 };
2433 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002434
2435 const char *Section;
2436 if (ObjCABI == 1)
2437 Section = "__OBJC, __image_info,regular";
2438 else
2439 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002440 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002441 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2442 llvm::ConstantArray::get(AT, values, 2),
2443 Section,
2444 0,
2445 true);
2446 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002447}
2448
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002449
2450// struct objc_module {
2451// unsigned long version;
2452// unsigned long size;
2453// const char *name;
2454// Symtab symtab;
2455// };
2456
2457// FIXME: Get from somewhere
2458static const int ModuleVersion = 7;
2459
2460void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002461 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002462
2463 std::vector<llvm::Constant*> Values(4);
2464 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2465 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002466 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002467 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002468 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002469 CreateMetadataVar("\01L_OBJC_MODULES",
2470 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2471 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002472 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002473}
2474
2475llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002476 unsigned NumClasses = DefinedClasses.size();
2477 unsigned NumCategories = DefinedCategories.size();
2478
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002479 // Return null if no symbols were defined.
2480 if (!NumClasses && !NumCategories)
2481 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2482
2483 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002484 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2485 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2486 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2487 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2488
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002489 // The runtime expects exactly the list of defined classes followed
2490 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002491 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002492 for (unsigned i=0; i<NumClasses; i++)
2493 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2494 ObjCTypes.Int8PtrTy);
2495 for (unsigned i=0; i<NumCategories; i++)
2496 Symbols[NumClasses + i] =
2497 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2498 ObjCTypes.Int8PtrTy);
2499
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002500 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002501 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002502 NumClasses + NumCategories),
2503 Symbols);
2504
2505 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2506
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002507 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002508 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2509 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002510 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002511 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2512}
2513
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002514llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002515 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002516 LazySymbols.insert(ID->getIdentifier());
2517
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002518 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2519
2520 if (!Entry) {
2521 llvm::Constant *Casted =
2522 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2523 ObjCTypes.ClassPtrTy);
2524 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002525 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2526 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002527 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002528 }
2529
2530 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002531}
2532
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002533llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002534 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2535
2536 if (!Entry) {
2537 llvm::Constant *Casted =
2538 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2539 ObjCTypes.SelectorPtrTy);
2540 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002541 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2542 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002543 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002544 }
2545
2546 return Builder.CreateLoad(Entry, false, "tmp");
2547}
2548
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002549llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002550 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002551
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002552 if (!Entry)
2553 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2554 llvm::ConstantArray::get(Ident->getName()),
2555 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002556 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002557
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002558 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002559}
2560
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002561/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2562/// interface declaration.
2563const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2564 const ObjCInterfaceDecl *OID) const {
2565 const llvm::Type *InterfaceTy =
2566 CGM.getTypes().ConvertType(
2567 CGM.getContext().getObjCInterfaceType(
2568 const_cast<ObjCInterfaceDecl*>(OID)));
2569 const llvm::StructLayout *Layout =
2570 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2571 return Layout;
2572}
2573
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002574/// GetIvarLayoutName - Returns a unique constant for the given
2575/// ivar layout bitmap.
2576llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2577 const ObjCCommonTypesHelper &ObjCTypes) {
2578 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2579}
2580
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002581void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2582 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002583 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002584 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002585 unsigned int BytePos, bool ForStrongLayout,
2586 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002587 bool IsUnion = (RD && RD->isUnion());
2588 uint64_t MaxUnionIvarSize = 0;
2589 uint64_t MaxSkippedUnionIvarSize = 0;
2590 FieldDecl *MaxField = 0;
2591 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002592 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002593 if (RecFields.empty())
2594 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002595 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002596 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002597 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2598 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2599
2600 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2601
2602 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002603 FieldDecl *Field = RecFields[i];
2604 // Skip over unnamed or bitfields
2605 if (!Field->getIdentifier() || Field->isBitField())
2606 continue;
2607 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002608 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002609 if (FQT->isUnionType())
2610 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002611 else
2612 assert(FQT->isRecordType() &&
2613 "only union/record is supported for ivar layout bitmap");
2614
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002615 const RecordType *RT = FQT->getAsRecordType();
2616 const RecordDecl *RD = RT->getDecl();
2617 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002618 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2619 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002620 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002621 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002622 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002623 ForStrongLayout, Index, SkIndex,
2624 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002625 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002626 continue;
2627 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002628
2629 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002630 const ConstantArrayType *CArray =
2631 dyn_cast_or_null<ConstantArrayType>(Array);
2632 assert(CArray && "only array with know element size is supported");
2633 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002634 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2635 const ConstantArrayType *CArray =
2636 dyn_cast_or_null<ConstantArrayType>(Array);
2637 FQT = CArray->getElementType();
2638 }
2639
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002640 assert(!FQT->isUnionType() &&
2641 "layout for array of unions not supported");
2642 if (FQT->isRecordType()) {
2643 uint64_t ElCount = CArray->getSize().getZExtValue();
2644 int OldIndex = Index;
2645 int OldSkIndex = SkIndex;
2646
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002647 // FIXME - Use a common routine with the above!
2648 const RecordType *RT = FQT->getAsRecordType();
2649 const RecordDecl *RD = RT->getDecl();
2650 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002651 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2652 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002653
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002654 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002655 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002656 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002657 ForStrongLayout, Index, SkIndex,
2658 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002659 TmpRecFields.clear();
2660
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002661 // Replicate layout information for each array element. Note that
2662 // one element is already done.
2663 uint64_t ElIx = 1;
2664 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2665 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002666 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002667 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2668 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002669 GC_IVAR gcivar;
2670 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2671 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2672 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002673 }
2674
Chris Lattnerf1690852009-03-31 08:48:01 +00002675 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002676 GC_IVAR skivar;
2677 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2678 skivar.ivar_size = SkipIvars[i].ivar_size;
2679 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002680 }
2681 }
2682 continue;
2683 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002684 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002685 // At this point, we are done with Record/Union and array there of.
2686 // For other arrays we are down to its element type.
2687 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2688 do {
2689 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2690 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2691 break;
2692 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002693 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002694 GCAttr = QualType::Strong;
2695 break;
2696 }
2697 else if (const PointerType *PT = FQT->getAsPointerType()) {
2698 FQT = PT->getPointeeType();
2699 }
2700 else {
2701 break;
2702 }
2703 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002704
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002705 if ((ForStrongLayout && GCAttr == QualType::Strong)
2706 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2707 if (IsUnion)
2708 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002709 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2710 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002711 if (UnionIvarSize > MaxUnionIvarSize)
2712 {
2713 MaxUnionIvarSize = UnionIvarSize;
2714 MaxField = Field;
2715 }
2716 }
2717 else
2718 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002719 GC_IVAR gcivar;
2720 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2721 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2722 WordSizeInBits;
2723 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002724 }
2725 }
2726 else if ((ForStrongLayout &&
2727 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2728 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2729 if (IsUnion)
2730 {
2731 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2732 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2733 {
2734 MaxSkippedUnionIvarSize = UnionIvarSize;
2735 MaxSkippedField = Field;
2736 }
2737 }
2738 else
2739 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002740 GC_IVAR skivar;
2741 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2742 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2743 WordSizeInBits;
2744 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002745 }
2746 }
2747 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002748 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002749 GC_IVAR gcivar;
2750 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2751 gcivar.ivar_size = MaxUnionIvarSize;
2752 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002753 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002754
2755 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002756 GC_IVAR skivar;
2757 skivar.ivar_bytepos = BytePos +
2758 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2759 skivar.ivar_size = MaxSkippedUnionIvarSize;
2760 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002761 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002762}
2763
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002764static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002765IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002766{
2767 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2768 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2769
2770 if (sa < sb)
2771 return -1;
2772 if (sa > sb)
2773 return 1;
2774 return 0;
2775}
2776
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002777/// BuildIvarLayout - Builds ivar layout bitmap for the class
2778/// implementation for the __strong or __weak case.
2779/// The layout map displays which words in ivar list must be skipped
2780/// and which must be scanned by GC (see below). String is built of bytes.
2781/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2782/// of words to skip and right nibble is count of words to scan. So, each
2783/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2784/// represented by a 0x00 byte which also ends the string.
2785/// 1. when ForStrongLayout is true, following ivars are scanned:
2786/// - id, Class
2787/// - object *
2788/// - __strong anything
2789///
2790/// 2. When ForStrongLayout is false, following ivars are scanned:
2791/// - __weak anything
2792///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002793llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002794 const ObjCImplementationDecl *OMD,
2795 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002796 int Index = -1;
2797 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002798 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002799 int SkipScan;
2800 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002801 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2802 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2803 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002804
Chris Lattnerf1690852009-03-31 08:48:01 +00002805 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002806 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002807 CGM.getContext().CollectObjCIvars(OI, RecFields);
2808 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002809 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002810
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002811 SkipIvars.clear();
2812 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002813
2814 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002815 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2816 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002817 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002818 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002819
2820 // Sort on byte position in case we encounterred a union nested in
2821 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002822 if (hasUnion && !IvarsInfo.empty())
2823 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2824 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002825 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2826
2827 // Build the string of skip/scan nibbles
2828 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002829 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002830 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002831 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002832 if (IvarsInfo[0].ivar_bytepos == 0) {
2833 WordsToSkip = 0;
2834 WordsToScan = IvarsInfo[0].ivar_size;
2835 }
2836 else {
2837 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2838 WordsToScan = IvarsInfo[0].ivar_size;
2839 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002840 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002841 {
2842 unsigned int TailPrevGCObjC =
2843 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2844 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2845 {
2846 // consecutive 'scanned' object pointers.
2847 WordsToScan += IvarsInfo[i].ivar_size;
2848 }
2849 else
2850 {
2851 // Skip over 'gc'able object pointer which lay over each other.
2852 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2853 continue;
2854 // Must skip over 1 or more words. We save current skip/scan values
2855 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002856 SKIP_SCAN SkScan;
2857 SkScan.skip = WordsToSkip;
2858 SkScan.scan = WordsToScan;
2859 SkipScanIvars.push_back(SkScan); ++SkipScan;
2860
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002861 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002862 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2863 SkScan.scan = 0;
2864 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002865 WordsToSkip = 0;
2866 WordsToScan = IvarsInfo[i].ivar_size;
2867 }
2868 }
2869 if (WordsToScan > 0)
2870 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002871 SKIP_SCAN SkScan;
2872 SkScan.skip = WordsToSkip;
2873 SkScan.scan = WordsToScan;
2874 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002875 }
2876
2877 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002878 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002879 {
2880 int LastByteSkipped =
2881 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2882 int LastByteScanned =
2883 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2884 BytesSkipped = (LastByteSkipped > LastByteScanned);
2885 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2886 if (BytesSkipped)
2887 {
2888 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002889 SKIP_SCAN SkScan;
2890 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2891 SkScan.scan = 0;
2892 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002893 }
2894 }
2895 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2896 // as 0xMN.
2897 for (int i = 0; i <= SkipScan; i++)
2898 {
2899 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2900 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2901 // 0xM0 followed by 0x0N detected.
2902 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2903 for (int j = i+1; j < SkipScan; j++)
2904 SkipScanIvars[j] = SkipScanIvars[j+1];
2905 --SkipScan;
2906 }
2907 }
2908
2909 // Generate the string.
2910 std::string BitMap;
2911 for (int i = 0; i <= SkipScan; i++)
2912 {
2913 unsigned char byte;
2914 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2915 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2916 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2917 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2918
2919 if (skip_small > 0 || skip_big > 0)
2920 BytesSkipped = true;
2921 // first skip big.
2922 for (unsigned int ix = 0; ix < skip_big; ix++)
2923 BitMap += (unsigned char)(0xf0);
2924
2925 // next (skip small, scan)
2926 if (skip_small)
2927 {
2928 byte = skip_small << 4;
2929 if (scan_big > 0)
2930 {
2931 byte |= 0xf;
2932 --scan_big;
2933 }
2934 else if (scan_small)
2935 {
2936 byte |= scan_small;
2937 scan_small = 0;
2938 }
2939 BitMap += byte;
2940 }
2941 // next scan big
2942 for (unsigned int ix = 0; ix < scan_big; ix++)
2943 BitMap += (unsigned char)(0x0f);
2944 // last scan small
2945 if (scan_small)
2946 {
2947 byte = scan_small;
2948 BitMap += byte;
2949 }
2950 }
2951 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002952 unsigned char zero = 0;
2953 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002954 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2955 // final layout.
2956 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002957 return llvm::Constant::getNullValue(PtrTy);
2958 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2959 llvm::ConstantArray::get(BitMap.c_str()),
2960 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002961 1, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002962 // FIXME. Need a commomand-line option for this eventually.
2963 if (ForStrongLayout)
2964 printf("\nstrong ivar layout: ");
2965 else
2966 printf("\nweak ivar layout: ");
2967 const unsigned char *s = (unsigned char*)BitMap.c_str();
2968 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002969 if (!(s[i] & 0xf0))
2970 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2971 else
2972 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002973 printf("\n");
2974
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002975 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002976}
2977
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002978llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002979 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2980
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002981 // FIXME: Avoid std::string copying.
2982 if (!Entry)
2983 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2984 llvm::ConstantArray::get(Sel.getAsString()),
2985 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002986 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002987
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002988 return getConstantGEP(Entry, 0, 0);
2989}
2990
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002991// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002992llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002993 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2994}
2995
2996// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002997llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002998 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2999}
3000
Devang Patel7794bb82009-03-04 18:21:39 +00003001llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
3002 std::string TypeStr;
3003 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3004
3005 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003006
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003007 if (!Entry)
3008 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3009 llvm::ConstantArray::get(TypeStr),
3010 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003011 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003012
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003013 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003014}
3015
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003016llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003017 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003018 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3019 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003020
3021 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3022
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003023 if (!Entry)
3024 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3025 llvm::ConstantArray::get(TypeStr),
3026 "__TEXT,__cstring,cstring_literals",
3027 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003028
3029 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003030}
3031
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003032// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003033llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003034 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3035
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003036 if (!Entry)
3037 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3038 llvm::ConstantArray::get(Ident->getName()),
3039 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003040 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003041
3042 return getConstantGEP(Entry, 0, 0);
3043}
3044
3045// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003046// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003047llvm::Constant *
3048 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3049 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003050 std::string TypeStr;
3051 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003052 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3053}
3054
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003055void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3056 const ObjCContainerDecl *CD,
3057 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003058 NameOut = '\01';
3059 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003060 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003061 assert (CD && "Missing container decl in GetNameForMethod");
3062 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003063 if (const ObjCCategoryImplDecl *CID =
3064 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3065 NameOut += '(';
3066 NameOut += CID->getNameAsString();
3067 NameOut+= ')';
3068 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003069 NameOut += ' ';
3070 NameOut += D->getSelector().getAsString();
3071 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003072}
3073
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003074/// GetFirstIvarInRecord - This routine returns the record for the
3075/// implementation of the fiven class OID. It also returns field
3076/// corresponding to the first ivar in the class in FIV. It also
3077/// returns the one before the first ivar.
3078///
3079const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3080 const ObjCInterfaceDecl *OID,
3081 RecordDecl::field_iterator &FIV,
3082 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003083 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3084 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003085 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003086 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3087 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003088 while (countSuperClassIvars-- > 0) {
3089 pfield = ifield;
3090 ++ifield;
3091 }
3092 FIV = ifield;
3093 PIV = pfield;
3094 return RD;
3095}
3096
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003097void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003098 EmitModuleInfo();
3099
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003100 // Emit the dummy bodies for any protocols which were referenced but
3101 // never defined.
3102 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3103 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3104 if (i->second->hasInitializer())
3105 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003106
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003107 std::vector<llvm::Constant*> Values(5);
3108 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3109 Values[1] = GetClassName(i->first);
3110 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3111 Values[3] = Values[4] =
3112 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3113 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3114 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3115 Values));
3116 }
3117
3118 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003119 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003120 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003121 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003122 }
3123
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003124 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003125 llvm::GlobalValue *GV =
3126 new llvm::GlobalVariable(AT, false,
3127 llvm::GlobalValue::AppendingLinkage,
3128 llvm::ConstantArray::get(AT, Used),
3129 "llvm.used",
3130 &CGM.getModule());
3131
3132 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003133
3134 // Add assembler directives to add lazy undefined symbol references
3135 // for classes which are referenced but not defined. This is
3136 // important for correct linker interaction.
3137
3138 // FIXME: Uh, this isn't particularly portable.
3139 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003140
3141 if (!CGM.getModule().getModuleInlineAsm().empty())
3142 s << "\n";
3143
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003144 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3145 e = LazySymbols.end(); i != e; ++i) {
3146 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3147 }
3148 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3149 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003150 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003151 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3152 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003153
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003154 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003155}
3156
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003157CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003158 : CGObjCCommonMac(cgm),
3159 ObjCTypes(cgm)
3160{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003161 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003162 ObjCABI = 2;
3163}
3164
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003165/* *** */
3166
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003167ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3168: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003169{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003170 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3171 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003172
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003173 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003174 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003175 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003176 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003177 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3178
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003179 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003180 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003181 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003182
3183 // FIXME: It would be nice to unify this with the opaque type, so
3184 // that the IR comes out a bit cleaner.
3185 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3186 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003187
3188 // I'm not sure I like this. The implicit coordination is a bit
3189 // gross. We should solve this in a reasonable fashion because this
3190 // is a pretty common task (match some runtime data structure with
3191 // an LLVM data structure).
3192
3193 // FIXME: This is leaked.
3194 // FIXME: Merge with rewriter code?
3195
3196 // struct _objc_super {
3197 // id self;
3198 // Class cls;
3199 // }
3200 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3201 SourceLocation(),
3202 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003203 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3204 Ctx.getObjCIdType(), 0, false));
3205 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3206 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003207 RD->completeDefinition(Ctx);
3208
3209 SuperCTy = Ctx.getTagDeclType(RD);
3210 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3211
3212 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003213 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3214
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003215 // struct _prop_t {
3216 // char *name;
3217 // char *attributes;
3218 // }
3219 PropertyTy = llvm::StructType::get(Int8PtrTy,
3220 Int8PtrTy,
3221 NULL);
3222 CGM.getModule().addTypeName("struct._prop_t",
3223 PropertyTy);
3224
3225 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003226 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003227 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003228 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003229 // }
3230 PropertyListTy = llvm::StructType::get(IntTy,
3231 IntTy,
3232 llvm::ArrayType::get(PropertyTy, 0),
3233 NULL);
3234 CGM.getModule().addTypeName("struct._prop_list_t",
3235 PropertyListTy);
3236 // struct _prop_list_t *
3237 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3238
3239 // struct _objc_method {
3240 // SEL _cmd;
3241 // char *method_type;
3242 // char *_imp;
3243 // }
3244 MethodTy = llvm::StructType::get(SelectorPtrTy,
3245 Int8PtrTy,
3246 Int8PtrTy,
3247 NULL);
3248 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003249
3250 // struct _objc_cache *
3251 CacheTy = llvm::OpaqueType::get();
3252 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3253 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003254
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003255 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003256
3257 QualType IdType = Ctx.getObjCIdType();
3258 QualType SelType = Ctx.getObjCSelType();
3259 llvm::SmallVector<QualType,16> Params;
3260 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003261
3262 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003263 Params.push_back(IdType);
3264 Params.push_back(SelType);
3265 Params.push_back(Ctx.LongTy);
3266 Params.push_back(Ctx.BoolTy);
3267 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3268 false);
3269 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003270
3271 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3272 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003273 Params.push_back(IdType);
3274 Params.push_back(SelType);
3275 Params.push_back(Ctx.LongTy);
3276 Params.push_back(IdType);
3277 Params.push_back(Ctx.BoolTy);
3278 Params.push_back(Ctx.BoolTy);
3279 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3280 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3281
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003282 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003283
3284 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003285 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003286 Params.push_back(IdType);
3287 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3288 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3289 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003290
3291 // gc's API
3292 // id objc_read_weak (id *)
3293 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003294 Params.push_back(Ctx.getPointerType(IdType));
3295 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3296 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3297
Chris Lattner96508e12009-04-17 22:12:36 +00003298 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003299 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003300 Params.push_back(IdType);
3301 Params.push_back(Ctx.getPointerType(IdType));
3302
3303 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003304 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3305 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3306 GcAssignStrongCastFn =
3307 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003308
3309 // void objc_exception_throw(id)
3310 Params.clear();
3311 Params.push_back(IdType);
3312
3313 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003314 ExceptionThrowFn =
3315 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003316
3317 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003318 // void objc_sync_exit (id)
3319 Params.clear();
3320 Params.push_back(IdType);
3321
3322 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003323 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003324}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003325
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003326ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3327 : ObjCCommonTypesHelper(cgm)
3328{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003329 // struct _objc_method_description {
3330 // SEL name;
3331 // char *types;
3332 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003333 MethodDescriptionTy =
3334 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003335 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003336 NULL);
3337 CGM.getModule().addTypeName("struct._objc_method_description",
3338 MethodDescriptionTy);
3339
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003340 // struct _objc_method_description_list {
3341 // int count;
3342 // struct _objc_method_description[1];
3343 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003344 MethodDescriptionListTy =
3345 llvm::StructType::get(IntTy,
3346 llvm::ArrayType::get(MethodDescriptionTy, 0),
3347 NULL);
3348 CGM.getModule().addTypeName("struct._objc_method_description_list",
3349 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003350
3351 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003352 MethodDescriptionListPtrTy =
3353 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3354
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003355 // Protocol description structures
3356
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003357 // struct _objc_protocol_extension {
3358 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3359 // struct _objc_method_description_list *optional_instance_methods;
3360 // struct _objc_method_description_list *optional_class_methods;
3361 // struct _objc_property_list *instance_properties;
3362 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003363 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003364 llvm::StructType::get(IntTy,
3365 MethodDescriptionListPtrTy,
3366 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003367 PropertyListPtrTy,
3368 NULL);
3369 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3370 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003371
3372 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003373 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3374
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003375 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003376
3377 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3378 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3379
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003380 const llvm::Type *T =
3381 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3382 LongTy,
3383 llvm::ArrayType::get(ProtocolTyHolder, 0),
3384 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003385 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3386
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003387 // struct _objc_protocol {
3388 // struct _objc_protocol_extension *isa;
3389 // char *protocol_name;
3390 // struct _objc_protocol **_objc_protocol_list;
3391 // struct _objc_method_description_list *instance_methods;
3392 // struct _objc_method_description_list *class_methods;
3393 // }
3394 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003395 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003396 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3397 MethodDescriptionListPtrTy,
3398 MethodDescriptionListPtrTy,
3399 NULL);
3400 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3401
3402 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3403 CGM.getModule().addTypeName("struct._objc_protocol_list",
3404 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003405 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003406 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3407
3408 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003409 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003410 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003411
3412 // Class description structures
3413
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003414 // struct _objc_ivar {
3415 // char *ivar_name;
3416 // char *ivar_type;
3417 // int ivar_offset;
3418 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003419 IvarTy = llvm::StructType::get(Int8PtrTy,
3420 Int8PtrTy,
3421 IntTy,
3422 NULL);
3423 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3424
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003425 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003426 IvarListTy = llvm::OpaqueType::get();
3427 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3428 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3429
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003430 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003431 MethodListTy = llvm::OpaqueType::get();
3432 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3433 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3434
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003435 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003436 ClassExtensionTy =
3437 llvm::StructType::get(IntTy,
3438 Int8PtrTy,
3439 PropertyListPtrTy,
3440 NULL);
3441 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3442 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3443
3444 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3445
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003446 // struct _objc_class {
3447 // Class isa;
3448 // Class super_class;
3449 // char *name;
3450 // long version;
3451 // long info;
3452 // long instance_size;
3453 // struct _objc_ivar_list *ivars;
3454 // struct _objc_method_list *methods;
3455 // struct _objc_cache *cache;
3456 // struct _objc_protocol_list *protocols;
3457 // char *ivar_layout;
3458 // struct _objc_class_ext *ext;
3459 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003460 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3461 llvm::PointerType::getUnqual(ClassTyHolder),
3462 Int8PtrTy,
3463 LongTy,
3464 LongTy,
3465 LongTy,
3466 IvarListPtrTy,
3467 MethodListPtrTy,
3468 CachePtrTy,
3469 ProtocolListPtrTy,
3470 Int8PtrTy,
3471 ClassExtensionPtrTy,
3472 NULL);
3473 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3474
3475 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3476 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3477 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3478
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003479 // struct _objc_category {
3480 // char *category_name;
3481 // char *class_name;
3482 // struct _objc_method_list *instance_method;
3483 // struct _objc_method_list *class_method;
3484 // uint32_t size; // sizeof(struct _objc_category)
3485 // struct _objc_property_list *instance_properties;// category's @property
3486 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003487 CategoryTy = llvm::StructType::get(Int8PtrTy,
3488 Int8PtrTy,
3489 MethodListPtrTy,
3490 MethodListPtrTy,
3491 ProtocolListPtrTy,
3492 IntTy,
3493 PropertyListPtrTy,
3494 NULL);
3495 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3496
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003497 // Global metadata structures
3498
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003499 // struct _objc_symtab {
3500 // long sel_ref_cnt;
3501 // SEL *refs;
3502 // short cls_def_cnt;
3503 // short cat_def_cnt;
3504 // char *defs[cls_def_cnt + cat_def_cnt];
3505 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003506 SymtabTy = llvm::StructType::get(LongTy,
3507 SelectorPtrTy,
3508 ShortTy,
3509 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003510 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003511 NULL);
3512 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3513 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3514
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003515 // struct _objc_module {
3516 // long version;
3517 // long size; // sizeof(struct _objc_module)
3518 // char *name;
3519 // struct _objc_symtab* symtab;
3520 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003521 ModuleTy =
3522 llvm::StructType::get(LongTy,
3523 LongTy,
3524 Int8PtrTy,
3525 SymtabPtrTy,
3526 NULL);
3527 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003528
Daniel Dunbar49f66022008-09-24 03:38:44 +00003529 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003530
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003531 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003532 std::vector<const llvm::Type*> Params;
3533 Params.push_back(ObjectPtrTy);
3534 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003535 MessageSendFn =
3536 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3537 Params,
3538 true),
3539 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003540
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003541 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003542 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003543 Params.push_back(ObjectPtrTy);
3544 Params.push_back(SelectorPtrTy);
3545 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003546 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3547 Params,
3548 true),
3549 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003550
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003551 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003552 Params.clear();
3553 Params.push_back(ObjectPtrTy);
3554 Params.push_back(SelectorPtrTy);
3555 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003556 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003557 MessageSendFpretFn =
3558 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3559 Params,
3560 true),
3561 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003562
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003563 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003564 Params.clear();
3565 Params.push_back(SuperPtrTy);
3566 Params.push_back(SelectorPtrTy);
3567 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003568 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3569 Params,
3570 true),
3571 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003572
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003573 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3574 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003575 Params.clear();
3576 Params.push_back(Int8PtrTy);
3577 Params.push_back(SuperPtrTy);
3578 Params.push_back(SelectorPtrTy);
3579 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003580 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3581 Params,
3582 true),
3583 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003584
3585 // There is no objc_msgSendSuper_fpret? How can that work?
3586 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003587
Anders Carlsson124526b2008-09-09 10:10:21 +00003588 // FIXME: This is the size of the setjmp buffer and should be
3589 // target specific. 18 is what's used on 32-bit X86.
3590 uint64_t SetJmpBufferSize = 18;
3591
3592 // Exceptions
3593 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003594 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003595
3596 ExceptionDataTy =
3597 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3598 SetJmpBufferSize),
3599 StackPtrTy, NULL);
3600 CGM.getModule().addTypeName("struct._objc_exception_data",
3601 ExceptionDataTy);
3602
3603 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003604 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3605 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003606 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3607 Params,
3608 false),
3609 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003610 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003611 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3612 Params,
3613 false),
3614 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003615 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003616 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3617 Params,
3618 false),
3619 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003620
3621 Params.clear();
3622 Params.push_back(ClassPtrTy);
3623 Params.push_back(ObjectPtrTy);
3624 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003625 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3626 Params,
3627 false),
3628 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003629
Anders Carlsson124526b2008-09-09 10:10:21 +00003630 Params.clear();
3631 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3632 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003633 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3634 Params,
3635 false),
3636 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003637
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003638}
3639
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003640ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003641: ObjCCommonTypesHelper(cgm)
3642{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003643 // struct _method_list_t {
3644 // uint32_t entsize; // sizeof(struct _objc_method)
3645 // uint32_t method_count;
3646 // struct _objc_method method_list[method_count];
3647 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003648 MethodListnfABITy = llvm::StructType::get(IntTy,
3649 IntTy,
3650 llvm::ArrayType::get(MethodTy, 0),
3651 NULL);
3652 CGM.getModule().addTypeName("struct.__method_list_t",
3653 MethodListnfABITy);
3654 // struct method_list_t *
3655 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003656
3657 // struct _protocol_t {
3658 // id isa; // NULL
3659 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003660 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003661 // const struct method_list_t * const instance_methods;
3662 // const struct method_list_t * const class_methods;
3663 // const struct method_list_t *optionalInstanceMethods;
3664 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003665 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003666 // const uint32_t size; // sizeof(struct _protocol_t)
3667 // const uint32_t flags; // = 0
3668 // }
3669
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003670 // Holder for struct _protocol_list_t *
3671 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3672
3673 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3674 Int8PtrTy,
3675 llvm::PointerType::getUnqual(
3676 ProtocolListTyHolder),
3677 MethodListnfABIPtrTy,
3678 MethodListnfABIPtrTy,
3679 MethodListnfABIPtrTy,
3680 MethodListnfABIPtrTy,
3681 PropertyListPtrTy,
3682 IntTy,
3683 IntTy,
3684 NULL);
3685 CGM.getModule().addTypeName("struct._protocol_t",
3686 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003687
3688 // struct _protocol_t*
3689 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003690
Fariborz Jahanianda320092009-01-29 19:24:30 +00003691 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003692 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003693 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003694 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003695 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3696 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003697 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003698 NULL);
3699 CGM.getModule().addTypeName("struct._objc_protocol_list",
3700 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003701 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3702 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003703
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003704 // struct _objc_protocol_list*
3705 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003706
3707 // struct _ivar_t {
3708 // unsigned long int *offset; // pointer to ivar offset location
3709 // char *name;
3710 // char *type;
3711 // uint32_t alignment;
3712 // uint32_t size;
3713 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003714 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3715 Int8PtrTy,
3716 Int8PtrTy,
3717 IntTy,
3718 IntTy,
3719 NULL);
3720 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3721
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003722 // struct _ivar_list_t {
3723 // uint32 entsize; // sizeof(struct _ivar_t)
3724 // uint32 count;
3725 // struct _iver_t list[count];
3726 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003727 IvarListnfABITy = llvm::StructType::get(IntTy,
3728 IntTy,
3729 llvm::ArrayType::get(
3730 IvarnfABITy, 0),
3731 NULL);
3732 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3733
3734 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003735
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003736 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003737 // uint32_t const flags;
3738 // uint32_t const instanceStart;
3739 // uint32_t const instanceSize;
3740 // uint32_t const reserved; // only when building for 64bit targets
3741 // const uint8_t * const ivarLayout;
3742 // const char *const name;
3743 // const struct _method_list_t * const baseMethods;
3744 // const struct _objc_protocol_list *const baseProtocols;
3745 // const struct _ivar_list_t *const ivars;
3746 // const uint8_t * const weakIvarLayout;
3747 // const struct _prop_list_t * const properties;
3748 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003749
3750 // FIXME. Add 'reserved' field in 64bit abi mode!
3751 ClassRonfABITy = llvm::StructType::get(IntTy,
3752 IntTy,
3753 IntTy,
3754 Int8PtrTy,
3755 Int8PtrTy,
3756 MethodListnfABIPtrTy,
3757 ProtocolListnfABIPtrTy,
3758 IvarListnfABIPtrTy,
3759 Int8PtrTy,
3760 PropertyListPtrTy,
3761 NULL);
3762 CGM.getModule().addTypeName("struct._class_ro_t",
3763 ClassRonfABITy);
3764
3765 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3766 std::vector<const llvm::Type*> Params;
3767 Params.push_back(ObjectPtrTy);
3768 Params.push_back(SelectorPtrTy);
3769 ImpnfABITy = llvm::PointerType::getUnqual(
3770 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3771
3772 // struct _class_t {
3773 // struct _class_t *isa;
3774 // struct _class_t * const superclass;
3775 // void *cache;
3776 // IMP *vtable;
3777 // struct class_ro_t *ro;
3778 // }
3779
3780 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3781 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3782 llvm::PointerType::getUnqual(ClassTyHolder),
3783 CachePtrTy,
3784 llvm::PointerType::getUnqual(ImpnfABITy),
3785 llvm::PointerType::getUnqual(
3786 ClassRonfABITy),
3787 NULL);
3788 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3789
3790 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3791 ClassnfABITy);
3792
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003793 // LLVM for struct _class_t *
3794 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3795
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003796 // struct _category_t {
3797 // const char * const name;
3798 // struct _class_t *const cls;
3799 // const struct _method_list_t * const instance_methods;
3800 // const struct _method_list_t * const class_methods;
3801 // const struct _protocol_list_t * const protocols;
3802 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003803 // }
3804 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003805 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003806 MethodListnfABIPtrTy,
3807 MethodListnfABIPtrTy,
3808 ProtocolListnfABIPtrTy,
3809 PropertyListPtrTy,
3810 NULL);
3811 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003812
3813 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003814 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3815 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003816
3817 // MessageRefTy - LLVM for:
3818 // struct _message_ref_t {
3819 // IMP messenger;
3820 // SEL name;
3821 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003822
3823 // First the clang type for struct _message_ref_t
3824 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3825 SourceLocation(),
3826 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003827 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3828 Ctx.VoidPtrTy, 0, false));
3829 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3830 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003831 RD->completeDefinition(Ctx);
3832
3833 MessageRefCTy = Ctx.getTagDeclType(RD);
3834 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3835 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003836
3837 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3838 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3839
3840 // SuperMessageRefTy - LLVM for:
3841 // struct _super_message_ref_t {
3842 // SUPER_IMP messenger;
3843 // SEL name;
3844 // };
3845 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3846 SelectorPtrTy,
3847 NULL);
3848 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3849
3850 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3851 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3852
3853 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3854 Params.clear();
3855 Params.push_back(ObjectPtrTy);
3856 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003857 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3858 Params,
3859 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003860 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003861 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003862 "objc_msgSend_fixup");
3863
3864 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3865 MessageSendFpretFixupFn =
3866 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3867 Params,
3868 true),
3869 "objc_msgSend_fpret_fixup");
3870
3871 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3872 MessageSendStretFixupFn =
3873 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3874 Params,
3875 true),
3876 "objc_msgSend_stret_fixup");
3877
3878 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3879 MessageSendIdFixupFn =
3880 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3881 Params,
3882 true),
3883 "objc_msgSendId_fixup");
3884
3885
3886 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3887 MessageSendIdStretFixupFn =
3888 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3889 Params,
3890 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003891 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003892
3893 // id objc_msgSendSuper2_fixup (struct objc_super *,
3894 // struct _super_message_ref_t*, ...)
3895 Params.clear();
3896 Params.push_back(SuperPtrTy);
3897 Params.push_back(SuperMessageRefPtrTy);
3898 MessageSendSuper2FixupFn =
3899 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3900 Params,
3901 true),
3902 "objc_msgSendSuper2_fixup");
3903
3904
3905 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3906 // struct _super_message_ref_t*, ...)
3907 MessageSendSuper2StretFixupFn =
3908 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3909 Params,
3910 true),
3911 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003912
3913 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003914 Params.push_back(Int8PtrTy);
3915 UnwindResumeOrRethrowFn =
3916 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3917 Params,
3918 false),
3919 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003920 ObjCBeginCatchFn =
3921 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3922 Params,
3923 false),
3924 "objc_begin_catch");
3925
3926 Params.clear();
3927 ObjCEndCatchFn =
3928 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3929 Params,
3930 false),
3931 "objc_end_catch");
3932
3933 // struct objc_typeinfo {
3934 // const void** vtable; // objc_ehtype_vtable + 2
3935 // const char* name; // c++ typeinfo string
3936 // Class cls;
3937 // };
3938 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3939 Int8PtrTy,
3940 ClassnfABIPtrTy,
3941 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003942 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003943 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003944}
3945
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003946llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3947 FinishNonFragileABIModule();
3948
3949 return NULL;
3950}
3951
3952void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3953 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003954
3955 // Build list of all implemented classe addresses in array
3956 // L_OBJC_LABEL_CLASS_$.
3957 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3958 // list of 'nonlazy' implementations (defined as those with a +load{}
3959 // method!!).
3960 unsigned NumClasses = DefinedClasses.size();
3961 if (NumClasses) {
3962 std::vector<llvm::Constant*> Symbols(NumClasses);
3963 for (unsigned i=0; i<NumClasses; i++)
3964 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3965 ObjCTypes.Int8PtrTy);
3966 llvm::Constant* Init =
3967 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3968 NumClasses),
3969 Symbols);
3970
3971 llvm::GlobalVariable *GV =
3972 new llvm::GlobalVariable(Init->getType(), false,
3973 llvm::GlobalValue::InternalLinkage,
3974 Init,
3975 "\01L_OBJC_LABEL_CLASS_$",
3976 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003977 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003978 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3979 UsedGlobals.push_back(GV);
3980 }
3981
3982 // Build list of all implemented category addresses in array
3983 // L_OBJC_LABEL_CATEGORY_$.
3984 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3985 // list of 'nonlazy' category implementations (defined as those with a +load{}
3986 // method!!).
3987 unsigned NumCategory = DefinedCategories.size();
3988 if (NumCategory) {
3989 std::vector<llvm::Constant*> Symbols(NumCategory);
3990 for (unsigned i=0; i<NumCategory; i++)
3991 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3992 ObjCTypes.Int8PtrTy);
3993 llvm::Constant* Init =
3994 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3995 NumCategory),
3996 Symbols);
3997
3998 llvm::GlobalVariable *GV =
3999 new llvm::GlobalVariable(Init->getType(), false,
4000 llvm::GlobalValue::InternalLinkage,
4001 Init,
4002 "\01L_OBJC_LABEL_CATEGORY_$",
4003 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004004 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004005 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4006 UsedGlobals.push_back(GV);
4007 }
4008
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004009 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4010 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4011 std::vector<llvm::Constant*> Values(2);
4012 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004013 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004014 // FIXME: Fix and continue?
4015 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4016 flags |= eImageInfo_GarbageCollected;
4017 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4018 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004019 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004020 llvm::Constant* Init = llvm::ConstantArray::get(
4021 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4022 Values);
4023 llvm::GlobalVariable *IMGV =
4024 new llvm::GlobalVariable(Init->getType(), false,
4025 llvm::GlobalValue::InternalLinkage,
4026 Init,
4027 "\01L_OBJC_IMAGE_INFO",
4028 &CGM.getModule());
4029 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4030 UsedGlobals.push_back(IMGV);
4031
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004032 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004033
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004034 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4035 e = UsedGlobals.end(); i != e; ++i) {
4036 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4037 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004038
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004039 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4040 llvm::GlobalValue *GV =
4041 new llvm::GlobalVariable(AT, false,
4042 llvm::GlobalValue::AppendingLinkage,
4043 llvm::ConstantArray::get(AT, Used),
4044 "llvm.used",
4045 &CGM.getModule());
4046
4047 GV->setSection("llvm.metadata");
4048
4049}
4050
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004051// Metadata flags
4052enum MetaDataDlags {
4053 CLS = 0x0,
4054 CLS_META = 0x1,
4055 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004056 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004057 CLS_EXCEPTION = 0x20
4058};
4059/// BuildClassRoTInitializer - generate meta-data for:
4060/// struct _class_ro_t {
4061/// uint32_t const flags;
4062/// uint32_t const instanceStart;
4063/// uint32_t const instanceSize;
4064/// uint32_t const reserved; // only when building for 64bit targets
4065/// const uint8_t * const ivarLayout;
4066/// const char *const name;
4067/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004068/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004069/// const struct _ivar_list_t *const ivars;
4070/// const uint8_t * const weakIvarLayout;
4071/// const struct _prop_list_t * const properties;
4072/// }
4073///
4074llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4075 unsigned flags,
4076 unsigned InstanceStart,
4077 unsigned InstanceSize,
4078 const ObjCImplementationDecl *ID) {
4079 std::string ClassName = ID->getNameAsString();
4080 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4081 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4082 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4083 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4084 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004085 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004086 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004087 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004088 // const struct _method_list_t * const baseMethods;
4089 std::vector<llvm::Constant*> Methods;
4090 std::string MethodListName("\01l_OBJC_$_");
4091 if (flags & CLS_META) {
4092 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4093 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4094 e = ID->classmeth_end(); i != e; ++i) {
4095 // Class methods should always be defined.
4096 Methods.push_back(GetMethodConstant(*i));
4097 }
4098 } else {
4099 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4100 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4101 e = ID->instmeth_end(); i != e; ++i) {
4102 // Instance methods should always be defined.
4103 Methods.push_back(GetMethodConstant(*i));
4104 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004105 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4106 e = ID->propimpl_end(); i != e; ++i) {
4107 ObjCPropertyImplDecl *PID = *i;
4108
4109 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4110 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4111
4112 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4113 if (llvm::Constant *C = GetMethodConstant(MD))
4114 Methods.push_back(C);
4115 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4116 if (llvm::Constant *C = GetMethodConstant(MD))
4117 Methods.push_back(C);
4118 }
4119 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004120 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004121 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004122 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004123
4124 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4125 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4126 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4127 + OID->getNameAsString(),
4128 OID->protocol_begin(),
4129 OID->protocol_end());
4130
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004131 if (flags & CLS_META)
4132 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4133 else
4134 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004135 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004136 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004137 if (flags & CLS_META)
4138 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4139 else
4140 Values[ 9] =
4141 EmitPropertyList(
4142 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4143 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004144 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4145 Values);
4146 llvm::GlobalVariable *CLASS_RO_GV =
4147 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4148 llvm::GlobalValue::InternalLinkage,
4149 Init,
4150 (flags & CLS_META) ?
4151 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4152 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4153 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004154 CLASS_RO_GV->setAlignment(
4155 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004156 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004157 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004158
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004159}
4160
4161/// BuildClassMetaData - This routine defines that to-level meta-data
4162/// for the given ClassName for:
4163/// struct _class_t {
4164/// struct _class_t *isa;
4165/// struct _class_t * const superclass;
4166/// void *cache;
4167/// IMP *vtable;
4168/// struct class_ro_t *ro;
4169/// }
4170///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004171llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4172 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004173 llvm::Constant *IsAGV,
4174 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004175 llvm::Constant *ClassRoGV,
4176 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004177 std::vector<llvm::Constant*> Values(5);
4178 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004179 Values[1] = SuperClassGV
4180 ? SuperClassGV
4181 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004182 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4183 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4184 Values[4] = ClassRoGV; // &CLASS_RO_GV
4185 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4186 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004187 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4188 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004189 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004190 GV->setAlignment(
4191 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004192 if (HiddenVisibility)
4193 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004194 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004195}
4196
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004197void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4198 std::string ClassName = ID->getNameAsString();
4199 if (!ObjCEmptyCacheVar) {
4200 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004201 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004202 false,
4203 llvm::GlobalValue::ExternalLinkage,
4204 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004205 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004206 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004207
4208 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004209 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004210 false,
4211 llvm::GlobalValue::ExternalLinkage,
4212 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004213 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004214 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004215 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004216 assert(ID->getClassInterface() &&
4217 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004218 uint32_t InstanceStart =
4219 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4220 uint32_t InstanceSize = InstanceStart;
4221 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004222 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4223 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004224
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004225 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004226
Daniel Dunbar04d40782009-04-14 06:00:08 +00004227 bool classIsHidden =
4228 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004229 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004230 flags |= OBJC2_CLS_HIDDEN;
4231 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004232 // class is root
4233 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004234 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004235 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004236 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004237 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004238 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4239 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4240 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004241 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004242 // work on super class metadata symbol.
4243 std::string SuperClassName =
4244 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004245 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004246 }
4247 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4248 InstanceStart,
4249 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004250 std::string TClassName = ObjCMetaClassName + ClassName;
4251 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004252 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4253 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004254
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004255 // Metadata for the class
4256 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004257 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004258 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004259
4260 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4261 flags |= CLS_EXCEPTION;
4262
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004263 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004264 flags |= CLS_ROOT;
4265 SuperClassGV = 0;
4266 }
4267 else {
4268 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004269 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004270 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004271 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004272 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004273 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004274 InstanceStart = InstanceSize = 0;
4275 if (ObjCInterfaceDecl *OID =
4276 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4277 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004278 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004279
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004280 RecordDecl::field_iterator firstField, lastField;
4281 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004282
Douglas Gregor6ab35242009-04-09 21:40:53 +00004283 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004284 ifield = firstField; ifield != e; ++ifield)
4285 lastField = ifield;
4286
Douglas Gregor6ab35242009-04-09 21:40:53 +00004287 if (lastField != RD->field_end(CGM.getContext())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004288 FieldDecl *Field = *lastField;
4289 const llvm::Type *FieldTy =
4290 CGM.getTypes().ConvertTypeForMem(Field->getType());
4291 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004292 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004293 if (firstField == RD->field_end(CGM.getContext()))
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004294 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004295 else {
4296 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004297 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004298 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004299 }
4300 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004301 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004302 InstanceStart,
4303 InstanceSize,
4304 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004305
4306 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004307 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004308 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4309 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004310 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004311
4312 // Force the definition of the EHType if necessary.
4313 if (flags & CLS_EXCEPTION)
4314 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004315}
4316
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004317/// GenerateProtocolRef - This routine is called to generate code for
4318/// a protocol reference expression; as in:
4319/// @code
4320/// @protocol(Proto1);
4321/// @endcode
4322/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4323/// which will hold address of the protocol meta-data.
4324///
4325llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4326 const ObjCProtocolDecl *PD) {
4327
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004328 // This routine is called for @protocol only. So, we must build definition
4329 // of protocol's meta-data (not a reference to it!)
4330 //
4331 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004332 ObjCTypes.ExternalProtocolPtrTy);
4333
4334 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4335 ProtocolName += PD->getNameAsCString();
4336
4337 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4338 if (PTGV)
4339 return Builder.CreateLoad(PTGV, false, "tmp");
4340 PTGV = new llvm::GlobalVariable(
4341 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004342 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004343 Init,
4344 ProtocolName,
4345 &CGM.getModule());
4346 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4347 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4348 UsedGlobals.push_back(PTGV);
4349 return Builder.CreateLoad(PTGV, false, "tmp");
4350}
4351
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004352/// GenerateCategory - Build metadata for a category implementation.
4353/// struct _category_t {
4354/// const char * const name;
4355/// struct _class_t *const cls;
4356/// const struct _method_list_t * const instance_methods;
4357/// const struct _method_list_t * const class_methods;
4358/// const struct _protocol_list_t * const protocols;
4359/// const struct _prop_list_t * const properties;
4360/// }
4361///
4362void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4363{
4364 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004365 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4366 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004367 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004368 std::string ExtClassName(getClassSymbolPrefix() +
4369 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004370
4371 std::vector<llvm::Constant*> Values(6);
4372 Values[0] = GetClassName(OCD->getIdentifier());
4373 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004374 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004375 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004376 std::vector<llvm::Constant*> Methods;
4377 std::string MethodListName(Prefix);
4378 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4379 "_$_" + OCD->getNameAsString();
4380
4381 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4382 e = OCD->instmeth_end(); i != e; ++i) {
4383 // Instance methods should always be defined.
4384 Methods.push_back(GetMethodConstant(*i));
4385 }
4386
4387 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004388 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004389 Methods);
4390
4391 MethodListName = Prefix;
4392 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4393 OCD->getNameAsString();
4394 Methods.clear();
4395 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4396 e = OCD->classmeth_end(); i != e; ++i) {
4397 // Class methods should always be defined.
4398 Methods.push_back(GetMethodConstant(*i));
4399 }
4400
4401 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004402 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004403 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004404 const ObjCCategoryDecl *Category =
4405 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004406 if (Category) {
4407 std::string ExtName(Interface->getNameAsString() + "_$_" +
4408 OCD->getNameAsString());
4409 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4410 + Interface->getNameAsString() + "_$_"
4411 + Category->getNameAsString(),
4412 Category->protocol_begin(),
4413 Category->protocol_end());
4414 Values[5] =
4415 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4416 OCD, Category, ObjCTypes);
4417 }
4418 else {
4419 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4420 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4421 }
4422
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004423 llvm::Constant *Init =
4424 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4425 Values);
4426 llvm::GlobalVariable *GCATV
4427 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4428 false,
4429 llvm::GlobalValue::InternalLinkage,
4430 Init,
4431 ExtCatName,
4432 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004433 GCATV->setAlignment(
4434 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004435 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004436 UsedGlobals.push_back(GCATV);
4437 DefinedCategories.push_back(GCATV);
4438}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004439
4440/// GetMethodConstant - Return a struct objc_method constant for the
4441/// given method if it has been defined. The result is null if the
4442/// method has not been defined. The return value has type MethodPtrTy.
4443llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4444 const ObjCMethodDecl *MD) {
4445 // FIXME: Use DenseMap::lookup
4446 llvm::Function *Fn = MethodDefinitions[MD];
4447 if (!Fn)
4448 return 0;
4449
4450 std::vector<llvm::Constant*> Method(3);
4451 Method[0] =
4452 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4453 ObjCTypes.SelectorPtrTy);
4454 Method[1] = GetMethodVarType(MD);
4455 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4456 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4457}
4458
4459/// EmitMethodList - Build meta-data for method declarations
4460/// struct _method_list_t {
4461/// uint32_t entsize; // sizeof(struct _objc_method)
4462/// uint32_t method_count;
4463/// struct _objc_method method_list[method_count];
4464/// }
4465///
4466llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4467 const std::string &Name,
4468 const char *Section,
4469 const ConstantVector &Methods) {
4470 // Return null for empty list.
4471 if (Methods.empty())
4472 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4473
4474 std::vector<llvm::Constant*> Values(3);
4475 // sizeof(struct _objc_method)
4476 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4477 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4478 // method_count
4479 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4480 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4481 Methods.size());
4482 Values[2] = llvm::ConstantArray::get(AT, Methods);
4483 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4484
4485 llvm::GlobalVariable *GV =
4486 new llvm::GlobalVariable(Init->getType(), false,
4487 llvm::GlobalValue::InternalLinkage,
4488 Init,
4489 Name,
4490 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004491 GV->setAlignment(
4492 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004493 GV->setSection(Section);
4494 UsedGlobals.push_back(GV);
4495 return llvm::ConstantExpr::getBitCast(GV,
4496 ObjCTypes.MethodListnfABIPtrTy);
4497}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004498
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004499/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4500/// the given ivar.
4501///
4502llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004503 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004504 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004505 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004506 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4507 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004508 llvm::GlobalVariable *IvarOffsetGV =
4509 CGM.getModule().getGlobalVariable(Name);
4510 if (!IvarOffsetGV)
4511 IvarOffsetGV =
4512 new llvm::GlobalVariable(ObjCTypes.LongTy,
4513 false,
4514 llvm::GlobalValue::ExternalLinkage,
4515 0,
4516 Name,
4517 &CGM.getModule());
4518 return IvarOffsetGV;
4519}
4520
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004521llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004522 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004523 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004524 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004525 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4526 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4527 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004528 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004529 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004530
4531 // FIXME: This matches gcc, but shouldn't the visibility be set on
4532 // the use as well (i.e., in ObjCIvarOffsetVariable).
4533 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4534 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4535 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004536 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004537 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004538 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004539 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004540 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004541}
4542
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004543/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004544/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004545/// IvarListnfABIPtrTy.
4546/// struct _ivar_t {
4547/// unsigned long int *offset; // pointer to ivar offset location
4548/// char *name;
4549/// char *type;
4550/// uint32_t alignment;
4551/// uint32_t size;
4552/// }
4553/// struct _ivar_list_t {
4554/// uint32 entsize; // sizeof(struct _ivar_t)
4555/// uint32 count;
4556/// struct _iver_t list[count];
4557/// }
4558///
4559llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4560 const ObjCImplementationDecl *ID) {
4561
4562 std::vector<llvm::Constant*> Ivars, Ivar(5);
4563
4564 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4565 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4566
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004567 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004568 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004569
4570 RecordDecl::field_iterator i,p;
4571 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004572 // collect declared and synthesized ivars in a small vector.
4573 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4574 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4575 E = OID->ivar_end(); I != E; ++I)
4576 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004577 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4578 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004579 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4580 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004581
Fariborz Jahanian18191882009-03-31 18:11:23 +00004582 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004583 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4584 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004585 FieldDecl *Field = *i;
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004586 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++],
4587 GetIvarBaseOffset(Layout, Field));
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004588 if (Field->getIdentifier())
4589 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4590 else
4591 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004592 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004593 const llvm::Type *FieldTy =
4594 CGM.getTypes().ConvertTypeForMem(Field->getType());
4595 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4596 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4597 Field->getType().getTypePtr()) >> 3;
4598 Align = llvm::Log2_32(Align);
4599 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004600 // NOTE. Size of a bitfield does not match gcc's, because of the way
4601 // bitfields are treated special in each. But I am told that 'size'
4602 // for bitfield ivars is ignored by the runtime so it does not matter.
4603 // (even if it matters, some day, there is enough info. to get the bitfield
4604 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004605 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4606 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4607 }
4608 // Return null for empty list.
4609 if (Ivars.empty())
4610 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4611 std::vector<llvm::Constant*> Values(3);
4612 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4613 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4614 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4615 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4616 Ivars.size());
4617 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4618 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4619 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4620 llvm::GlobalVariable *GV =
4621 new llvm::GlobalVariable(Init->getType(), false,
4622 llvm::GlobalValue::InternalLinkage,
4623 Init,
4624 Prefix + OID->getNameAsString(),
4625 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004626 GV->setAlignment(
4627 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004628 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004629
4630 UsedGlobals.push_back(GV);
4631 return llvm::ConstantExpr::getBitCast(GV,
4632 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004633}
4634
4635llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4636 const ObjCProtocolDecl *PD) {
4637 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4638
4639 if (!Entry) {
4640 // We use the initializer as a marker of whether this is a forward
4641 // reference or not. At module finalization we add the empty
4642 // contents for protocols which were referenced but never defined.
4643 Entry =
4644 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4645 llvm::GlobalValue::ExternalLinkage,
4646 0,
4647 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4648 &CGM.getModule());
4649 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4650 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004651 }
4652
4653 return Entry;
4654}
4655
4656/// GetOrEmitProtocol - Generate the protocol meta-data:
4657/// @code
4658/// struct _protocol_t {
4659/// id isa; // NULL
4660/// const char * const protocol_name;
4661/// const struct _protocol_list_t * protocol_list; // super protocols
4662/// const struct method_list_t * const instance_methods;
4663/// const struct method_list_t * const class_methods;
4664/// const struct method_list_t *optionalInstanceMethods;
4665/// const struct method_list_t *optionalClassMethods;
4666/// const struct _prop_list_t * properties;
4667/// const uint32_t size; // sizeof(struct _protocol_t)
4668/// const uint32_t flags; // = 0
4669/// }
4670/// @endcode
4671///
4672
4673llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4674 const ObjCProtocolDecl *PD) {
4675 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4676
4677 // Early exit if a defining object has already been generated.
4678 if (Entry && Entry->hasInitializer())
4679 return Entry;
4680
4681 const char *ProtocolName = PD->getNameAsCString();
4682
4683 // Construct method lists.
4684 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4685 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004686 for (ObjCProtocolDecl::instmeth_iterator
4687 i = PD->instmeth_begin(CGM.getContext()),
4688 e = PD->instmeth_end(CGM.getContext());
4689 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004690 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004691 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004692 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4693 OptInstanceMethods.push_back(C);
4694 } else {
4695 InstanceMethods.push_back(C);
4696 }
4697 }
4698
Douglas Gregor6ab35242009-04-09 21:40:53 +00004699 for (ObjCProtocolDecl::classmeth_iterator
4700 i = PD->classmeth_begin(CGM.getContext()),
4701 e = PD->classmeth_end(CGM.getContext());
4702 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004703 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004704 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004705 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4706 OptClassMethods.push_back(C);
4707 } else {
4708 ClassMethods.push_back(C);
4709 }
4710 }
4711
4712 std::vector<llvm::Constant*> Values(10);
4713 // isa is NULL
4714 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4715 Values[1] = GetClassName(PD->getIdentifier());
4716 Values[2] = EmitProtocolList(
4717 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4718 PD->protocol_begin(),
4719 PD->protocol_end());
4720
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004721 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004722 + PD->getNameAsString(),
4723 "__DATA, __objc_const",
4724 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004725 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004726 + PD->getNameAsString(),
4727 "__DATA, __objc_const",
4728 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004729 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004730 + PD->getNameAsString(),
4731 "__DATA, __objc_const",
4732 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004733 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004734 + PD->getNameAsString(),
4735 "__DATA, __objc_const",
4736 OptClassMethods);
4737 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4738 0, PD, ObjCTypes);
4739 uint32_t Size =
4740 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4741 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4742 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4743 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4744 Values);
4745
4746 if (Entry) {
4747 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004748 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004749 Entry->setInitializer(Init);
4750 } else {
4751 Entry =
4752 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004753 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004754 Init,
4755 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4756 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004757 Entry->setAlignment(
4758 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004759 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004760 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004761 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4762
4763 // Use this protocol meta-data to build protocol list table in section
4764 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004765 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004766 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004767 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004768 Entry,
4769 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4770 +ProtocolName,
4771 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004772 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004773 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004774 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004775 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4776 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004777 return Entry;
4778}
4779
4780/// EmitProtocolList - Generate protocol list meta-data:
4781/// @code
4782/// struct _protocol_list_t {
4783/// long protocol_count; // Note, this is 32/64 bit
4784/// struct _protocol_t[protocol_count];
4785/// }
4786/// @endcode
4787///
4788llvm::Constant *
4789CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4790 ObjCProtocolDecl::protocol_iterator begin,
4791 ObjCProtocolDecl::protocol_iterator end) {
4792 std::vector<llvm::Constant*> ProtocolRefs;
4793
Fariborz Jahanianda320092009-01-29 19:24:30 +00004794 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004795 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004796 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4797
Daniel Dunbar948e2582009-02-15 07:36:20 +00004798 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004799 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4800 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004801 return llvm::ConstantExpr::getBitCast(GV,
4802 ObjCTypes.ProtocolListnfABIPtrTy);
4803
4804 for (; begin != end; ++begin)
4805 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4806
Fariborz Jahanianda320092009-01-29 19:24:30 +00004807 // This list is null terminated.
4808 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004809 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810
4811 std::vector<llvm::Constant*> Values(2);
4812 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4813 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004814 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004815 ProtocolRefs.size()),
4816 ProtocolRefs);
4817
4818 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4819 GV = new llvm::GlobalVariable(Init->getType(), false,
4820 llvm::GlobalValue::InternalLinkage,
4821 Init,
4822 Name,
4823 &CGM.getModule());
4824 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004825 GV->setAlignment(
4826 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004827 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004828 return llvm::ConstantExpr::getBitCast(GV,
4829 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004830}
4831
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004832/// GetMethodDescriptionConstant - This routine build following meta-data:
4833/// struct _objc_method {
4834/// SEL _cmd;
4835/// char *method_type;
4836/// char *_imp;
4837/// }
4838
4839llvm::Constant *
4840CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4841 std::vector<llvm::Constant*> Desc(3);
4842 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4843 ObjCTypes.SelectorPtrTy);
4844 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004845 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004846 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4847 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4848}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004849
4850/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4851/// This code gen. amounts to generating code for:
4852/// @code
4853/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4854/// @encode
4855///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004856LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004857 CodeGen::CodeGenFunction &CGF,
4858 QualType ObjectTy,
4859 llvm::Value *BaseValue,
4860 const ObjCIvarDecl *Ivar,
4861 const FieldDecl *Field,
4862 unsigned CVRQualifiers) {
4863 assert(ObjectTy->isObjCInterfaceType() &&
4864 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004865 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004866 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004867
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004868 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004869 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004870 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4871 // (char*)BaseValue + Offset_symbol
4872 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4873 // (type *)((char*)BaseValue + Offset_symbol)
4874 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004875 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004876 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4877 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004878
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004879 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004880 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004881 CodeGenTypes::BitFieldInfo bitFieldInfo =
4882 CGM.getTypes().getBitFieldInfo(Field);
4883 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004884 FieldTy->isSignedIntegerType(),
4885 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004886 }
4887
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004888 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004889 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4890 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004891 LValue::SetObjCIvar(LV, true);
4892 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004893}
4894
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004895llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4896 CodeGen::CodeGenFunction &CGF,
4897 ObjCInterfaceDecl *Interface,
4898 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004899 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4900 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004901}
4902
Fariborz Jahanian46551122009-02-04 00:22:57 +00004903CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4904 CodeGen::CodeGenFunction &CGF,
4905 QualType ResultType,
4906 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004907 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004908 QualType Arg0Ty,
4909 bool IsSuper,
4910 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004911 // FIXME. Even though IsSuper is passes. This function doese not
4912 // handle calls to 'super' receivers.
4913 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004914 llvm::Value *Arg0 = Receiver;
4915 if (!IsSuper)
4916 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004917
4918 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004919 // FIXME. This is too much work to get the ABI-specific result type
4920 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004921 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4922 llvm::SmallVector<QualType, 16>());
4923 llvm::Constant *Fn;
4924 std::string Name("\01l_");
4925 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004926#if 0
4927 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004928 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4929 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4930 // FIXME. Is there a better way of getting these names.
4931 // They are available in RuntimeFunctions vector pair.
4932 Name += "objc_msgSendId_stret_fixup";
4933 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004934 else
4935#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004936 if (IsSuper) {
4937 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4938 Name += "objc_msgSendSuper2_stret_fixup";
4939 }
4940 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004941 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004942 Fn = ObjCTypes.MessageSendStretFixupFn;
4943 Name += "objc_msgSend_stret_fixup";
4944 }
4945 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004946 else if (ResultType->isFloatingType() &&
4947 // Selection of frret API only happens in 32bit nonfragile ABI.
4948 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004949 Fn = ObjCTypes.MessageSendFpretFixupFn;
4950 Name += "objc_msgSend_fpret_fixup";
4951 }
4952 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004953#if 0
4954// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004955 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4956 Fn = ObjCTypes.MessageSendIdFixupFn;
4957 Name += "objc_msgSendId_fixup";
4958 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004959 else
4960#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004961 if (IsSuper) {
4962 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4963 Name += "objc_msgSendSuper2_fixup";
4964 }
4965 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004966 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004967 Fn = ObjCTypes.MessageSendFixupFn;
4968 Name += "objc_msgSend_fixup";
4969 }
4970 }
4971 Name += '_';
4972 std::string SelName(Sel.getAsString());
4973 // Replace all ':' in selector name with '_' ouch!
4974 for(unsigned i = 0; i < SelName.size(); i++)
4975 if (SelName[i] == ':')
4976 SelName[i] = '_';
4977 Name += SelName;
4978 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4979 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004980 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004981 std::vector<llvm::Constant*> Values(2);
4982 Values[0] = Fn;
4983 Values[1] = GetMethodVarName(Sel);
4984 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4985 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004986 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004987 Init,
4988 Name,
4989 &CGM.getModule());
4990 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00004991 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004992 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004993 }
4994 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004995
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004996 CallArgList ActualArgs;
4997 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4998 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4999 ObjCTypes.MessageRefCPtrTy));
5000 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005001 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5002 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5003 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005004 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005005 Callee = CGF.Builder.CreateBitCast(Callee,
5006 llvm::PointerType::getUnqual(FTy));
5007 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005008}
5009
5010/// Generate code for a message send expression in the nonfragile abi.
5011CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5012 CodeGen::CodeGenFunction &CGF,
5013 QualType ResultType,
5014 Selector Sel,
5015 llvm::Value *Receiver,
5016 bool IsClassMessage,
5017 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005018 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005019 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005020 false, CallArgs);
5021}
5022
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005023llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005024CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005025 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5026
Daniel Dunbardfff2302009-03-02 05:18:14 +00005027 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005028 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5029 llvm::GlobalValue::ExternalLinkage,
5030 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005031 }
5032
5033 return GV;
5034}
5035
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005036llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005037 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005038 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5039
5040 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005041 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005042 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005043 Entry =
5044 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5045 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005046 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005047 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005048 &CGM.getModule());
5049 Entry->setAlignment(
5050 CGM.getTargetData().getPrefTypeAlignment(
5051 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005052 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5053 UsedGlobals.push_back(Entry);
5054 }
5055
5056 return Builder.CreateLoad(Entry, false, "tmp");
5057}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005058
Daniel Dunbar11394522009-04-18 08:51:00 +00005059llvm::Value *
5060CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5061 const ObjCInterfaceDecl *ID) {
5062 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5063
5064 if (!Entry) {
5065 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5066 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5067 Entry =
5068 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5069 llvm::GlobalValue::InternalLinkage,
5070 ClassGV,
5071 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5072 &CGM.getModule());
5073 Entry->setAlignment(
5074 CGM.getTargetData().getPrefTypeAlignment(
5075 ObjCTypes.ClassnfABIPtrTy));
5076 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005077 UsedGlobals.push_back(Entry);
5078 }
5079
5080 return Builder.CreateLoad(Entry, false, "tmp");
5081}
5082
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005083/// EmitMetaClassRef - Return a Value * of the address of _class_t
5084/// meta-data
5085///
5086llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5087 const ObjCInterfaceDecl *ID) {
5088 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5089 if (Entry)
5090 return Builder.CreateLoad(Entry, false, "tmp");
5091
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005092 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005093 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005094 Entry =
5095 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5096 llvm::GlobalValue::InternalLinkage,
5097 MetaClassGV,
5098 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5099 &CGM.getModule());
5100 Entry->setAlignment(
5101 CGM.getTargetData().getPrefTypeAlignment(
5102 ObjCTypes.ClassnfABIPtrTy));
5103
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005104 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005105 UsedGlobals.push_back(Entry);
5106
5107 return Builder.CreateLoad(Entry, false, "tmp");
5108}
5109
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005110/// GetClass - Return a reference to the class for the given interface
5111/// decl.
5112llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5113 const ObjCInterfaceDecl *ID) {
5114 return EmitClassRef(Builder, ID);
5115}
5116
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005117/// Generates a message send where the super is the receiver. This is
5118/// a message send to self with special delivery semantics indicating
5119/// which class's method should be called.
5120CodeGen::RValue
5121CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5122 QualType ResultType,
5123 Selector Sel,
5124 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005125 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005126 llvm::Value *Receiver,
5127 bool IsClassMessage,
5128 const CodeGen::CallArgList &CallArgs) {
5129 // ...
5130 // Create and init a super structure; this is a (receiver, class)
5131 // pair we will pass to objc_msgSendSuper.
5132 llvm::Value *ObjCSuper =
5133 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5134
5135 llvm::Value *ReceiverAsObject =
5136 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5137 CGF.Builder.CreateStore(ReceiverAsObject,
5138 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5139
5140 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005141 llvm::Value *Target;
5142 if (IsClassMessage) {
5143 if (isCategoryImpl) {
5144 // Message sent to "super' in a class method defined in
5145 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005146 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005147 Target = CGF.Builder.CreateStructGEP(Target, 0);
5148 Target = CGF.Builder.CreateLoad(Target);
5149 }
5150 else
5151 Target = EmitMetaClassRef(CGF.Builder, Class);
5152 }
5153 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005154 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005155
5156 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5157 // and ObjCTypes types.
5158 const llvm::Type *ClassTy =
5159 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5160 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5161 CGF.Builder.CreateStore(Target,
5162 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5163
5164 return EmitMessageSend(CGF, ResultType, Sel,
5165 ObjCSuper, ObjCTypes.SuperPtrCTy,
5166 true, CallArgs);
5167}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005168
5169llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5170 Selector Sel) {
5171 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5172
5173 if (!Entry) {
5174 llvm::Constant *Casted =
5175 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5176 ObjCTypes.SelectorPtrTy);
5177 Entry =
5178 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5179 llvm::GlobalValue::InternalLinkage,
5180 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5181 &CGM.getModule());
5182 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5183 UsedGlobals.push_back(Entry);
5184 }
5185
5186 return Builder.CreateLoad(Entry, false, "tmp");
5187}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005188/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5189/// objc_assign_ivar (id src, id *dst)
5190///
5191void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5192 llvm::Value *src, llvm::Value *dst)
5193{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005194 const llvm::Type * SrcTy = src->getType();
5195 if (!isa<llvm::PointerType>(SrcTy)) {
5196 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5197 assert(Size <= 8 && "does not support size > 8");
5198 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5199 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005200 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5201 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005202 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5203 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5204 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5205 src, dst, "assignivar");
5206 return;
5207}
5208
5209/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5210/// objc_assign_strongCast (id src, id *dst)
5211///
5212void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5213 CodeGen::CodeGenFunction &CGF,
5214 llvm::Value *src, llvm::Value *dst)
5215{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005216 const llvm::Type * SrcTy = src->getType();
5217 if (!isa<llvm::PointerType>(SrcTy)) {
5218 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5219 assert(Size <= 8 && "does not support size > 8");
5220 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5221 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005222 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5223 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005224 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5225 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5226 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5227 src, dst, "weakassign");
5228 return;
5229}
5230
5231/// EmitObjCWeakRead - Code gen for loading value of a __weak
5232/// object: objc_read_weak (id *src)
5233///
5234llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5235 CodeGen::CodeGenFunction &CGF,
5236 llvm::Value *AddrWeakObj)
5237{
Eli Friedman8339b352009-03-07 03:57:15 +00005238 const llvm::Type* DestTy =
5239 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005240 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5241 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5242 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005243 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005244 return read_weak;
5245}
5246
5247/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5248/// objc_assign_weak (id src, id *dst)
5249///
5250void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5251 llvm::Value *src, llvm::Value *dst)
5252{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005253 const llvm::Type * SrcTy = src->getType();
5254 if (!isa<llvm::PointerType>(SrcTy)) {
5255 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5256 assert(Size <= 8 && "does not support size > 8");
5257 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5258 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005259 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5260 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005261 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5262 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005263 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005264 src, dst, "weakassign");
5265 return;
5266}
5267
5268/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5269/// objc_assign_global (id src, id *dst)
5270///
5271void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5272 llvm::Value *src, llvm::Value *dst)
5273{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005274 const llvm::Type * SrcTy = src->getType();
5275 if (!isa<llvm::PointerType>(SrcTy)) {
5276 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5277 assert(Size <= 8 && "does not support size > 8");
5278 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5279 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005280 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5281 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005282 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5283 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5284 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5285 src, dst, "globalassign");
5286 return;
5287}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005288
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005289void
5290CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5291 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005292 bool isTry = isa<ObjCAtTryStmt>(S);
5293 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5294 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005295 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005296 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005297 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005298 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5299
5300 // For @synchronized, call objc_sync_enter(sync.expr). The
5301 // evaluation of the expression must occur before we enter the
5302 // @synchronized. We can safely avoid a temp here because jumps into
5303 // @synchronized are illegal & this will dominate uses.
5304 llvm::Value *SyncArg = 0;
5305 if (!isTry) {
5306 SyncArg =
5307 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5308 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005309 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005310 }
5311
5312 // Push an EH context entry, used for handling rethrows and jumps
5313 // through finally.
5314 CGF.PushCleanupBlock(FinallyBlock);
5315
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005316 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005317
5318 CGF.EmitBlock(TryBlock);
5319 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5320 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5321 CGF.EmitBranchThroughCleanup(FinallyEnd);
5322
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005323 // Emit the exception handler.
5324
5325 CGF.EmitBlock(TryHandler);
5326
5327 llvm::Value *llvm_eh_exception =
5328 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5329 llvm::Value *llvm_eh_selector_i64 =
5330 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5331 llvm::Value *llvm_eh_typeid_for_i64 =
5332 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5333 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5334 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5335
5336 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5337 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005338 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005339
5340 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005341 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005342 bool HasCatchAll = false;
5343 if (isTry) {
5344 if (const ObjCAtCatchStmt* CatchStmt =
5345 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5346 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005347 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005348 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005349
5350 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005351 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005352 // Use i8* null here to signal this is a catch all, not a cleanup.
5353 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5354 SelectorArgs.push_back(Null);
5355 HasCatchAll = true;
5356 break;
5357 }
5358
Daniel Dunbarede8de92009-03-06 00:01:21 +00005359 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5360 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005361 llvm::Value *IDEHType =
5362 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5363 if (!IDEHType)
5364 IDEHType =
5365 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5366 llvm::GlobalValue::ExternalLinkage,
5367 0, "OBJC_EHTYPE_id", &CGM.getModule());
5368 SelectorArgs.push_back(IDEHType);
5369 HasCatchAll = true;
5370 break;
5371 }
5372
5373 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005374 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005375 assert(PT && "Invalid @catch type.");
5376 const ObjCInterfaceType *IT =
5377 PT->getPointeeType()->getAsObjCInterfaceType();
5378 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005379 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005380 SelectorArgs.push_back(EHType);
5381 }
5382 }
5383 }
5384
5385 // We use a cleanup unless there was already a catch all.
5386 if (!HasCatchAll) {
5387 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005388 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005389 }
5390
5391 llvm::Value *Selector =
5392 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5393 SelectorArgs.begin(), SelectorArgs.end(),
5394 "selector");
5395 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005396 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005397 const Stmt *CatchBody = Handlers[i].second;
5398
5399 llvm::BasicBlock *Next = 0;
5400
5401 // The last handler always matches.
5402 if (i + 1 != e) {
5403 assert(CatchParam && "Only last handler can be a catch all.");
5404
5405 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5406 Next = CGF.createBasicBlock("catch.next");
5407 llvm::Value *Id =
5408 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5409 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5410 ObjCTypes.Int8PtrTy));
5411 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5412 Match, Next);
5413
5414 CGF.EmitBlock(Match);
5415 }
5416
5417 if (CatchBody) {
5418 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5419 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5420
5421 // Cleanups must call objc_end_catch.
5422 //
5423 // FIXME: It seems incorrect for objc_begin_catch to be inside
5424 // this context, but this matches gcc.
5425 CGF.PushCleanupBlock(MatchEnd);
5426 CGF.setInvokeDest(MatchHandler);
5427
5428 llvm::Value *ExcObject =
5429 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5430
5431 // Bind the catch parameter if it exists.
5432 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005433 ExcObject =
5434 CGF.Builder.CreateBitCast(ExcObject,
5435 CGF.ConvertType(CatchParam->getType()));
5436 // CatchParam is a ParmVarDecl because of the grammar
5437 // construction used to handle this, but for codegen purposes
5438 // we treat this as a local decl.
5439 CGF.EmitLocalBlockVarDecl(*CatchParam);
5440 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005441 }
5442
5443 CGF.ObjCEHValueStack.push_back(ExcObject);
5444 CGF.EmitStmt(CatchBody);
5445 CGF.ObjCEHValueStack.pop_back();
5446
5447 CGF.EmitBranchThroughCleanup(FinallyEnd);
5448
5449 CGF.EmitBlock(MatchHandler);
5450
5451 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5452 // We are required to emit this call to satisfy LLVM, even
5453 // though we don't use the result.
5454 llvm::SmallVector<llvm::Value*, 8> Args;
5455 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005456 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005457 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5458 0));
5459 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5460 CGF.Builder.CreateStore(Exc, RethrowPtr);
5461 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5462
5463 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5464
5465 CGF.EmitBlock(MatchEnd);
5466
5467 // Unfortunately, we also have to generate another EH frame here
5468 // in case this throws.
5469 llvm::BasicBlock *MatchEndHandler =
5470 CGF.createBasicBlock("match.end.handler");
5471 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5472 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5473 Cont, MatchEndHandler,
5474 Args.begin(), Args.begin());
5475
5476 CGF.EmitBlock(Cont);
5477 if (Info.SwitchBlock)
5478 CGF.EmitBlock(Info.SwitchBlock);
5479 if (Info.EndBlock)
5480 CGF.EmitBlock(Info.EndBlock);
5481
5482 CGF.EmitBlock(MatchEndHandler);
5483 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5484 // We are required to emit this call to satisfy LLVM, even
5485 // though we don't use the result.
5486 Args.clear();
5487 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005488 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005489 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5490 0));
5491 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5492 CGF.Builder.CreateStore(Exc, RethrowPtr);
5493 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5494
5495 if (Next)
5496 CGF.EmitBlock(Next);
5497 } else {
5498 assert(!Next && "catchup should be last handler.");
5499
5500 CGF.Builder.CreateStore(Exc, RethrowPtr);
5501 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5502 }
5503 }
5504
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005505 // Pop the cleanup entry, the @finally is outside this cleanup
5506 // scope.
5507 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5508 CGF.setInvokeDest(PrevLandingPad);
5509
5510 CGF.EmitBlock(FinallyBlock);
5511
5512 if (isTry) {
5513 if (const ObjCAtFinallyStmt* FinallyStmt =
5514 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5515 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5516 } else {
5517 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5518 // @synchronized.
5519 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005520 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005521
5522 if (Info.SwitchBlock)
5523 CGF.EmitBlock(Info.SwitchBlock);
5524 if (Info.EndBlock)
5525 CGF.EmitBlock(Info.EndBlock);
5526
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005527 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005528 CGF.EmitBranch(FinallyEnd);
5529
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005530 CGF.EmitBlock(FinallyRethrow);
5531 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5532 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005533 CGF.Builder.CreateUnreachable();
5534
5535 CGF.EmitBlock(FinallyEnd);
5536}
5537
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005538/// EmitThrowStmt - Generate code for a throw statement.
5539void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5540 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005541 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005542 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005543 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005544 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005545 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5546 "Unexpected rethrow outside @catch block.");
5547 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005548 }
5549
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005550 llvm::Value *ExceptionAsObject =
5551 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5552 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5553 if (InvokeDest) {
5554 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5555 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5556 Cont, InvokeDest,
5557 &ExceptionAsObject, &ExceptionAsObject + 1);
5558 CGF.EmitBlock(Cont);
5559 } else
5560 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5561 CGF.Builder.CreateUnreachable();
5562
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005563 // Clear the insertion point to indicate we are in unreachable code.
5564 CGF.Builder.ClearInsertionPoint();
5565}
Daniel Dunbare588b992009-03-01 04:46:24 +00005566
5567llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005568CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5569 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005570 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005571
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005572 // If we don't need a definition, return the entry if found or check
5573 // if we use an external reference.
5574 if (!ForDefinition) {
5575 if (Entry)
5576 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005577
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005578 // If this type (or a super class) has the __objc_exception__
5579 // attribute, emit an external reference.
5580 if (hasObjCExceptionAttribute(ID))
5581 return Entry =
5582 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5583 llvm::GlobalValue::ExternalLinkage,
5584 0,
5585 (std::string("OBJC_EHTYPE_$_") +
5586 ID->getIdentifier()->getName()),
5587 &CGM.getModule());
5588 }
5589
5590 // Otherwise we need to either make a new entry or fill in the
5591 // initializer.
5592 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005593 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005594 std::string VTableName = "objc_ehtype_vtable";
5595 llvm::GlobalVariable *VTableGV =
5596 CGM.getModule().getGlobalVariable(VTableName);
5597 if (!VTableGV)
5598 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5599 llvm::GlobalValue::ExternalLinkage,
5600 0, VTableName, &CGM.getModule());
5601
5602 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5603
5604 std::vector<llvm::Constant*> Values(3);
5605 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5606 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005607 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005608 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5609
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005610 if (Entry) {
5611 Entry->setInitializer(Init);
5612 } else {
5613 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5614 llvm::GlobalValue::WeakAnyLinkage,
5615 Init,
5616 (std::string("OBJC_EHTYPE_$_") +
5617 ID->getIdentifier()->getName()),
5618 &CGM.getModule());
5619 }
5620
Daniel Dunbar04d40782009-04-14 06:00:08 +00005621 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005622 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005623 Entry->setAlignment(8);
5624
5625 if (ForDefinition) {
5626 Entry->setSection("__DATA,__objc_const");
5627 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5628 } else {
5629 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5630 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005631
5632 return Entry;
5633}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005634
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005635/* *** */
5636
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005637CodeGen::CGObjCRuntime *
5638CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005639 return new CGObjCMac(CGM);
5640}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005641
5642CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005643CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005644 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005645}