blob: ed71b09942b49e52734b2db1749a4c179cb7017d [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);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000425 llvm::Constant *GetMethodVarType(const 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 Jahanian5de14dc2009-01-28 22:18:42 +0000462 /// EmitPropertyList - Emit the given property list. The return
463 /// value has type PropertyListPtrTy.
464 llvm::Constant *EmitPropertyList(const std::string &Name,
465 const Decl *Container,
466 const ObjCContainerDecl *OCD,
467 const ObjCCommonTypesHelper &ObjCTypes);
468
Fariborz Jahanianda320092009-01-29 19:24:30 +0000469 /// GetProtocolRef - Return a reference to the internal protocol
470 /// description, creating an empty one if it has not been
471 /// defined. The return value has type ProtocolPtrTy.
472 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000473
474 /// GetIvarBaseOffset - returns ivars byte offset.
475 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000476 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000477
Chris Lattnercd0ee142009-03-31 08:33:16 +0000478 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000479 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
480 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000483 /// CreateMetadataVar - Create a global variable with internal
484 /// linkage for use by the Objective-C runtime.
485 ///
486 /// This is a convenience wrapper which not only creates the
487 /// variable, but also sets the section and alignment and adds the
488 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000489 ///
490 /// \param Name - The variable name.
491 /// \param Init - The variable initializer; this is also used to
492 /// define the type of the variable.
493 /// \param Section - The section the variable should go into, or 0.
494 /// \param Align - The alignment for the variable, or 0.
495 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000496 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000497 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
498 llvm::Constant *Init,
499 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000500 unsigned Align,
501 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000502
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000503 /// GetNamedIvarList - Return the list of ivars in the interface
504 /// itself (not including super classes and not including unnamed
505 /// bitfields).
506 ///
507 /// For the non-fragile ABI, this also includes synthesized property
508 /// ivars.
509 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
510 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
511
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000512public:
513 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
514 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000515
Steve Naroff33fdb732009-03-31 16:53:37 +0000516 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000517
518 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
519 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000520
521 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
522
523 /// GetOrEmitProtocol - Get the protocol object for the given
524 /// declaration, emitting it if necessary. The return value has type
525 /// ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
527
528 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
529 /// object for the given declaration, emitting it if needed. These
530 /// forward references will be filled in with empty bodies if no
531 /// definition is seen. The return value has type ProtocolPtrTy.
532 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000533};
534
535class CGObjCMac : public CGObjCCommonMac {
536private:
537 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000538 /// EmitImageInfo - Emit the image info marker used to encode some module
539 /// level information.
540 void EmitImageInfo();
541
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000542 /// EmitModuleInfo - Another marker encoding module level
543 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000544 void EmitModuleInfo();
545
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000546 /// EmitModuleSymols - Emit module symbols, the list of defined
547 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000548 llvm::Constant *EmitModuleSymbols();
549
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000550 /// FinishModule - Write out global data structures at the end of
551 /// processing a translation unit.
552 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000553
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000554 /// EmitClassExtension - Generate the class extension structure used
555 /// to store the weak ivar layout and properties. The return value
556 /// has type ClassExtensionPtrTy.
557 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
558
559 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
560 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000561 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000562 const ObjCInterfaceDecl *ID);
563
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000564 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000565 QualType ResultType,
566 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000567 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000568 QualType Arg0Ty,
569 bool IsSuper,
570 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000571
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000572 /// EmitIvarList - Emit the ivar list for the given
573 /// implementation. If ForClass is true the list of class ivars
574 /// (i.e. metaclass ivars) is emitted, otherwise the list of
575 /// interface ivars will be emitted. The return value has type
576 /// IvarListPtrTy.
577 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000578 bool ForClass);
579
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 /// EmitMetaClass - Emit a forward reference to the class structure
581 /// for the metaclass of the given interface. The return value has
582 /// type ClassPtrTy.
583 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
584
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000585 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000586 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000587 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
588 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000589 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000590 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000591
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000592 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000593
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000594 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000595
596 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000597 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000598 llvm::Constant *EmitMethodList(const std::string &Name,
599 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000600 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000601
602 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000603 /// method declarations.
604 /// - TypeName: The name for the type containing the methods.
605 /// - IsProtocol: True iff these methods are for a protocol.
606 /// - ClassMethds: True iff these are class methods.
607 /// - Required: When true, only "required" methods are
608 /// listed. Similarly, when false only "optional" methods are
609 /// listed. For classes this should always be true.
610 /// - begin, end: The method list to output.
611 ///
612 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000613 llvm::Constant *EmitMethodDescList(const std::string &Name,
614 const char *Section,
615 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000616
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000617 /// GetOrEmitProtocol - Get the protocol object for the given
618 /// declaration, emitting it if necessary. The return value has type
619 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000621
622 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
623 /// object for the given declaration, emitting it if needed. These
624 /// forward references will be filled in with empty bodies if no
625 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000626 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000627
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000628 /// EmitProtocolExtension - Generate the protocol extension
629 /// structure used to store optional instance and class methods, and
630 /// protocol properties. The return value has type
631 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000632 llvm::Constant *
633 EmitProtocolExtension(const ObjCProtocolDecl *PD,
634 const ConstantVector &OptInstanceMethods,
635 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000636
637 /// EmitProtocolList - Generate the list of referenced
638 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000639 llvm::Constant *EmitProtocolList(const std::string &Name,
640 ObjCProtocolDecl::protocol_iterator begin,
641 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000642
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000643 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
644 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000645 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000646
Fariborz Jahanianda320092009-01-29 19:24:30 +0000647 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000648 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000649
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000650 virtual llvm::Function *ModuleInitFunction();
651
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000652 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000653 QualType ResultType,
654 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000655 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000656 bool IsClassMessage,
657 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000658
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000659 virtual CodeGen::RValue
660 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000661 QualType ResultType,
662 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000663 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000664 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000665 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000666 bool IsClassMessage,
667 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000668
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000669 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000670 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000673
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000674 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000675
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000676 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000677
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000678 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000679 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000680
Chris Lattner74391b42009-03-22 21:03:39 +0000681 virtual llvm::Constant *GetPropertyGetFunction();
682 virtual llvm::Constant *GetPropertySetFunction();
683 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000684
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000685 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
686 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000687 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
688 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000689 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000690 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000691 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000693 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
694 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000695 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
696 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000697 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
698 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000699
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000700 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
701 QualType ObjectTy,
702 llvm::Value *BaseValue,
703 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000704 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000705 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
706 ObjCInterfaceDecl *Interface,
707 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000708};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000709
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000710class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000711private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000712 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000713 llvm::GlobalVariable* ObjCEmptyCacheVar;
714 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000715
Daniel Dunbar11394522009-04-18 08:51:00 +0000716 /// SuperClassReferences - uniqued super class references.
717 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
718
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000719 /// MetaClassReferences - uniqued meta class references.
720 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000721
722 /// EHTypeReferences - uniqued class ehtype references.
723 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000724
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000725 /// FinishNonFragileABIModule - Write out global data structures at the end of
726 /// processing a translation unit.
727 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000728
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000729 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
730 unsigned InstanceStart,
731 unsigned InstanceSize,
732 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000733 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
734 llvm::Constant *IsAGV,
735 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000736 llvm::Constant *ClassRoGV,
737 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000738
739 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
740
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000741 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
742
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000743 /// EmitMethodList - Emit the method list for the given
744 /// implementation. The return value has type MethodListnfABITy.
745 llvm::Constant *EmitMethodList(const std::string &Name,
746 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000747 const ConstantVector &Methods);
748 /// EmitIvarList - Emit the ivar list for the given
749 /// implementation. If ForClass is true the list of class ivars
750 /// (i.e. metaclass ivars) is emitted, otherwise the list of
751 /// interface ivars will be emitted. The return value has type
752 /// IvarListnfABIPtrTy.
753 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000754
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000755 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000756 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000757 unsigned long int offset);
758
Fariborz Jahanianda320092009-01-29 19:24:30 +0000759 /// GetOrEmitProtocol - Get the protocol object for the given
760 /// declaration, emitting it if necessary. The return value has type
761 /// ProtocolPtrTy.
762 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
763
764 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
765 /// object for the given declaration, emitting it if needed. These
766 /// forward references will be filled in with empty bodies if no
767 /// definition is seen. The return value has type ProtocolPtrTy.
768 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
769
770 /// EmitProtocolList - Generate the list of referenced
771 /// protocols. The return value has type ProtocolListPtrTy.
772 llvm::Constant *EmitProtocolList(const std::string &Name,
773 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000774 ObjCProtocolDecl::protocol_iterator end);
775
776 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
777 QualType ResultType,
778 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000779 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000780 QualType Arg0Ty,
781 bool IsSuper,
782 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000783
784 /// GetClassGlobal - Return the global variable for the Objective-C
785 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000786 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
787
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000788 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000789 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000790 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000791 const ObjCInterfaceDecl *ID);
792
793 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
794 /// for the given super class reference.
795 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
796 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000797
798 /// EmitMetaClassRef - Return a Value * of the address of _class_t
799 /// meta-data
800 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
801 const ObjCInterfaceDecl *ID);
802
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000803 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
804 /// the given ivar.
805 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000806 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000807 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000808 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000809
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000810 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
811 /// for the given selector.
812 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000813
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000814 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000815 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000816 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
817 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000818
819 const char *getMetaclassSymbolPrefix() const {
820 return "OBJC_METACLASS_$_";
821 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000822
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000823 const char *getClassSymbolPrefix() const {
824 return "OBJC_CLASS_$_";
825 }
826
Daniel Dunbarb02532a2009-04-19 23:41:48 +0000827 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
828 uint32_t &InstanceStart,
829 uint32_t &InstanceSize);
830
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000831public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000832 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000833 // FIXME. All stubs for now!
834 virtual llvm::Function *ModuleInitFunction();
835
836 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
837 QualType ResultType,
838 Selector Sel,
839 llvm::Value *Receiver,
840 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000841 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000842
843 virtual CodeGen::RValue
844 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
845 QualType ResultType,
846 Selector Sel,
847 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000848 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000849 llvm::Value *Receiver,
850 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000851 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000852
853 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000854 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000855
856 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000857 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000858
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000859 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000860
861 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000862 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000863 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000864
Chris Lattner74391b42009-03-22 21:03:39 +0000865 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000866 return ObjCTypes.GetPropertyFn;
867 }
Chris Lattner74391b42009-03-22 21:03:39 +0000868 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000869 return ObjCTypes.SetPropertyFn;
870 }
Chris Lattner74391b42009-03-22 21:03:39 +0000871 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000872 return ObjCTypes.EnumerationMutationFn;
873 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000874
875 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000876 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000877 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000878 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000879 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000880 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000881 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000882 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000883 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000884 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000885 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000886 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000887 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000888 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000889 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
890 QualType ObjectTy,
891 llvm::Value *BaseValue,
892 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000893 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000894 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
895 ObjCInterfaceDecl *Interface,
896 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000897};
898
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000899} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000900
901/* *** Helper Functions *** */
902
903/// getConstantGEP() - Help routine to construct simple GEPs.
904static llvm::Constant *getConstantGEP(llvm::Constant *C,
905 unsigned idx0,
906 unsigned idx1) {
907 llvm::Value *Idxs[] = {
908 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
909 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
910 };
911 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
912}
913
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000914/// hasObjCExceptionAttribute - Return true if this class or any super
915/// class has the __objc_exception__ attribute.
916static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000917 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000918 return true;
919 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
920 return hasObjCExceptionAttribute(Super);
921 return false;
922}
923
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000924/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000925
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000926CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
927 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000928{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000929 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000930 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000931}
932
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000933/// GetClass - Return a reference to the class for the given interface
934/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000935llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000936 const ObjCInterfaceDecl *ID) {
937 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000938}
939
940/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000941llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000942 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000943}
944
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000945/// Generate a constant CFString object.
946/*
947 struct __builtin_CFString {
948 const int *isa; // point to __CFConstantStringClassReference
949 int flags;
950 const char *str;
951 long length;
952 };
953*/
954
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000955llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000956 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000957 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000958}
959
960/// Generates a message send where the super is the receiver. This is
961/// a message send to self with special delivery semantics indicating
962/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000963CodeGen::RValue
964CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000965 QualType ResultType,
966 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000967 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000968 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000969 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000970 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000971 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000972 // Create and init a super structure; this is a (receiver, class)
973 // pair we will pass to objc_msgSendSuper.
974 llvm::Value *ObjCSuper =
975 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
976 llvm::Value *ReceiverAsObject =
977 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
978 CGF.Builder.CreateStore(ReceiverAsObject,
979 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000980
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000981 // If this is a class message the metaclass is passed as the target.
982 llvm::Value *Target;
983 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000984 if (isCategoryImpl) {
985 // Message sent to 'super' in a class method defined in a category
986 // implementation requires an odd treatment.
987 // If we are in a class method, we must retrieve the
988 // _metaclass_ for the current class, pointed at by
989 // the class's "isa" pointer. The following assumes that
990 // isa" is the first ivar in a class (which it must be).
991 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
992 Target = CGF.Builder.CreateStructGEP(Target, 0);
993 Target = CGF.Builder.CreateLoad(Target);
994 }
995 else {
996 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
997 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
998 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
999 Target = Super;
1000 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001001 } else {
1002 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1003 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001004 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1005 // and ObjCTypes types.
1006 const llvm::Type *ClassTy =
1007 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001008 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001009 CGF.Builder.CreateStore(Target,
1010 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1011
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001012 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001013 ObjCSuper, ObjCTypes.SuperPtrCTy,
1014 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001015}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001016
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001017/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001018CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001019 QualType ResultType,
1020 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001021 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001022 bool IsClassMessage,
1023 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001024 llvm::Value *Arg0 =
1025 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001026 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001027 Arg0, CGF.getContext().getObjCIdType(),
1028 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001029}
1030
1031CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001032 QualType ResultType,
1033 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001034 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001035 QualType Arg0Ty,
1036 bool IsSuper,
1037 const CallArgList &CallArgs) {
1038 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001039 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1040 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1041 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001042 CGF.getContext().getObjCSelType()));
1043 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001044
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001045 CodeGenTypes &Types = CGM.getTypes();
1046 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1047 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001048
1049 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001050 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001051 Fn = ObjCTypes.getSendStretFn(IsSuper);
1052 } else if (ResultType->isFloatingType()) {
1053 // FIXME: Sadly, this is wrong. This actually depends on the
1054 // architecture. This happens to be right for x86-32 though.
1055 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1056 } else {
1057 Fn = ObjCTypes.getSendFn(IsSuper);
1058 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001059 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001060 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001061}
1062
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001063llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001064 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001065 // FIXME: I don't understand why gcc generates this, or where it is
1066 // resolved. Investigate. Its also wasteful to look this up over and
1067 // over.
1068 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1069
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001070 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1071 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001072}
1073
Fariborz Jahanianda320092009-01-29 19:24:30 +00001074void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001075 // FIXME: We shouldn't need this, the protocol decl should contain
1076 // enough information to tell us whether this was a declaration or a
1077 // definition.
1078 DefinedProtocols.insert(PD->getIdentifier());
1079
1080 // If we have generated a forward reference to this protocol, emit
1081 // it now. Otherwise do nothing, the protocol objects are lazily
1082 // emitted.
1083 if (Protocols.count(PD->getIdentifier()))
1084 GetOrEmitProtocol(PD);
1085}
1086
Fariborz Jahanianda320092009-01-29 19:24:30 +00001087llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001088 if (DefinedProtocols.count(PD->getIdentifier()))
1089 return GetOrEmitProtocol(PD);
1090 return GetOrEmitProtocolRef(PD);
1091}
1092
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001093/*
1094 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1095 struct _objc_protocol {
1096 struct _objc_protocol_extension *isa;
1097 char *protocol_name;
1098 struct _objc_protocol_list *protocol_list;
1099 struct _objc__method_prototype_list *instance_methods;
1100 struct _objc__method_prototype_list *class_methods
1101 };
1102
1103 See EmitProtocolExtension().
1104*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001105llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1106 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1107
1108 // Early exit if a defining object has already been generated.
1109 if (Entry && Entry->hasInitializer())
1110 return Entry;
1111
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001112 // FIXME: I don't understand why gcc generates this, or where it is
1113 // resolved. Investigate. Its also wasteful to look this up over and
1114 // over.
1115 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1116
Chris Lattner8ec03f52008-11-24 03:54:41 +00001117 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001118
1119 // Construct method lists.
1120 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1121 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001122 for (ObjCProtocolDecl::instmeth_iterator
1123 i = PD->instmeth_begin(CGM.getContext()),
1124 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001125 ObjCMethodDecl *MD = *i;
1126 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1127 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1128 OptInstanceMethods.push_back(C);
1129 } else {
1130 InstanceMethods.push_back(C);
1131 }
1132 }
1133
Douglas Gregor6ab35242009-04-09 21:40:53 +00001134 for (ObjCProtocolDecl::classmeth_iterator
1135 i = PD->classmeth_begin(CGM.getContext()),
1136 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001137 ObjCMethodDecl *MD = *i;
1138 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1139 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1140 OptClassMethods.push_back(C);
1141 } else {
1142 ClassMethods.push_back(C);
1143 }
1144 }
1145
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001146 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001147 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001148 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001149 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001150 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001151 PD->protocol_begin(),
1152 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001153 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001154 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1155 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001156 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1157 InstanceMethods);
1158 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001159 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1160 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001161 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1162 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001163 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1164 Values);
1165
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001166 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001167 // Already created, fix the linkage and update the initializer.
1168 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001169 Entry->setInitializer(Init);
1170 } else {
1171 Entry =
1172 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1173 llvm::GlobalValue::InternalLinkage,
1174 Init,
1175 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1176 &CGM.getModule());
1177 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001178 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001179 UsedGlobals.push_back(Entry);
1180 // FIXME: Is this necessary? Why only for protocol?
1181 Entry->setAlignment(4);
1182 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001183
1184 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001185}
1186
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001187llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001188 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1189
1190 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001191 // We use the initializer as a marker of whether this is a forward
1192 // reference or not. At module finalization we add the empty
1193 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001194 Entry =
1195 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001196 llvm::GlobalValue::ExternalLinkage,
1197 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001198 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001199 &CGM.getModule());
1200 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001201 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001202 UsedGlobals.push_back(Entry);
1203 // FIXME: Is this necessary? Why only for protocol?
1204 Entry->setAlignment(4);
1205 }
1206
1207 return Entry;
1208}
1209
1210/*
1211 struct _objc_protocol_extension {
1212 uint32_t size;
1213 struct objc_method_description_list *optional_instance_methods;
1214 struct objc_method_description_list *optional_class_methods;
1215 struct objc_property_list *instance_properties;
1216 };
1217*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001218llvm::Constant *
1219CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1220 const ConstantVector &OptInstanceMethods,
1221 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001222 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001223 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001224 std::vector<llvm::Constant*> Values(4);
1225 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001226 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001227 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1228 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001229 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1230 OptInstanceMethods);
1231 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001232 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1233 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001234 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1235 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001236 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1237 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001238 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001239
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001240 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001241 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1242 Values[3]->isNullValue())
1243 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1244
1245 llvm::Constant *Init =
1246 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001247
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001248 // No special section, but goes in llvm.used
1249 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1250 Init,
1251 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001252}
1253
1254/*
1255 struct objc_protocol_list {
1256 struct objc_protocol_list *next;
1257 long count;
1258 Protocol *list[];
1259 };
1260*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001261llvm::Constant *
1262CGObjCMac::EmitProtocolList(const std::string &Name,
1263 ObjCProtocolDecl::protocol_iterator begin,
1264 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001265 std::vector<llvm::Constant*> ProtocolRefs;
1266
Daniel Dunbardbc933702008-08-21 21:57:41 +00001267 for (; begin != end; ++begin)
1268 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001269
1270 // Just return null for empty protocol lists
1271 if (ProtocolRefs.empty())
1272 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1273
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001274 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001275 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1276
1277 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001278 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001279 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1280 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1281 Values[2] =
1282 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1283 ProtocolRefs.size()),
1284 ProtocolRefs);
1285
1286 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1287 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001288 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001289 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001290 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1291}
1292
1293/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001294 struct _objc_property {
1295 const char * const name;
1296 const char * const attributes;
1297 };
1298
1299 struct _objc_property_list {
1300 uint32_t entsize; // sizeof (struct _objc_property)
1301 uint32_t prop_count;
1302 struct _objc_property[prop_count];
1303 };
1304*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001305llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1306 const Decl *Container,
1307 const ObjCContainerDecl *OCD,
1308 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001309 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001310 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1311 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001312 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001313 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001314 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001315 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1316 Prop));
1317 }
1318
1319 // Return null for empty list.
1320 if (Properties.empty())
1321 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1322
1323 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001324 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001325 std::vector<llvm::Constant*> Values(3);
1326 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1327 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1328 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1329 Properties.size());
1330 Values[2] = llvm::ConstantArray::get(AT, Properties);
1331 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1332
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001333 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001334 CreateMetadataVar(Name, Init,
1335 (ObjCABI == 2) ? "__DATA, __objc_const" :
1336 "__OBJC,__property,regular,no_dead_strip",
1337 (ObjCABI == 2) ? 8 : 4,
1338 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001339 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001340}
1341
1342/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001343 struct objc_method_description_list {
1344 int count;
1345 struct objc_method_description list[];
1346 };
1347*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001348llvm::Constant *
1349CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1350 std::vector<llvm::Constant*> Desc(2);
1351 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1352 ObjCTypes.SelectorPtrTy);
1353 Desc[1] = GetMethodVarType(MD);
1354 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1355 Desc);
1356}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001357
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001358llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1359 const char *Section,
1360 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001361 // Return null for empty list.
1362 if (Methods.empty())
1363 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1364
1365 std::vector<llvm::Constant*> Values(2);
1366 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1367 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1368 Methods.size());
1369 Values[1] = llvm::ConstantArray::get(AT, Methods);
1370 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1371
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001372 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001373 return llvm::ConstantExpr::getBitCast(GV,
1374 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001375}
1376
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001377/*
1378 struct _objc_category {
1379 char *category_name;
1380 char *class_name;
1381 struct _objc_method_list *instance_methods;
1382 struct _objc_method_list *class_methods;
1383 struct _objc_protocol_list *protocols;
1384 uint32_t size; // <rdar://4585769>
1385 struct _objc_property_list *instance_properties;
1386 };
1387 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001388void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001389 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001390
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001391 // FIXME: This is poor design, the OCD should have a pointer to the
1392 // category decl. Additionally, note that Category can be null for
1393 // the @implementation w/o an @interface case. Sema should just
1394 // create one for us as it does for @implementation so everyone else
1395 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001396 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001397 const ObjCCategoryDecl *Category =
1398 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001399 std::string ExtName(Interface->getNameAsString() + "_" +
1400 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001401
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001402 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1403 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1404 e = OCD->instmeth_end(); i != e; ++i) {
1405 // Instance methods should always be defined.
1406 InstanceMethods.push_back(GetMethodConstant(*i));
1407 }
1408 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1409 e = OCD->classmeth_end(); i != e; ++i) {
1410 // Class methods should always be defined.
1411 ClassMethods.push_back(GetMethodConstant(*i));
1412 }
1413
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001414 std::vector<llvm::Constant*> Values(7);
1415 Values[0] = GetClassName(OCD->getIdentifier());
1416 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001417 Values[2] =
1418 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1419 ExtName,
1420 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001421 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001422 Values[3] =
1423 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001424 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001425 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001426 if (Category) {
1427 Values[4] =
1428 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1429 Category->protocol_begin(),
1430 Category->protocol_end());
1431 } else {
1432 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1433 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001434 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001435
1436 // If there is no category @interface then there can be no properties.
1437 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001438 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001439 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001440 } else {
1441 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1442 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001443
1444 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1445 Values);
1446
1447 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001448 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1449 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001450 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001451 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001452}
1453
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001454// FIXME: Get from somewhere?
1455enum ClassFlags {
1456 eClassFlags_Factory = 0x00001,
1457 eClassFlags_Meta = 0x00002,
1458 // <rdr://5142207>
1459 eClassFlags_HasCXXStructors = 0x02000,
1460 eClassFlags_Hidden = 0x20000,
1461 eClassFlags_ABI2_Hidden = 0x00010,
1462 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1463};
1464
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001465/*
1466 struct _objc_class {
1467 Class isa;
1468 Class super_class;
1469 const char *name;
1470 long version;
1471 long info;
1472 long instance_size;
1473 struct _objc_ivar_list *ivars;
1474 struct _objc_method_list *methods;
1475 struct _objc_cache *cache;
1476 struct _objc_protocol_list *protocols;
1477 // Objective-C 1.0 extensions (<rdr://4585769>)
1478 const char *ivar_layout;
1479 struct _objc_class_ext *ext;
1480 };
1481
1482 See EmitClassExtension();
1483 */
1484void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001485 DefinedSymbols.insert(ID->getIdentifier());
1486
Chris Lattner8ec03f52008-11-24 03:54:41 +00001487 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001488 // FIXME: Gross
1489 ObjCInterfaceDecl *Interface =
1490 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001491 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001492 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001493 Interface->protocol_begin(),
1494 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001495 const llvm::Type *InterfaceTy;
1496 if (Interface->isForwardDecl())
1497 InterfaceTy = llvm::StructType::get(NULL, NULL);
1498 else
1499 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001500 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001501 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001502 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001503
1504 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001505 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001506 Flags |= eClassFlags_Hidden;
1507
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001508 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1509 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1510 e = ID->instmeth_end(); i != e; ++i) {
1511 // Instance methods should always be defined.
1512 InstanceMethods.push_back(GetMethodConstant(*i));
1513 }
1514 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1515 e = ID->classmeth_end(); i != e; ++i) {
1516 // Class methods should always be defined.
1517 ClassMethods.push_back(GetMethodConstant(*i));
1518 }
1519
1520 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1521 e = ID->propimpl_end(); i != e; ++i) {
1522 ObjCPropertyImplDecl *PID = *i;
1523
1524 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1525 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1526
1527 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1528 if (llvm::Constant *C = GetMethodConstant(MD))
1529 InstanceMethods.push_back(C);
1530 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1531 if (llvm::Constant *C = GetMethodConstant(MD))
1532 InstanceMethods.push_back(C);
1533 }
1534 }
1535
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001536 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001537 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001538 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001539 // Record a reference to the super class.
1540 LazySymbols.insert(Super->getIdentifier());
1541
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001542 Values[ 1] =
1543 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1544 ObjCTypes.ClassPtrTy);
1545 } else {
1546 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1547 }
1548 Values[ 2] = GetClassName(ID->getIdentifier());
1549 // Version is always 0.
1550 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1551 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1552 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001553 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001554 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001555 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001556 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001557 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001558 // cache is always NULL.
1559 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1560 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001561 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001562 // Values[10] = BuildIvarLayout(ID, true);
1563 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001564 Values[11] = EmitClassExtension(ID);
1565 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1566 Values);
1567
1568 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001569 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1570 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001571 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001572 DefinedClasses.push_back(GV);
1573}
1574
1575llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1576 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001577 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001578 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001579 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001580 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001581
Daniel Dunbar04d40782009-04-14 06:00:08 +00001582 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001583 Flags |= eClassFlags_Hidden;
1584
1585 std::vector<llvm::Constant*> Values(12);
1586 // The isa for the metaclass is the root of the hierarchy.
1587 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1588 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1589 Root = Super;
1590 Values[ 0] =
1591 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1592 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001593 // The super class for the metaclass is emitted as the name of the
1594 // super class. The runtime fixes this up to point to the
1595 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001596 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1597 Values[ 1] =
1598 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1599 ObjCTypes.ClassPtrTy);
1600 } else {
1601 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1602 }
1603 Values[ 2] = GetClassName(ID->getIdentifier());
1604 // Version is always 0.
1605 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1606 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1607 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001608 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001609 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001610 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001611 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001612 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001613 // cache is always NULL.
1614 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1615 Values[ 9] = Protocols;
1616 // ivar_layout for metaclass is always NULL.
1617 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1618 // The class extension is always unused for metaclasses.
1619 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1620 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1621 Values);
1622
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001623 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001624 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001625
1626 // Check for a forward reference.
1627 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1628 if (GV) {
1629 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1630 "Forward metaclass reference has incorrect type.");
1631 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1632 GV->setInitializer(Init);
1633 } else {
1634 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1635 llvm::GlobalValue::InternalLinkage,
1636 Init, Name,
1637 &CGM.getModule());
1638 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001639 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001640 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001641 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001642
1643 return GV;
1644}
1645
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001646llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001647 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001648
1649 // FIXME: Should we look these up somewhere other than the
1650 // module. Its a bit silly since we only generate these while
1651 // processing an implementation, so exactly one pointer would work
1652 // if know when we entered/exitted an implementation block.
1653
1654 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001655 // Previously, metaclass with internal linkage may have been defined.
1656 // pass 'true' as 2nd argument so it is returned.
1657 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001658 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1659 "Forward metaclass reference has incorrect type.");
1660 return GV;
1661 } else {
1662 // Generate as an external reference to keep a consistent
1663 // module. This will be patched up when we emit the metaclass.
1664 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1665 llvm::GlobalValue::ExternalLinkage,
1666 0,
1667 Name,
1668 &CGM.getModule());
1669 }
1670}
1671
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001672/*
1673 struct objc_class_ext {
1674 uint32_t size;
1675 const char *weak_ivar_layout;
1676 struct _objc_property_list *properties;
1677 };
1678*/
1679llvm::Constant *
1680CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1681 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001682 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001683
1684 std::vector<llvm::Constant*> Values(3);
1685 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001686 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001687 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001688 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001689 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001690 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001691
1692 // Return null if no extension bits are used.
1693 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1694 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1695
1696 llvm::Constant *Init =
1697 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001698 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001699 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1700 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001701}
1702
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001703/// getInterfaceDeclForIvar - Get the interface declaration node where
1704/// this ivar is declared in.
1705/// FIXME. Ideally, this info should be in the ivar node. But currently
1706/// it is not and prevailing wisdom is that ASTs should not have more
1707/// info than is absolutely needed, even though this info reflects the
1708/// source language.
1709///
1710static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1711 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001712 const ObjCIvarDecl *IVD,
1713 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001714 if (!OI)
1715 return 0;
1716 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1717 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1718 E = OI->ivar_end(); I != E; ++I)
1719 if ((*I)->getIdentifier() == IVD->getIdentifier())
1720 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001721 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001722 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1723 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001724 ObjCPropertyDecl *PDecl = (*I);
1725 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1726 if (IV->getIdentifier() == IVD->getIdentifier())
1727 return OI;
1728 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001729 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001730}
1731
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001732/*
1733 struct objc_ivar {
1734 char *ivar_name;
1735 char *ivar_type;
1736 int ivar_offset;
1737 };
1738
1739 struct objc_ivar_list {
1740 int ivar_count;
1741 struct objc_ivar list[count];
1742 };
1743 */
1744llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001745 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001746 std::vector<llvm::Constant*> Ivars, Ivar(3);
1747
1748 // When emitting the root class GCC emits ivar entries for the
1749 // actual class structure. It is not clear if we need to follow this
1750 // behavior; for now lets try and get away with not doing it. If so,
1751 // the cleanest solution would be to make up an ObjCInterfaceDecl
1752 // for the class.
1753 if (ForClass)
1754 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001755
1756 ObjCInterfaceDecl *OID =
1757 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001758 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001759
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001760 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1761 GetNamedIvarList(OID, OIvars);
1762
1763 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1764 ObjCIvarDecl *IVD = OIvars[i];
1765 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001766 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00001767 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00001768 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
1769 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001770 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001771 }
1772
1773 // Return null for empty list.
1774 if (Ivars.empty())
1775 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1776
1777 std::vector<llvm::Constant*> Values(2);
1778 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1779 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1780 Ivars.size());
1781 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1782 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1783
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001784 llvm::GlobalVariable *GV;
1785 if (ForClass)
1786 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001787 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1788 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001789 else
1790 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1791 + ID->getNameAsString(),
1792 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001793 4, true);
1794 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001795}
1796
1797/*
1798 struct objc_method {
1799 SEL method_name;
1800 char *method_types;
1801 void *method;
1802 };
1803
1804 struct objc_method_list {
1805 struct objc_method_list *obsolete;
1806 int count;
1807 struct objc_method methods_list[count];
1808 };
1809*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001810
1811/// GetMethodConstant - Return a struct objc_method constant for the
1812/// given method if it has been defined. The result is null if the
1813/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001814llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001815 // FIXME: Use DenseMap::lookup
1816 llvm::Function *Fn = MethodDefinitions[MD];
1817 if (!Fn)
1818 return 0;
1819
1820 std::vector<llvm::Constant*> Method(3);
1821 Method[0] =
1822 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1823 ObjCTypes.SelectorPtrTy);
1824 Method[1] = GetMethodVarType(MD);
1825 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1826 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1827}
1828
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001829llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1830 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001831 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001832 // Return null for empty list.
1833 if (Methods.empty())
1834 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1835
1836 std::vector<llvm::Constant*> Values(3);
1837 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1838 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1839 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1840 Methods.size());
1841 Values[2] = llvm::ConstantArray::get(AT, Methods);
1842 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1843
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001844 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001845 return llvm::ConstantExpr::getBitCast(GV,
1846 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001847}
1848
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001849llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001850 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001851 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001852 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001853
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001854 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001855 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001856 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001857 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001858 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001859 llvm::GlobalValue::InternalLinkage,
1860 Name,
1861 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001862 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001863
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001864 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001865}
1866
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001867uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001868 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001869 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001870 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1871
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001872 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001873 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1874 // FIXME: The "field no" for bitfields is something completely
1875 // different; it is the offset in multiples of the base type size!
1876 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1877 const llvm::Type *Ty =
1878 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1879 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1880 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001881}
1882
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001883/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001884uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1885 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001886 const FieldDecl *Field) {
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00001887 // Is this a c struct?
1888 if (!OI)
1889 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001890 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001891 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1892 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001893}
1894
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001895llvm::GlobalVariable *
1896CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1897 llvm::Constant *Init,
1898 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001899 unsigned Align,
1900 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001901 const llvm::Type *Ty = Init->getType();
1902 llvm::GlobalVariable *GV =
1903 new llvm::GlobalVariable(Ty, false,
1904 llvm::GlobalValue::InternalLinkage,
1905 Init,
1906 Name,
1907 &CGM.getModule());
1908 if (Section)
1909 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001910 if (Align)
1911 GV->setAlignment(Align);
1912 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001913 UsedGlobals.push_back(GV);
1914 return GV;
1915}
1916
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001917llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001918 // Abuse this interface function as a place to finalize.
1919 FinishModule();
1920
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001921 return NULL;
1922}
1923
Chris Lattner74391b42009-03-22 21:03:39 +00001924llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001925 return ObjCTypes.GetPropertyFn;
1926}
1927
Chris Lattner74391b42009-03-22 21:03:39 +00001928llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001929 return ObjCTypes.SetPropertyFn;
1930}
1931
Chris Lattner74391b42009-03-22 21:03:39 +00001932llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001933 return ObjCTypes.EnumerationMutationFn;
1934}
1935
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001936/*
1937
1938Objective-C setjmp-longjmp (sjlj) Exception Handling
1939--
1940
1941The basic framework for a @try-catch-finally is as follows:
1942{
1943 objc_exception_data d;
1944 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001945 bool _call_try_exit = true;
1946
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001947 objc_exception_try_enter(&d);
1948 if (!setjmp(d.jmp_buf)) {
1949 ... try body ...
1950 } else {
1951 // exception path
1952 id _caught = objc_exception_extract(&d);
1953
1954 // enter new try scope for handlers
1955 if (!setjmp(d.jmp_buf)) {
1956 ... match exception and execute catch blocks ...
1957
1958 // fell off end, rethrow.
1959 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001960 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001961 } else {
1962 // exception in catch block
1963 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001964 _call_try_exit = false;
1965 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001966 }
1967 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001968 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001969
1970finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001971 if (_call_try_exit)
1972 objc_exception_try_exit(&d);
1973
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001974 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001975 ... dispatch to finally destination ...
1976
1977finally_rethrow:
1978 objc_exception_throw(_rethrow);
1979
1980finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001981}
1982
1983This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001984uses _rethrow to determine if objc_exception_try_exit should be called
1985and if the object should be rethrown. This breaks in the face of
1986throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001987
1988We specialize this framework for a few particular circumstances:
1989
1990 - If there are no catch blocks, then we avoid emitting the second
1991 exception handling context.
1992
1993 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1994 e)) we avoid emitting the code to rethrow an uncaught exception.
1995
1996 - FIXME: If there is no @finally block we can do a few more
1997 simplifications.
1998
1999Rethrows and Jumps-Through-Finally
2000--
2001
2002Support for implicit rethrows and jumping through the finally block is
2003handled by storing the current exception-handling context in
2004ObjCEHStack.
2005
Daniel Dunbar898d5082008-09-30 01:06:03 +00002006In order to implement proper @finally semantics, we support one basic
2007mechanism for jumping through the finally block to an arbitrary
2008destination. Constructs which generate exits from a @try or @catch
2009block use this mechanism to implement the proper semantics by chaining
2010jumps, as necessary.
2011
2012This mechanism works like the one used for indirect goto: we
2013arbitrarily assign an ID to each destination and store the ID for the
2014destination in a variable prior to entering the finally block. At the
2015end of the finally block we simply create a switch to the proper
2016destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002017
2018Code gen for @synchronized(expr) stmt;
2019Effectively generating code for:
2020objc_sync_enter(expr);
2021@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002022*/
2023
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002024void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2025 const Stmt &S) {
2026 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002027 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002028 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002029 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002030 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2031 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2032 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002033
2034 // For @synchronized, call objc_sync_enter(sync.expr). The
2035 // evaluation of the expression must occur before we enter the
2036 // @synchronized. We can safely avoid a temp here because jumps into
2037 // @synchronized are illegal & this will dominate uses.
2038 llvm::Value *SyncArg = 0;
2039 if (!isTry) {
2040 SyncArg =
2041 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2042 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002043 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002044 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002045
2046 // Push an EH context entry, used for handling rethrows and jumps
2047 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002048 CGF.PushCleanupBlock(FinallyBlock);
2049
Anders Carlsson273558f2009-02-07 21:37:21 +00002050 CGF.ObjCEHValueStack.push_back(0);
2051
Daniel Dunbar898d5082008-09-30 01:06:03 +00002052 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002053 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2054 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002055 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2056 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002057 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2058 "_call_try_exit");
2059 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2060
Anders Carlsson80f25672008-09-09 17:59:25 +00002061 // Enter a new try block and call setjmp.
2062 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2063 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2064 "jmpbufarray");
2065 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2066 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2067 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002068
Daniel Dunbar55e87422008-11-11 02:29:29 +00002069 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2070 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002071 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002072 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002073
2074 // Emit the @try block.
2075 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002076 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2077 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002078 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002079
2080 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002081 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002082
2083 // Retrieve the exception object. We may emit multiple blocks but
2084 // nothing can cross this so the value is already in SSA form.
2085 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2086 ExceptionData,
2087 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002088 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002089 if (!isTry)
2090 {
2091 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002092 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002093 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002094 }
2095 else if (const ObjCAtCatchStmt* CatchStmt =
2096 cast<ObjCAtTryStmt>(S).getCatchStmts())
2097 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002098 // Enter a new exception try block (in case a @catch block throws
2099 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002100 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002101
Anders Carlsson80f25672008-09-09 17:59:25 +00002102 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2103 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002104 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002105
Daniel Dunbar55e87422008-11-11 02:29:29 +00002106 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2107 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002108 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002109
2110 CGF.EmitBlock(CatchBlock);
2111
Daniel Dunbar55e40722008-09-27 07:03:52 +00002112 // Handle catch list. As a special case we check if everything is
2113 // matched and avoid generating code for falling off the end if
2114 // so.
2115 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002116 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002117 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002118
Steve Naroff7ba138a2009-03-03 19:52:17 +00002119 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002120 const PointerType *PT = 0;
2121
Anders Carlsson80f25672008-09-09 17:59:25 +00002122 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002123 if (!CatchParam) {
2124 AllMatched = true;
2125 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002126 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002127
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002128 // catch(id e) always matches.
2129 // FIXME: For the time being we also match id<X>; this should
2130 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002131 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002132 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002133 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002134 }
2135
Daniel Dunbar55e40722008-09-27 07:03:52 +00002136 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002137 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002138 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002139 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002140 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002141 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002142
Anders Carlssondde0a942008-09-11 09:15:33 +00002143 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002144 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002145 break;
2146 }
2147
Daniel Dunbar129271a2008-09-27 07:36:24 +00002148 assert(PT && "Unexpected non-pointer type in @catch");
2149 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002150 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002151 assert(ObjCType && "Catch parameter must have Objective-C type!");
2152
2153 // Check if the @catch block matches the exception object.
2154 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2155
Anders Carlsson80f25672008-09-09 17:59:25 +00002156 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2157 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002158
Daniel Dunbar55e87422008-11-11 02:29:29 +00002159 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002160
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002161 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002162 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002163
2164 // Emit the @catch block.
2165 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002166 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002167 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002168
2169 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002170 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002171 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002172 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002173
2174 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002175 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002176
2177 CGF.EmitBlock(NextCatchBlock);
2178 }
2179
Daniel Dunbar55e40722008-09-27 07:03:52 +00002180 if (!AllMatched) {
2181 // None of the handlers caught the exception, so store it to be
2182 // rethrown at the end of the @finally block.
2183 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002184 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002185 }
2186
2187 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002188 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002189 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2190 ExceptionData),
2191 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002192 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002193 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002194 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002195 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002196 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002197 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002198 }
2199
Daniel Dunbar898d5082008-09-30 01:06:03 +00002200 // Pop the exception-handling stack entry. It is important to do
2201 // this now, because the code in the @finally block is not in this
2202 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002203 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2204
Anders Carlsson273558f2009-02-07 21:37:21 +00002205 CGF.ObjCEHValueStack.pop_back();
2206
Anders Carlsson80f25672008-09-09 17:59:25 +00002207 // Emit the @finally block.
2208 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002209 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2210
2211 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2212
2213 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002214 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002215
2216 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002217 if (isTry) {
2218 if (const ObjCAtFinallyStmt* FinallyStmt =
2219 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2220 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002221 } else {
2222 // Emit objc_sync_exit(expr); as finally's sole statement for
2223 // @synchronized.
2224 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002225 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002226
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002227 // Emit the switch block
2228 if (Info.SwitchBlock)
2229 CGF.EmitBlock(Info.SwitchBlock);
2230 if (Info.EndBlock)
2231 CGF.EmitBlock(Info.EndBlock);
2232
Daniel Dunbar898d5082008-09-30 01:06:03 +00002233 CGF.EmitBlock(FinallyRethrow);
2234 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2235 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002236 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002237
2238 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002239}
2240
2241void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002242 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002243 llvm::Value *ExceptionAsObject;
2244
2245 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2246 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2247 ExceptionAsObject =
2248 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2249 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002250 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002251 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002252 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002253 }
2254
2255 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002256 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002257
2258 // Clear the insertion point to indicate we are in unreachable code.
2259 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002260}
2261
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002262/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002263/// object: objc_read_weak (id *src)
2264///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002265llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002266 llvm::Value *AddrWeakObj)
2267{
Eli Friedman8339b352009-03-07 03:57:15 +00002268 const llvm::Type* DestTy =
2269 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002270 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002271 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002272 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002273 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002274 return read_weak;
2275}
2276
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002277/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2278/// objc_assign_weak (id src, id *dst)
2279///
2280void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2281 llvm::Value *src, llvm::Value *dst)
2282{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002283 const llvm::Type * SrcTy = src->getType();
2284 if (!isa<llvm::PointerType>(SrcTy)) {
2285 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2286 assert(Size <= 8 && "does not support size > 8");
2287 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2288 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002289 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2290 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002291 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2292 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002293 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002294 src, dst, "weakassign");
2295 return;
2296}
2297
Fariborz Jahanian58626502008-11-19 00:59:10 +00002298/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2299/// objc_assign_global (id src, id *dst)
2300///
2301void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2302 llvm::Value *src, llvm::Value *dst)
2303{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002304 const llvm::Type * SrcTy = src->getType();
2305 if (!isa<llvm::PointerType>(SrcTy)) {
2306 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2307 assert(Size <= 8 && "does not support size > 8");
2308 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2309 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002310 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2311 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002312 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2313 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002314 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2315 src, dst, "globalassign");
2316 return;
2317}
2318
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002319/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2320/// objc_assign_ivar (id src, id *dst)
2321///
2322void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2323 llvm::Value *src, llvm::Value *dst)
2324{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002325 const llvm::Type * SrcTy = src->getType();
2326 if (!isa<llvm::PointerType>(SrcTy)) {
2327 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2328 assert(Size <= 8 && "does not support size > 8");
2329 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2330 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002331 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2332 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002333 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2334 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2335 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2336 src, dst, "assignivar");
2337 return;
2338}
2339
Fariborz Jahanian58626502008-11-19 00:59:10 +00002340/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2341/// objc_assign_strongCast (id src, id *dst)
2342///
2343void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2344 llvm::Value *src, llvm::Value *dst)
2345{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002346 const llvm::Type * SrcTy = src->getType();
2347 if (!isa<llvm::PointerType>(SrcTy)) {
2348 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2349 assert(Size <= 8 && "does not support size > 8");
2350 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2351 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002352 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2353 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002354 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2355 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002356 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2357 src, dst, "weakassign");
2358 return;
2359}
2360
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002361/// EmitObjCValueForIvar - Code Gen for ivar reference.
2362///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002363LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2364 QualType ObjectTy,
2365 llvm::Value *BaseValue,
2366 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002367 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002368 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2369 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002370 if (Ivar->isBitField())
2371 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2372 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002373 // TODO: Add a special case for isa (index 0)
2374 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2375 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002376 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002377 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2378 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002379 LValue::SetObjCIvar(LV, true);
2380 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002381}
2382
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002383llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2384 ObjCInterfaceDecl *Interface,
2385 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002386 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002387 const FieldDecl *Field =
2388 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002389 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002390 return llvm::ConstantInt::get(
2391 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2392 Offset);
2393}
2394
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002395/* *** Private Interface *** */
2396
2397/// EmitImageInfo - Emit the image info marker used to encode some module
2398/// level information.
2399///
2400/// See: <rdr://4810609&4810587&4810587>
2401/// struct IMAGE_INFO {
2402/// unsigned version;
2403/// unsigned flags;
2404/// };
2405enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002406 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2407 // this implies.
2408 eImageInfo_GarbageCollected = (1 << 1),
2409 eImageInfo_GCOnly = (1 << 2),
2410 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2411
2412 // A flag indicating that the module has no instances of an
2413 // @synthesize of a superclass variable. <rdar://problem/6803242>
2414 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002415};
2416
2417void CGObjCMac::EmitImageInfo() {
2418 unsigned version = 0; // Version is unused?
2419 unsigned flags = 0;
2420
2421 // FIXME: Fix and continue?
2422 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2423 flags |= eImageInfo_GarbageCollected;
2424 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2425 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002426
2427 // We never allow @synthesize of a superclass property.
2428 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002429
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002430 // Emitted as int[2];
2431 llvm::Constant *values[2] = {
2432 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2433 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2434 };
2435 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002436
2437 const char *Section;
2438 if (ObjCABI == 1)
2439 Section = "__OBJC, __image_info,regular";
2440 else
2441 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002442 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002443 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2444 llvm::ConstantArray::get(AT, values, 2),
2445 Section,
2446 0,
2447 true);
2448 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002449}
2450
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002451
2452// struct objc_module {
2453// unsigned long version;
2454// unsigned long size;
2455// const char *name;
2456// Symtab symtab;
2457// };
2458
2459// FIXME: Get from somewhere
2460static const int ModuleVersion = 7;
2461
2462void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002463 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002464
2465 std::vector<llvm::Constant*> Values(4);
2466 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2467 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002468 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002469 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002470 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002471 CreateMetadataVar("\01L_OBJC_MODULES",
2472 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2473 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002474 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002475}
2476
2477llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002478 unsigned NumClasses = DefinedClasses.size();
2479 unsigned NumCategories = DefinedCategories.size();
2480
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002481 // Return null if no symbols were defined.
2482 if (!NumClasses && !NumCategories)
2483 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2484
2485 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002486 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2487 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2488 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2489 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2490
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002491 // The runtime expects exactly the list of defined classes followed
2492 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002493 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002494 for (unsigned i=0; i<NumClasses; i++)
2495 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2496 ObjCTypes.Int8PtrTy);
2497 for (unsigned i=0; i<NumCategories; i++)
2498 Symbols[NumClasses + i] =
2499 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2500 ObjCTypes.Int8PtrTy);
2501
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002502 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002503 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002504 NumClasses + NumCategories),
2505 Symbols);
2506
2507 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2508
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002509 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002510 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2511 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002512 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002513 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2514}
2515
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002516llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002517 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002518 LazySymbols.insert(ID->getIdentifier());
2519
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002520 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2521
2522 if (!Entry) {
2523 llvm::Constant *Casted =
2524 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2525 ObjCTypes.ClassPtrTy);
2526 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002527 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2528 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002529 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002530 }
2531
2532 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002533}
2534
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002535llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002536 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2537
2538 if (!Entry) {
2539 llvm::Constant *Casted =
2540 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2541 ObjCTypes.SelectorPtrTy);
2542 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002543 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2544 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002545 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002546 }
2547
2548 return Builder.CreateLoad(Entry, false, "tmp");
2549}
2550
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002551llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002552 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002553
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002554 if (!Entry)
2555 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2556 llvm::ConstantArray::get(Ident->getName()),
2557 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002558 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002559
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002560 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002561}
2562
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002563/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2564/// interface declaration.
2565const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2566 const ObjCInterfaceDecl *OID) const {
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002567 // FIXME: When does this happen? It seems pretty bad to do this...
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002568 if (OID->isForwardDecl())
2569 return CGM.getTargetData().getStructLayout(llvm::StructType::get(NULL,
2570 NULL));
2571
2572 QualType T =
2573 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2574 const llvm::StructType *InterfaceTy =
2575 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2576 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002577}
2578
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002579/// GetIvarLayoutName - Returns a unique constant for the given
2580/// ivar layout bitmap.
2581llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2582 const ObjCCommonTypesHelper &ObjCTypes) {
2583 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2584}
2585
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002586void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2587 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002588 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002589 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002590 unsigned int BytePos, bool ForStrongLayout,
2591 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002592 bool IsUnion = (RD && RD->isUnion());
2593 uint64_t MaxUnionIvarSize = 0;
2594 uint64_t MaxSkippedUnionIvarSize = 0;
2595 FieldDecl *MaxField = 0;
2596 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002597 FieldDecl *LastFieldBitfield = 0;
2598
Chris Lattnerf1690852009-03-31 08:48:01 +00002599 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002600 if (RecFields.empty())
2601 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002602 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002603 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002604 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2605 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2606
2607 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2608
2609 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002610 FieldDecl *Field = RecFields[i];
2611 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002612 if (!Field->getIdentifier() || Field->isBitField()) {
2613 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002614 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002615 }
2616 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002617 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002618 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002619 if (FQT->isUnionType())
2620 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002621 else
2622 assert(FQT->isRecordType() &&
2623 "only union/record is supported for ivar layout bitmap");
2624
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002625 const RecordType *RT = FQT->getAsRecordType();
2626 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002627 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002628 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2629 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002630 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2631 const llvm::StructLayout *RecLayout =
2632 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2633
2634 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002635 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002636 ForStrongLayout, Index, SkIndex,
2637 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002638 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002639 continue;
2640 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002641
2642 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002643 const ConstantArrayType *CArray =
2644 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002645 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002646 assert(CArray && "only array with know element size is supported");
2647 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002648 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2649 const ConstantArrayType *CArray =
2650 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002651 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002652 FQT = CArray->getElementType();
2653 }
2654
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002655 assert(!FQT->isUnionType() &&
2656 "layout for array of unions not supported");
2657 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002658 int OldIndex = Index;
2659 int OldSkIndex = SkIndex;
2660
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002661 // FIXME - Use a common routine with the above!
2662 const RecordType *RT = FQT->getAsRecordType();
2663 const RecordDecl *RD = RT->getDecl();
2664 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002665 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2666 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002667 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2668 const llvm::StructLayout *RecLayout =
2669 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002670
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002671 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002672 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002673 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002674 ForStrongLayout, Index, SkIndex,
2675 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002676 TmpRecFields.clear();
2677
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002678 // Replicate layout information for each array element. Note that
2679 // one element is already done.
2680 uint64_t ElIx = 1;
2681 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2682 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002683 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002684 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2685 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002686 GC_IVAR gcivar;
2687 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2688 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2689 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002690 }
2691
Chris Lattnerf1690852009-03-31 08:48:01 +00002692 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002693 GC_IVAR skivar;
2694 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2695 skivar.ivar_size = SkipIvars[i].ivar_size;
2696 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002697 }
2698 }
2699 continue;
2700 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002701 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002702 // At this point, we are done with Record/Union and array there of.
2703 // For other arrays we are down to its element type.
2704 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2705 do {
2706 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2707 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2708 break;
2709 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002710 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002711 GCAttr = QualType::Strong;
2712 break;
2713 }
2714 else if (const PointerType *PT = FQT->getAsPointerType()) {
2715 FQT = PT->getPointeeType();
2716 }
2717 else {
2718 break;
2719 }
2720 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002721
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002722 if ((ForStrongLayout && GCAttr == QualType::Strong)
2723 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2724 if (IsUnion)
2725 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002726 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2727 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002728 if (UnionIvarSize > MaxUnionIvarSize)
2729 {
2730 MaxUnionIvarSize = UnionIvarSize;
2731 MaxField = Field;
2732 }
2733 }
2734 else
2735 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002736 GC_IVAR gcivar;
2737 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2738 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2739 WordSizeInBits;
2740 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002741 }
2742 }
2743 else if ((ForStrongLayout &&
2744 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2745 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2746 if (IsUnion)
2747 {
2748 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2749 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2750 {
2751 MaxSkippedUnionIvarSize = UnionIvarSize;
2752 MaxSkippedField = Field;
2753 }
2754 }
2755 else
2756 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002757 GC_IVAR skivar;
2758 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2759 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002760 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002761 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002762 }
2763 }
2764 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002765 if (LastFieldBitfield) {
2766 // Last field was a bitfield. Must update skip info.
2767 GC_IVAR skivar;
2768 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
2769 LastFieldBitfield);
2770 Expr *BitWidth = LastFieldBitfield->getBitWidth();
2771 uint64_t BitFieldSize =
2772 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
2773 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
2774 + ((BitFieldSize % ByteSizeInBits) != 0);
2775 SkipIvars.push_back(skivar); ++SkIndex;
2776 }
2777
Chris Lattnerf1690852009-03-31 08:48:01 +00002778 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002779 GC_IVAR gcivar;
2780 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2781 gcivar.ivar_size = MaxUnionIvarSize;
2782 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002783 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002784
2785 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002786 GC_IVAR skivar;
2787 skivar.ivar_bytepos = BytePos +
2788 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2789 skivar.ivar_size = MaxSkippedUnionIvarSize;
2790 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002791 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002792}
2793
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002794static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002795IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002796{
2797 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2798 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2799
2800 if (sa < sb)
2801 return -1;
2802 if (sa > sb)
2803 return 1;
2804 return 0;
2805}
2806
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002807/// BuildIvarLayout - Builds ivar layout bitmap for the class
2808/// implementation for the __strong or __weak case.
2809/// The layout map displays which words in ivar list must be skipped
2810/// and which must be scanned by GC (see below). String is built of bytes.
2811/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2812/// of words to skip and right nibble is count of words to scan. So, each
2813/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2814/// represented by a 0x00 byte which also ends the string.
2815/// 1. when ForStrongLayout is true, following ivars are scanned:
2816/// - id, Class
2817/// - object *
2818/// - __strong anything
2819///
2820/// 2. When ForStrongLayout is false, following ivars are scanned:
2821/// - __weak anything
2822///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002823llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002824 const ObjCImplementationDecl *OMD,
2825 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002826 int Index = -1;
2827 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002828 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002829 int SkipScan;
2830 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002831 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2832 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2833 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002834
Chris Lattnerf1690852009-03-31 08:48:01 +00002835 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002836 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002837 CGM.getContext().CollectObjCIvars(OI, RecFields);
2838 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002839 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002840
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002841 SkipIvars.clear();
2842 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002843
2844 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002845 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2846 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002847 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002848 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002849
2850 // Sort on byte position in case we encounterred a union nested in
2851 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002852 if (hasUnion && !IvarsInfo.empty())
2853 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2854 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002855 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2856
2857 // Build the string of skip/scan nibbles
2858 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002859 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002860 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002861 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002862 if (IvarsInfo[0].ivar_bytepos == 0) {
2863 WordsToSkip = 0;
2864 WordsToScan = IvarsInfo[0].ivar_size;
2865 }
2866 else {
2867 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2868 WordsToScan = IvarsInfo[0].ivar_size;
2869 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002870 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002871 {
2872 unsigned int TailPrevGCObjC =
2873 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2874 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2875 {
2876 // consecutive 'scanned' object pointers.
2877 WordsToScan += IvarsInfo[i].ivar_size;
2878 }
2879 else
2880 {
2881 // Skip over 'gc'able object pointer which lay over each other.
2882 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2883 continue;
2884 // Must skip over 1 or more words. We save current skip/scan values
2885 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002886 SKIP_SCAN SkScan;
2887 SkScan.skip = WordsToSkip;
2888 SkScan.scan = WordsToScan;
2889 SkipScanIvars.push_back(SkScan); ++SkipScan;
2890
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002891 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002892 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2893 SkScan.scan = 0;
2894 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002895 WordsToSkip = 0;
2896 WordsToScan = IvarsInfo[i].ivar_size;
2897 }
2898 }
2899 if (WordsToScan > 0)
2900 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002901 SKIP_SCAN SkScan;
2902 SkScan.skip = WordsToSkip;
2903 SkScan.scan = WordsToScan;
2904 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002905 }
2906
2907 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002908 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002909 {
2910 int LastByteSkipped =
2911 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2912 int LastByteScanned =
2913 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2914 BytesSkipped = (LastByteSkipped > LastByteScanned);
2915 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2916 if (BytesSkipped)
2917 {
2918 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002919 SKIP_SCAN SkScan;
2920 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2921 SkScan.scan = 0;
2922 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002923 }
2924 }
2925 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2926 // as 0xMN.
2927 for (int i = 0; i <= SkipScan; i++)
2928 {
2929 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2930 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2931 // 0xM0 followed by 0x0N detected.
2932 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2933 for (int j = i+1; j < SkipScan; j++)
2934 SkipScanIvars[j] = SkipScanIvars[j+1];
2935 --SkipScan;
2936 }
2937 }
2938
2939 // Generate the string.
2940 std::string BitMap;
2941 for (int i = 0; i <= SkipScan; i++)
2942 {
2943 unsigned char byte;
2944 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2945 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2946 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2947 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2948
2949 if (skip_small > 0 || skip_big > 0)
2950 BytesSkipped = true;
2951 // first skip big.
2952 for (unsigned int ix = 0; ix < skip_big; ix++)
2953 BitMap += (unsigned char)(0xf0);
2954
2955 // next (skip small, scan)
2956 if (skip_small)
2957 {
2958 byte = skip_small << 4;
2959 if (scan_big > 0)
2960 {
2961 byte |= 0xf;
2962 --scan_big;
2963 }
2964 else if (scan_small)
2965 {
2966 byte |= scan_small;
2967 scan_small = 0;
2968 }
2969 BitMap += byte;
2970 }
2971 // next scan big
2972 for (unsigned int ix = 0; ix < scan_big; ix++)
2973 BitMap += (unsigned char)(0x0f);
2974 // last scan small
2975 if (scan_small)
2976 {
2977 byte = scan_small;
2978 BitMap += byte;
2979 }
2980 }
2981 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002982 unsigned char zero = 0;
2983 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002984
2985 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
2986 printf("\n%s ivar layout for class '%s': ",
2987 ForStrongLayout ? "strong" : "weak",
2988 OMD->getClassInterface()->getNameAsCString());
2989 const unsigned char *s = (unsigned char*)BitMap.c_str();
2990 for (unsigned i = 0; i < BitMap.size(); i++)
2991 if (!(s[i] & 0xf0))
2992 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2993 else
2994 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2995 printf("\n");
2996 }
2997
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002998 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2999 // final layout.
3000 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003001 return llvm::Constant::getNullValue(PtrTy);
3002 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3003 llvm::ConstantArray::get(BitMap.c_str()),
3004 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003005 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003006 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003007}
3008
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003009llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003010 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3011
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003012 // FIXME: Avoid std::string copying.
3013 if (!Entry)
3014 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3015 llvm::ConstantArray::get(Sel.getAsString()),
3016 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003017 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003018
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003019 return getConstantGEP(Entry, 0, 0);
3020}
3021
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003022// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003023llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003024 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3025}
3026
3027// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003028llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003029 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3030}
3031
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003032llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003033 std::string TypeStr;
3034 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3035
3036 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003037
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003038 if (!Entry)
3039 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3040 llvm::ConstantArray::get(TypeStr),
3041 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003042 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003043
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003044 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003045}
3046
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003047llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003048 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003049 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3050 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003051
3052 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3053
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003054 if (!Entry)
3055 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3056 llvm::ConstantArray::get(TypeStr),
3057 "__TEXT,__cstring,cstring_literals",
3058 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003059
3060 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003061}
3062
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003063// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003064llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003065 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3066
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003067 if (!Entry)
3068 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3069 llvm::ConstantArray::get(Ident->getName()),
3070 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003071 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003072
3073 return getConstantGEP(Entry, 0, 0);
3074}
3075
3076// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003077// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003078llvm::Constant *
3079 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3080 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003081 std::string TypeStr;
3082 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003083 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3084}
3085
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003086void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3087 const ObjCContainerDecl *CD,
3088 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003089 NameOut = '\01';
3090 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003091 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003092 assert (CD && "Missing container decl in GetNameForMethod");
3093 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003094 if (const ObjCCategoryImplDecl *CID =
3095 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3096 NameOut += '(';
3097 NameOut += CID->getNameAsString();
3098 NameOut+= ')';
3099 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003100 NameOut += ' ';
3101 NameOut += D->getSelector().getAsString();
3102 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003103}
3104
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003105void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003106 EmitModuleInfo();
3107
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003108 // Emit the dummy bodies for any protocols which were referenced but
3109 // never defined.
3110 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3111 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3112 if (i->second->hasInitializer())
3113 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003114
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003115 std::vector<llvm::Constant*> Values(5);
3116 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3117 Values[1] = GetClassName(i->first);
3118 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3119 Values[3] = Values[4] =
3120 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3121 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3122 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3123 Values));
3124 }
3125
3126 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003127 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003128 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003129 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003130 }
3131
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003132 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003133 llvm::GlobalValue *GV =
3134 new llvm::GlobalVariable(AT, false,
3135 llvm::GlobalValue::AppendingLinkage,
3136 llvm::ConstantArray::get(AT, Used),
3137 "llvm.used",
3138 &CGM.getModule());
3139
3140 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003141
3142 // Add assembler directives to add lazy undefined symbol references
3143 // for classes which are referenced but not defined. This is
3144 // important for correct linker interaction.
3145
3146 // FIXME: Uh, this isn't particularly portable.
3147 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003148
3149 if (!CGM.getModule().getModuleInlineAsm().empty())
3150 s << "\n";
3151
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003152 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3153 e = LazySymbols.end(); i != e; ++i) {
3154 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3155 }
3156 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3157 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003158 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003159 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3160 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003161
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003162 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003163}
3164
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003165CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003166 : CGObjCCommonMac(cgm),
3167 ObjCTypes(cgm)
3168{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003169 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003170 ObjCABI = 2;
3171}
3172
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003173/* *** */
3174
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003175ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3176: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003177{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003178 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3179 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003180
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003181 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003182 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003183 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003184 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003185 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3186
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003187 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003188 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003189 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003190
3191 // FIXME: It would be nice to unify this with the opaque type, so
3192 // that the IR comes out a bit cleaner.
3193 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3194 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003195
3196 // I'm not sure I like this. The implicit coordination is a bit
3197 // gross. We should solve this in a reasonable fashion because this
3198 // is a pretty common task (match some runtime data structure with
3199 // an LLVM data structure).
3200
3201 // FIXME: This is leaked.
3202 // FIXME: Merge with rewriter code?
3203
3204 // struct _objc_super {
3205 // id self;
3206 // Class cls;
3207 // }
3208 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3209 SourceLocation(),
3210 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003211 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3212 Ctx.getObjCIdType(), 0, false));
3213 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3214 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003215 RD->completeDefinition(Ctx);
3216
3217 SuperCTy = Ctx.getTagDeclType(RD);
3218 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3219
3220 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003221 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3222
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003223 // struct _prop_t {
3224 // char *name;
3225 // char *attributes;
3226 // }
3227 PropertyTy = llvm::StructType::get(Int8PtrTy,
3228 Int8PtrTy,
3229 NULL);
3230 CGM.getModule().addTypeName("struct._prop_t",
3231 PropertyTy);
3232
3233 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003234 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003235 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003236 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003237 // }
3238 PropertyListTy = llvm::StructType::get(IntTy,
3239 IntTy,
3240 llvm::ArrayType::get(PropertyTy, 0),
3241 NULL);
3242 CGM.getModule().addTypeName("struct._prop_list_t",
3243 PropertyListTy);
3244 // struct _prop_list_t *
3245 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3246
3247 // struct _objc_method {
3248 // SEL _cmd;
3249 // char *method_type;
3250 // char *_imp;
3251 // }
3252 MethodTy = llvm::StructType::get(SelectorPtrTy,
3253 Int8PtrTy,
3254 Int8PtrTy,
3255 NULL);
3256 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003257
3258 // struct _objc_cache *
3259 CacheTy = llvm::OpaqueType::get();
3260 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3261 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003262
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003263 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003264
3265 QualType IdType = Ctx.getObjCIdType();
3266 QualType SelType = Ctx.getObjCSelType();
3267 llvm::SmallVector<QualType,16> Params;
3268 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003269
3270 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003271 Params.push_back(IdType);
3272 Params.push_back(SelType);
3273 Params.push_back(Ctx.LongTy);
3274 Params.push_back(Ctx.BoolTy);
3275 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3276 false);
3277 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003278
3279 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3280 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003281 Params.push_back(IdType);
3282 Params.push_back(SelType);
3283 Params.push_back(Ctx.LongTy);
3284 Params.push_back(IdType);
3285 Params.push_back(Ctx.BoolTy);
3286 Params.push_back(Ctx.BoolTy);
3287 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3288 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3289
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003290 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003291
3292 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003293 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003294 Params.push_back(IdType);
3295 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3296 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3297 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003298
3299 // gc's API
3300 // id objc_read_weak (id *)
3301 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003302 Params.push_back(Ctx.getPointerType(IdType));
3303 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3304 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3305
Chris Lattner96508e12009-04-17 22:12:36 +00003306 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003307 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003308 Params.push_back(IdType);
3309 Params.push_back(Ctx.getPointerType(IdType));
3310
3311 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003312 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3313 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3314 GcAssignStrongCastFn =
3315 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003316
3317 // void objc_exception_throw(id)
3318 Params.clear();
3319 Params.push_back(IdType);
3320
3321 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003322 ExceptionThrowFn =
3323 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003324
3325 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003326 // void objc_sync_exit (id)
3327 Params.clear();
3328 Params.push_back(IdType);
3329
3330 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003331 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003332}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003333
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003334ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3335 : ObjCCommonTypesHelper(cgm)
3336{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003337 // struct _objc_method_description {
3338 // SEL name;
3339 // char *types;
3340 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003341 MethodDescriptionTy =
3342 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003343 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003344 NULL);
3345 CGM.getModule().addTypeName("struct._objc_method_description",
3346 MethodDescriptionTy);
3347
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003348 // struct _objc_method_description_list {
3349 // int count;
3350 // struct _objc_method_description[1];
3351 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003352 MethodDescriptionListTy =
3353 llvm::StructType::get(IntTy,
3354 llvm::ArrayType::get(MethodDescriptionTy, 0),
3355 NULL);
3356 CGM.getModule().addTypeName("struct._objc_method_description_list",
3357 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003358
3359 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003360 MethodDescriptionListPtrTy =
3361 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3362
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003363 // Protocol description structures
3364
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003365 // struct _objc_protocol_extension {
3366 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3367 // struct _objc_method_description_list *optional_instance_methods;
3368 // struct _objc_method_description_list *optional_class_methods;
3369 // struct _objc_property_list *instance_properties;
3370 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003371 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003372 llvm::StructType::get(IntTy,
3373 MethodDescriptionListPtrTy,
3374 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003375 PropertyListPtrTy,
3376 NULL);
3377 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3378 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003379
3380 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003381 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3382
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003383 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003384
3385 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3386 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3387
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003388 const llvm::Type *T =
3389 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3390 LongTy,
3391 llvm::ArrayType::get(ProtocolTyHolder, 0),
3392 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003393 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3394
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003395 // struct _objc_protocol {
3396 // struct _objc_protocol_extension *isa;
3397 // char *protocol_name;
3398 // struct _objc_protocol **_objc_protocol_list;
3399 // struct _objc_method_description_list *instance_methods;
3400 // struct _objc_method_description_list *class_methods;
3401 // }
3402 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003403 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003404 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3405 MethodDescriptionListPtrTy,
3406 MethodDescriptionListPtrTy,
3407 NULL);
3408 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3409
3410 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3411 CGM.getModule().addTypeName("struct._objc_protocol_list",
3412 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003413 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003414 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3415
3416 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003417 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003418 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003419
3420 // Class description structures
3421
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003422 // struct _objc_ivar {
3423 // char *ivar_name;
3424 // char *ivar_type;
3425 // int ivar_offset;
3426 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003427 IvarTy = llvm::StructType::get(Int8PtrTy,
3428 Int8PtrTy,
3429 IntTy,
3430 NULL);
3431 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3432
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003433 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003434 IvarListTy = llvm::OpaqueType::get();
3435 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3436 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3437
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003438 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003439 MethodListTy = llvm::OpaqueType::get();
3440 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3441 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3442
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003443 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003444 ClassExtensionTy =
3445 llvm::StructType::get(IntTy,
3446 Int8PtrTy,
3447 PropertyListPtrTy,
3448 NULL);
3449 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3450 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3451
3452 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3453
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003454 // struct _objc_class {
3455 // Class isa;
3456 // Class super_class;
3457 // char *name;
3458 // long version;
3459 // long info;
3460 // long instance_size;
3461 // struct _objc_ivar_list *ivars;
3462 // struct _objc_method_list *methods;
3463 // struct _objc_cache *cache;
3464 // struct _objc_protocol_list *protocols;
3465 // char *ivar_layout;
3466 // struct _objc_class_ext *ext;
3467 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003468 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3469 llvm::PointerType::getUnqual(ClassTyHolder),
3470 Int8PtrTy,
3471 LongTy,
3472 LongTy,
3473 LongTy,
3474 IvarListPtrTy,
3475 MethodListPtrTy,
3476 CachePtrTy,
3477 ProtocolListPtrTy,
3478 Int8PtrTy,
3479 ClassExtensionPtrTy,
3480 NULL);
3481 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3482
3483 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3484 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3485 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3486
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003487 // struct _objc_category {
3488 // char *category_name;
3489 // char *class_name;
3490 // struct _objc_method_list *instance_method;
3491 // struct _objc_method_list *class_method;
3492 // uint32_t size; // sizeof(struct _objc_category)
3493 // struct _objc_property_list *instance_properties;// category's @property
3494 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003495 CategoryTy = llvm::StructType::get(Int8PtrTy,
3496 Int8PtrTy,
3497 MethodListPtrTy,
3498 MethodListPtrTy,
3499 ProtocolListPtrTy,
3500 IntTy,
3501 PropertyListPtrTy,
3502 NULL);
3503 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3504
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003505 // Global metadata structures
3506
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003507 // struct _objc_symtab {
3508 // long sel_ref_cnt;
3509 // SEL *refs;
3510 // short cls_def_cnt;
3511 // short cat_def_cnt;
3512 // char *defs[cls_def_cnt + cat_def_cnt];
3513 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003514 SymtabTy = llvm::StructType::get(LongTy,
3515 SelectorPtrTy,
3516 ShortTy,
3517 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003518 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003519 NULL);
3520 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3521 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3522
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003523 // struct _objc_module {
3524 // long version;
3525 // long size; // sizeof(struct _objc_module)
3526 // char *name;
3527 // struct _objc_symtab* symtab;
3528 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003529 ModuleTy =
3530 llvm::StructType::get(LongTy,
3531 LongTy,
3532 Int8PtrTy,
3533 SymtabPtrTy,
3534 NULL);
3535 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003536
Daniel Dunbar49f66022008-09-24 03:38:44 +00003537 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003538
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003539 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003540 std::vector<const llvm::Type*> Params;
3541 Params.push_back(ObjectPtrTy);
3542 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003543 MessageSendFn =
3544 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3545 Params,
3546 true),
3547 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003548
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003549 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003550 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003551 Params.push_back(ObjectPtrTy);
3552 Params.push_back(SelectorPtrTy);
3553 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003554 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3555 Params,
3556 true),
3557 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003558
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003559 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003560 Params.clear();
3561 Params.push_back(ObjectPtrTy);
3562 Params.push_back(SelectorPtrTy);
3563 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003564 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003565 MessageSendFpretFn =
3566 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3567 Params,
3568 true),
3569 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003570
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003571 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003572 Params.clear();
3573 Params.push_back(SuperPtrTy);
3574 Params.push_back(SelectorPtrTy);
3575 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003576 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3577 Params,
3578 true),
3579 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003580
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003581 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3582 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003583 Params.clear();
3584 Params.push_back(Int8PtrTy);
3585 Params.push_back(SuperPtrTy);
3586 Params.push_back(SelectorPtrTy);
3587 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003588 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3589 Params,
3590 true),
3591 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003592
3593 // There is no objc_msgSendSuper_fpret? How can that work?
3594 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003595
Anders Carlsson124526b2008-09-09 10:10:21 +00003596 // FIXME: This is the size of the setjmp buffer and should be
3597 // target specific. 18 is what's used on 32-bit X86.
3598 uint64_t SetJmpBufferSize = 18;
3599
3600 // Exceptions
3601 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003602 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003603
3604 ExceptionDataTy =
3605 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3606 SetJmpBufferSize),
3607 StackPtrTy, NULL);
3608 CGM.getModule().addTypeName("struct._objc_exception_data",
3609 ExceptionDataTy);
3610
3611 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003612 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3613 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003614 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3615 Params,
3616 false),
3617 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003618 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003619 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3620 Params,
3621 false),
3622 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003623 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003624 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3625 Params,
3626 false),
3627 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003628
3629 Params.clear();
3630 Params.push_back(ClassPtrTy);
3631 Params.push_back(ObjectPtrTy);
3632 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003633 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3634 Params,
3635 false),
3636 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003637
Anders Carlsson124526b2008-09-09 10:10:21 +00003638 Params.clear();
3639 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3640 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003641 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3642 Params,
3643 false),
3644 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003645
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003646}
3647
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003648ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003649: ObjCCommonTypesHelper(cgm)
3650{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003651 // struct _method_list_t {
3652 // uint32_t entsize; // sizeof(struct _objc_method)
3653 // uint32_t method_count;
3654 // struct _objc_method method_list[method_count];
3655 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003656 MethodListnfABITy = llvm::StructType::get(IntTy,
3657 IntTy,
3658 llvm::ArrayType::get(MethodTy, 0),
3659 NULL);
3660 CGM.getModule().addTypeName("struct.__method_list_t",
3661 MethodListnfABITy);
3662 // struct method_list_t *
3663 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003664
3665 // struct _protocol_t {
3666 // id isa; // NULL
3667 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003668 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003669 // const struct method_list_t * const instance_methods;
3670 // const struct method_list_t * const class_methods;
3671 // const struct method_list_t *optionalInstanceMethods;
3672 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003673 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003674 // const uint32_t size; // sizeof(struct _protocol_t)
3675 // const uint32_t flags; // = 0
3676 // }
3677
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003678 // Holder for struct _protocol_list_t *
3679 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3680
3681 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3682 Int8PtrTy,
3683 llvm::PointerType::getUnqual(
3684 ProtocolListTyHolder),
3685 MethodListnfABIPtrTy,
3686 MethodListnfABIPtrTy,
3687 MethodListnfABIPtrTy,
3688 MethodListnfABIPtrTy,
3689 PropertyListPtrTy,
3690 IntTy,
3691 IntTy,
3692 NULL);
3693 CGM.getModule().addTypeName("struct._protocol_t",
3694 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003695
3696 // struct _protocol_t*
3697 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003698
Fariborz Jahanianda320092009-01-29 19:24:30 +00003699 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003700 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003701 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003702 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003703 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3704 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003705 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003706 NULL);
3707 CGM.getModule().addTypeName("struct._objc_protocol_list",
3708 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003709 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3710 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003711
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003712 // struct _objc_protocol_list*
3713 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003714
3715 // struct _ivar_t {
3716 // unsigned long int *offset; // pointer to ivar offset location
3717 // char *name;
3718 // char *type;
3719 // uint32_t alignment;
3720 // uint32_t size;
3721 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003722 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3723 Int8PtrTy,
3724 Int8PtrTy,
3725 IntTy,
3726 IntTy,
3727 NULL);
3728 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3729
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003730 // struct _ivar_list_t {
3731 // uint32 entsize; // sizeof(struct _ivar_t)
3732 // uint32 count;
3733 // struct _iver_t list[count];
3734 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003735 IvarListnfABITy = llvm::StructType::get(IntTy,
3736 IntTy,
3737 llvm::ArrayType::get(
3738 IvarnfABITy, 0),
3739 NULL);
3740 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3741
3742 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003743
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003744 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003745 // uint32_t const flags;
3746 // uint32_t const instanceStart;
3747 // uint32_t const instanceSize;
3748 // uint32_t const reserved; // only when building for 64bit targets
3749 // const uint8_t * const ivarLayout;
3750 // const char *const name;
3751 // const struct _method_list_t * const baseMethods;
3752 // const struct _objc_protocol_list *const baseProtocols;
3753 // const struct _ivar_list_t *const ivars;
3754 // const uint8_t * const weakIvarLayout;
3755 // const struct _prop_list_t * const properties;
3756 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003757
3758 // FIXME. Add 'reserved' field in 64bit abi mode!
3759 ClassRonfABITy = llvm::StructType::get(IntTy,
3760 IntTy,
3761 IntTy,
3762 Int8PtrTy,
3763 Int8PtrTy,
3764 MethodListnfABIPtrTy,
3765 ProtocolListnfABIPtrTy,
3766 IvarListnfABIPtrTy,
3767 Int8PtrTy,
3768 PropertyListPtrTy,
3769 NULL);
3770 CGM.getModule().addTypeName("struct._class_ro_t",
3771 ClassRonfABITy);
3772
3773 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3774 std::vector<const llvm::Type*> Params;
3775 Params.push_back(ObjectPtrTy);
3776 Params.push_back(SelectorPtrTy);
3777 ImpnfABITy = llvm::PointerType::getUnqual(
3778 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3779
3780 // struct _class_t {
3781 // struct _class_t *isa;
3782 // struct _class_t * const superclass;
3783 // void *cache;
3784 // IMP *vtable;
3785 // struct class_ro_t *ro;
3786 // }
3787
3788 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3789 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3790 llvm::PointerType::getUnqual(ClassTyHolder),
3791 CachePtrTy,
3792 llvm::PointerType::getUnqual(ImpnfABITy),
3793 llvm::PointerType::getUnqual(
3794 ClassRonfABITy),
3795 NULL);
3796 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3797
3798 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3799 ClassnfABITy);
3800
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003801 // LLVM for struct _class_t *
3802 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3803
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003804 // struct _category_t {
3805 // const char * const name;
3806 // struct _class_t *const cls;
3807 // const struct _method_list_t * const instance_methods;
3808 // const struct _method_list_t * const class_methods;
3809 // const struct _protocol_list_t * const protocols;
3810 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003811 // }
3812 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003813 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003814 MethodListnfABIPtrTy,
3815 MethodListnfABIPtrTy,
3816 ProtocolListnfABIPtrTy,
3817 PropertyListPtrTy,
3818 NULL);
3819 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003820
3821 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003822 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3823 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003824
3825 // MessageRefTy - LLVM for:
3826 // struct _message_ref_t {
3827 // IMP messenger;
3828 // SEL name;
3829 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003830
3831 // First the clang type for struct _message_ref_t
3832 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3833 SourceLocation(),
3834 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003835 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3836 Ctx.VoidPtrTy, 0, false));
3837 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3838 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003839 RD->completeDefinition(Ctx);
3840
3841 MessageRefCTy = Ctx.getTagDeclType(RD);
3842 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3843 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003844
3845 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3846 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3847
3848 // SuperMessageRefTy - LLVM for:
3849 // struct _super_message_ref_t {
3850 // SUPER_IMP messenger;
3851 // SEL name;
3852 // };
3853 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3854 SelectorPtrTy,
3855 NULL);
3856 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3857
3858 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3859 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3860
3861 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3862 Params.clear();
3863 Params.push_back(ObjectPtrTy);
3864 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003865 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3866 Params,
3867 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003868 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003869 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003870 "objc_msgSend_fixup");
3871
3872 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3873 MessageSendFpretFixupFn =
3874 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3875 Params,
3876 true),
3877 "objc_msgSend_fpret_fixup");
3878
3879 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3880 MessageSendStretFixupFn =
3881 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3882 Params,
3883 true),
3884 "objc_msgSend_stret_fixup");
3885
3886 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3887 MessageSendIdFixupFn =
3888 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3889 Params,
3890 true),
3891 "objc_msgSendId_fixup");
3892
3893
3894 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3895 MessageSendIdStretFixupFn =
3896 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3897 Params,
3898 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003899 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003900
3901 // id objc_msgSendSuper2_fixup (struct objc_super *,
3902 // struct _super_message_ref_t*, ...)
3903 Params.clear();
3904 Params.push_back(SuperPtrTy);
3905 Params.push_back(SuperMessageRefPtrTy);
3906 MessageSendSuper2FixupFn =
3907 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3908 Params,
3909 true),
3910 "objc_msgSendSuper2_fixup");
3911
3912
3913 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3914 // struct _super_message_ref_t*, ...)
3915 MessageSendSuper2StretFixupFn =
3916 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3917 Params,
3918 true),
3919 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003920
3921 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003922 Params.push_back(Int8PtrTy);
3923 UnwindResumeOrRethrowFn =
3924 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3925 Params,
3926 false),
3927 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003928 ObjCBeginCatchFn =
3929 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3930 Params,
3931 false),
3932 "objc_begin_catch");
3933
3934 Params.clear();
3935 ObjCEndCatchFn =
3936 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3937 Params,
3938 false),
3939 "objc_end_catch");
3940
3941 // struct objc_typeinfo {
3942 // const void** vtable; // objc_ehtype_vtable + 2
3943 // const char* name; // c++ typeinfo string
3944 // Class cls;
3945 // };
3946 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3947 Int8PtrTy,
3948 ClassnfABIPtrTy,
3949 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003950 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003951 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003952}
3953
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003954llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3955 FinishNonFragileABIModule();
3956
3957 return NULL;
3958}
3959
3960void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3961 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003962
3963 // Build list of all implemented classe addresses in array
3964 // L_OBJC_LABEL_CLASS_$.
3965 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3966 // list of 'nonlazy' implementations (defined as those with a +load{}
3967 // method!!).
3968 unsigned NumClasses = DefinedClasses.size();
3969 if (NumClasses) {
3970 std::vector<llvm::Constant*> Symbols(NumClasses);
3971 for (unsigned i=0; i<NumClasses; i++)
3972 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3973 ObjCTypes.Int8PtrTy);
3974 llvm::Constant* Init =
3975 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3976 NumClasses),
3977 Symbols);
3978
3979 llvm::GlobalVariable *GV =
3980 new llvm::GlobalVariable(Init->getType(), false,
3981 llvm::GlobalValue::InternalLinkage,
3982 Init,
3983 "\01L_OBJC_LABEL_CLASS_$",
3984 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003985 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003986 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3987 UsedGlobals.push_back(GV);
3988 }
3989
3990 // Build list of all implemented category addresses in array
3991 // L_OBJC_LABEL_CATEGORY_$.
3992 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3993 // list of 'nonlazy' category implementations (defined as those with a +load{}
3994 // method!!).
3995 unsigned NumCategory = DefinedCategories.size();
3996 if (NumCategory) {
3997 std::vector<llvm::Constant*> Symbols(NumCategory);
3998 for (unsigned i=0; i<NumCategory; i++)
3999 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4000 ObjCTypes.Int8PtrTy);
4001 llvm::Constant* Init =
4002 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4003 NumCategory),
4004 Symbols);
4005
4006 llvm::GlobalVariable *GV =
4007 new llvm::GlobalVariable(Init->getType(), false,
4008 llvm::GlobalValue::InternalLinkage,
4009 Init,
4010 "\01L_OBJC_LABEL_CATEGORY_$",
4011 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004012 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004013 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4014 UsedGlobals.push_back(GV);
4015 }
4016
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004017 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4018 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4019 std::vector<llvm::Constant*> Values(2);
4020 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004021 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004022 // FIXME: Fix and continue?
4023 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4024 flags |= eImageInfo_GarbageCollected;
4025 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4026 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004027 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004028 llvm::Constant* Init = llvm::ConstantArray::get(
4029 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4030 Values);
4031 llvm::GlobalVariable *IMGV =
4032 new llvm::GlobalVariable(Init->getType(), false,
4033 llvm::GlobalValue::InternalLinkage,
4034 Init,
4035 "\01L_OBJC_IMAGE_INFO",
4036 &CGM.getModule());
4037 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4038 UsedGlobals.push_back(IMGV);
4039
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004040 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004041
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004042 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4043 e = UsedGlobals.end(); i != e; ++i) {
4044 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4045 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004046
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004047 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4048 llvm::GlobalValue *GV =
4049 new llvm::GlobalVariable(AT, false,
4050 llvm::GlobalValue::AppendingLinkage,
4051 llvm::ConstantArray::get(AT, Used),
4052 "llvm.used",
4053 &CGM.getModule());
4054
4055 GV->setSection("llvm.metadata");
4056
4057}
4058
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004059// Metadata flags
4060enum MetaDataDlags {
4061 CLS = 0x0,
4062 CLS_META = 0x1,
4063 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004064 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004065 CLS_EXCEPTION = 0x20
4066};
4067/// BuildClassRoTInitializer - generate meta-data for:
4068/// struct _class_ro_t {
4069/// uint32_t const flags;
4070/// uint32_t const instanceStart;
4071/// uint32_t const instanceSize;
4072/// uint32_t const reserved; // only when building for 64bit targets
4073/// const uint8_t * const ivarLayout;
4074/// const char *const name;
4075/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004076/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004077/// const struct _ivar_list_t *const ivars;
4078/// const uint8_t * const weakIvarLayout;
4079/// const struct _prop_list_t * const properties;
4080/// }
4081///
4082llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4083 unsigned flags,
4084 unsigned InstanceStart,
4085 unsigned InstanceSize,
4086 const ObjCImplementationDecl *ID) {
4087 std::string ClassName = ID->getNameAsString();
4088 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4089 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4090 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4091 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4092 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004093 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004094 // Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4095 // : BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004096 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004097 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004098 // const struct _method_list_t * const baseMethods;
4099 std::vector<llvm::Constant*> Methods;
4100 std::string MethodListName("\01l_OBJC_$_");
4101 if (flags & CLS_META) {
4102 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4103 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4104 e = ID->classmeth_end(); i != e; ++i) {
4105 // Class methods should always be defined.
4106 Methods.push_back(GetMethodConstant(*i));
4107 }
4108 } else {
4109 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4110 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4111 e = ID->instmeth_end(); i != e; ++i) {
4112 // Instance methods should always be defined.
4113 Methods.push_back(GetMethodConstant(*i));
4114 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004115 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4116 e = ID->propimpl_end(); i != e; ++i) {
4117 ObjCPropertyImplDecl *PID = *i;
4118
4119 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4120 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4121
4122 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4123 if (llvm::Constant *C = GetMethodConstant(MD))
4124 Methods.push_back(C);
4125 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4126 if (llvm::Constant *C = GetMethodConstant(MD))
4127 Methods.push_back(C);
4128 }
4129 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004130 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004131 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004132 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004133
4134 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4135 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4136 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4137 + OID->getNameAsString(),
4138 OID->protocol_begin(),
4139 OID->protocol_end());
4140
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004141 if (flags & CLS_META)
4142 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4143 else
4144 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004145 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004146 // Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4147 // : BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004148 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004149 if (flags & CLS_META)
4150 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4151 else
4152 Values[ 9] =
4153 EmitPropertyList(
4154 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4155 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004156 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4157 Values);
4158 llvm::GlobalVariable *CLASS_RO_GV =
4159 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4160 llvm::GlobalValue::InternalLinkage,
4161 Init,
4162 (flags & CLS_META) ?
4163 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4164 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4165 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004166 CLASS_RO_GV->setAlignment(
4167 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004168 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004169 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004170
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004171}
4172
4173/// BuildClassMetaData - This routine defines that to-level meta-data
4174/// for the given ClassName for:
4175/// struct _class_t {
4176/// struct _class_t *isa;
4177/// struct _class_t * const superclass;
4178/// void *cache;
4179/// IMP *vtable;
4180/// struct class_ro_t *ro;
4181/// }
4182///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004183llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4184 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004185 llvm::Constant *IsAGV,
4186 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004187 llvm::Constant *ClassRoGV,
4188 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004189 std::vector<llvm::Constant*> Values(5);
4190 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004191 Values[1] = SuperClassGV
4192 ? SuperClassGV
4193 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004194 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4195 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4196 Values[4] = ClassRoGV; // &CLASS_RO_GV
4197 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4198 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004199 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4200 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004201 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004202 GV->setAlignment(
4203 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004204 if (HiddenVisibility)
4205 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004206 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004207}
4208
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004209/// countInheritedIvars - count number of ivars in class and its super class(s)
4210///
4211static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4212 ASTContext &Context) {
4213 int count = 0;
4214 if (!OI)
4215 return 0;
4216 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4217 if (SuperClass)
4218 count += countInheritedIvars(SuperClass, Context);
4219 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4220 E = OI->ivar_end(); I != E; ++I)
4221 ++count;
4222 // look into properties.
4223 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4224 E = OI->prop_end(Context); I != E; ++I) {
4225 if ((*I)->getPropertyIvarDecl())
4226 ++count;
4227 }
4228 return count;
4229}
4230
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004231void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4232 uint32_t &InstanceStart,
4233 uint32_t &InstanceSize) {
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004234 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4235
Daniel Dunbar6ec07162009-04-20 07:18:49 +00004236 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4237 CGM.getContext());
4238 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4239 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4240 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4241 while (countSuperClassIvars-- > 0) {
4242 lastField = firstField;
4243 ++firstField;
4244 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004245
4246 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4247 ifield = firstField; ifield != e; ++ifield)
4248 lastField = ifield;
4249
4250 InstanceStart = InstanceSize = 0;
4251 if (lastField != RD->field_end(CGM.getContext())) {
4252 FieldDecl *Field = *lastField;
4253 const llvm::Type *FieldTy =
4254 CGM.getTypes().ConvertTypeForMem(Field->getType());
4255 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4256 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4257 if (firstField == RD->field_end(CGM.getContext()))
4258 InstanceStart = InstanceSize;
4259 else {
4260 Field = *firstField;
4261 InstanceStart = GetIvarBaseOffset(Layout, Field);
4262 }
4263 }
4264}
4265
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004266void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4267 std::string ClassName = ID->getNameAsString();
4268 if (!ObjCEmptyCacheVar) {
4269 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004270 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004271 false,
4272 llvm::GlobalValue::ExternalLinkage,
4273 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004274 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004275 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004276
4277 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004278 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004279 false,
4280 llvm::GlobalValue::ExternalLinkage,
4281 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004282 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004283 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004284 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004285 assert(ID->getClassInterface() &&
4286 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004287 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004288 uint32_t InstanceStart =
4289 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4290 uint32_t InstanceSize = InstanceStart;
4291 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004292 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4293 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004294
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004295 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004296
Daniel Dunbar04d40782009-04-14 06:00:08 +00004297 bool classIsHidden =
4298 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004299 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004300 flags |= OBJC2_CLS_HIDDEN;
4301 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004302 // class is root
4303 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004304 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004305 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004306 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004307 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004308 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4309 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4310 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004311 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004312 // work on super class metadata symbol.
4313 std::string SuperClassName =
4314 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004315 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004316 }
4317 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4318 InstanceStart,
4319 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004320 std::string TClassName = ObjCMetaClassName + ClassName;
4321 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004322 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4323 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004324
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004325 // Metadata for the class
4326 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004327 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004328 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004329
4330 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4331 flags |= CLS_EXCEPTION;
4332
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004333 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004334 flags |= CLS_ROOT;
4335 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004336 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004337 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004338 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004339 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004340 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004341 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004342 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004343 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004344 InstanceStart,
4345 InstanceSize,
4346 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004347
4348 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004349 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004350 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4351 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004352 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004353
4354 // Force the definition of the EHType if necessary.
4355 if (flags & CLS_EXCEPTION)
4356 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004357}
4358
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004359/// GenerateProtocolRef - This routine is called to generate code for
4360/// a protocol reference expression; as in:
4361/// @code
4362/// @protocol(Proto1);
4363/// @endcode
4364/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4365/// which will hold address of the protocol meta-data.
4366///
4367llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4368 const ObjCProtocolDecl *PD) {
4369
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004370 // This routine is called for @protocol only. So, we must build definition
4371 // of protocol's meta-data (not a reference to it!)
4372 //
4373 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004374 ObjCTypes.ExternalProtocolPtrTy);
4375
4376 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4377 ProtocolName += PD->getNameAsCString();
4378
4379 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4380 if (PTGV)
4381 return Builder.CreateLoad(PTGV, false, "tmp");
4382 PTGV = new llvm::GlobalVariable(
4383 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004384 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004385 Init,
4386 ProtocolName,
4387 &CGM.getModule());
4388 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4389 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4390 UsedGlobals.push_back(PTGV);
4391 return Builder.CreateLoad(PTGV, false, "tmp");
4392}
4393
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004394/// GenerateCategory - Build metadata for a category implementation.
4395/// struct _category_t {
4396/// const char * const name;
4397/// struct _class_t *const cls;
4398/// const struct _method_list_t * const instance_methods;
4399/// const struct _method_list_t * const class_methods;
4400/// const struct _protocol_list_t * const protocols;
4401/// const struct _prop_list_t * const properties;
4402/// }
4403///
4404void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4405{
4406 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004407 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4408 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004409 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004410 std::string ExtClassName(getClassSymbolPrefix() +
4411 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004412
4413 std::vector<llvm::Constant*> Values(6);
4414 Values[0] = GetClassName(OCD->getIdentifier());
4415 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004416 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004417 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004418 std::vector<llvm::Constant*> Methods;
4419 std::string MethodListName(Prefix);
4420 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4421 "_$_" + OCD->getNameAsString();
4422
4423 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4424 e = OCD->instmeth_end(); i != e; ++i) {
4425 // Instance methods should always be defined.
4426 Methods.push_back(GetMethodConstant(*i));
4427 }
4428
4429 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004430 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004431 Methods);
4432
4433 MethodListName = Prefix;
4434 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4435 OCD->getNameAsString();
4436 Methods.clear();
4437 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4438 e = OCD->classmeth_end(); i != e; ++i) {
4439 // Class methods should always be defined.
4440 Methods.push_back(GetMethodConstant(*i));
4441 }
4442
4443 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004444 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004445 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004446 const ObjCCategoryDecl *Category =
4447 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004448 if (Category) {
4449 std::string ExtName(Interface->getNameAsString() + "_$_" +
4450 OCD->getNameAsString());
4451 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4452 + Interface->getNameAsString() + "_$_"
4453 + Category->getNameAsString(),
4454 Category->protocol_begin(),
4455 Category->protocol_end());
4456 Values[5] =
4457 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4458 OCD, Category, ObjCTypes);
4459 }
4460 else {
4461 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4462 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4463 }
4464
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004465 llvm::Constant *Init =
4466 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4467 Values);
4468 llvm::GlobalVariable *GCATV
4469 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4470 false,
4471 llvm::GlobalValue::InternalLinkage,
4472 Init,
4473 ExtCatName,
4474 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004475 GCATV->setAlignment(
4476 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004477 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004478 UsedGlobals.push_back(GCATV);
4479 DefinedCategories.push_back(GCATV);
4480}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004481
4482/// GetMethodConstant - Return a struct objc_method constant for the
4483/// given method if it has been defined. The result is null if the
4484/// method has not been defined. The return value has type MethodPtrTy.
4485llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4486 const ObjCMethodDecl *MD) {
4487 // FIXME: Use DenseMap::lookup
4488 llvm::Function *Fn = MethodDefinitions[MD];
4489 if (!Fn)
4490 return 0;
4491
4492 std::vector<llvm::Constant*> Method(3);
4493 Method[0] =
4494 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4495 ObjCTypes.SelectorPtrTy);
4496 Method[1] = GetMethodVarType(MD);
4497 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4498 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4499}
4500
4501/// EmitMethodList - Build meta-data for method declarations
4502/// struct _method_list_t {
4503/// uint32_t entsize; // sizeof(struct _objc_method)
4504/// uint32_t method_count;
4505/// struct _objc_method method_list[method_count];
4506/// }
4507///
4508llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4509 const std::string &Name,
4510 const char *Section,
4511 const ConstantVector &Methods) {
4512 // Return null for empty list.
4513 if (Methods.empty())
4514 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4515
4516 std::vector<llvm::Constant*> Values(3);
4517 // sizeof(struct _objc_method)
4518 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4519 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4520 // method_count
4521 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4522 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4523 Methods.size());
4524 Values[2] = llvm::ConstantArray::get(AT, Methods);
4525 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4526
4527 llvm::GlobalVariable *GV =
4528 new llvm::GlobalVariable(Init->getType(), false,
4529 llvm::GlobalValue::InternalLinkage,
4530 Init,
4531 Name,
4532 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004533 GV->setAlignment(
4534 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004535 GV->setSection(Section);
4536 UsedGlobals.push_back(GV);
4537 return llvm::ConstantExpr::getBitCast(GV,
4538 ObjCTypes.MethodListnfABIPtrTy);
4539}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004540
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004541/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4542/// the given ivar.
4543///
4544llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004545 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004546 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004547 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004548 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4549 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004550 llvm::GlobalVariable *IvarOffsetGV =
4551 CGM.getModule().getGlobalVariable(Name);
4552 if (!IvarOffsetGV)
4553 IvarOffsetGV =
4554 new llvm::GlobalVariable(ObjCTypes.LongTy,
4555 false,
4556 llvm::GlobalValue::ExternalLinkage,
4557 0,
4558 Name,
4559 &CGM.getModule());
4560 return IvarOffsetGV;
4561}
4562
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004563llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004564 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004565 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004566 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004567 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4568 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4569 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004570 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004571 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004572
4573 // FIXME: This matches gcc, but shouldn't the visibility be set on
4574 // the use as well (i.e., in ObjCIvarOffsetVariable).
4575 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4576 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4577 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004578 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004579 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004580 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004581 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004582 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004583}
4584
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004585/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004586/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004587/// IvarListnfABIPtrTy.
4588/// struct _ivar_t {
4589/// unsigned long int *offset; // pointer to ivar offset location
4590/// char *name;
4591/// char *type;
4592/// uint32_t alignment;
4593/// uint32_t size;
4594/// }
4595/// struct _ivar_list_t {
4596/// uint32 entsize; // sizeof(struct _ivar_t)
4597/// uint32 count;
4598/// struct _iver_t list[count];
4599/// }
4600///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004601
4602void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4603 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4604 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4605 E = OID->ivar_end(); I != E; ++I) {
4606 // Ignore unnamed bit-fields.
4607 if (!(*I)->getDeclName())
4608 continue;
4609
4610 Res.push_back(*I);
4611 }
4612
4613 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4614 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4615 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4616 Res.push_back(IV);
4617}
4618
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004619llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4620 const ObjCImplementationDecl *ID) {
4621
4622 std::vector<llvm::Constant*> Ivars, Ivar(5);
4623
4624 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4625 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4626
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004627 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004628 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004629
Daniel Dunbar91636d62009-04-20 00:33:43 +00004630 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004631 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004632 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004633
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004634 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4635 ObjCIvarDecl *IVD = OIvars[i];
4636 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004637 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004638 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004639 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004640 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004641 const llvm::Type *FieldTy =
4642 CGM.getTypes().ConvertTypeForMem(Field->getType());
4643 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4644 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4645 Field->getType().getTypePtr()) >> 3;
4646 Align = llvm::Log2_32(Align);
4647 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004648 // NOTE. Size of a bitfield does not match gcc's, because of the
4649 // way bitfields are treated special in each. But I am told that
4650 // 'size' for bitfield ivars is ignored by the runtime so it does
4651 // not matter. If it matters, there is enough info to get the
4652 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004653 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4654 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4655 }
4656 // Return null for empty list.
4657 if (Ivars.empty())
4658 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4659 std::vector<llvm::Constant*> Values(3);
4660 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4661 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4662 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4663 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4664 Ivars.size());
4665 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4666 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4667 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4668 llvm::GlobalVariable *GV =
4669 new llvm::GlobalVariable(Init->getType(), false,
4670 llvm::GlobalValue::InternalLinkage,
4671 Init,
4672 Prefix + OID->getNameAsString(),
4673 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004674 GV->setAlignment(
4675 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004676 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004677
4678 UsedGlobals.push_back(GV);
4679 return llvm::ConstantExpr::getBitCast(GV,
4680 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004681}
4682
4683llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4684 const ObjCProtocolDecl *PD) {
4685 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4686
4687 if (!Entry) {
4688 // We use the initializer as a marker of whether this is a forward
4689 // reference or not. At module finalization we add the empty
4690 // contents for protocols which were referenced but never defined.
4691 Entry =
4692 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4693 llvm::GlobalValue::ExternalLinkage,
4694 0,
4695 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4696 &CGM.getModule());
4697 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4698 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004699 }
4700
4701 return Entry;
4702}
4703
4704/// GetOrEmitProtocol - Generate the protocol meta-data:
4705/// @code
4706/// struct _protocol_t {
4707/// id isa; // NULL
4708/// const char * const protocol_name;
4709/// const struct _protocol_list_t * protocol_list; // super protocols
4710/// const struct method_list_t * const instance_methods;
4711/// const struct method_list_t * const class_methods;
4712/// const struct method_list_t *optionalInstanceMethods;
4713/// const struct method_list_t *optionalClassMethods;
4714/// const struct _prop_list_t * properties;
4715/// const uint32_t size; // sizeof(struct _protocol_t)
4716/// const uint32_t flags; // = 0
4717/// }
4718/// @endcode
4719///
4720
4721llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4722 const ObjCProtocolDecl *PD) {
4723 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4724
4725 // Early exit if a defining object has already been generated.
4726 if (Entry && Entry->hasInitializer())
4727 return Entry;
4728
4729 const char *ProtocolName = PD->getNameAsCString();
4730
4731 // Construct method lists.
4732 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4733 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004734 for (ObjCProtocolDecl::instmeth_iterator
4735 i = PD->instmeth_begin(CGM.getContext()),
4736 e = PD->instmeth_end(CGM.getContext());
4737 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004738 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004739 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004740 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4741 OptInstanceMethods.push_back(C);
4742 } else {
4743 InstanceMethods.push_back(C);
4744 }
4745 }
4746
Douglas Gregor6ab35242009-04-09 21:40:53 +00004747 for (ObjCProtocolDecl::classmeth_iterator
4748 i = PD->classmeth_begin(CGM.getContext()),
4749 e = PD->classmeth_end(CGM.getContext());
4750 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004751 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004752 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4754 OptClassMethods.push_back(C);
4755 } else {
4756 ClassMethods.push_back(C);
4757 }
4758 }
4759
4760 std::vector<llvm::Constant*> Values(10);
4761 // isa is NULL
4762 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4763 Values[1] = GetClassName(PD->getIdentifier());
4764 Values[2] = EmitProtocolList(
4765 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4766 PD->protocol_begin(),
4767 PD->protocol_end());
4768
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004769 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004770 + PD->getNameAsString(),
4771 "__DATA, __objc_const",
4772 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004773 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004774 + PD->getNameAsString(),
4775 "__DATA, __objc_const",
4776 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004777 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004778 + PD->getNameAsString(),
4779 "__DATA, __objc_const",
4780 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004781 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004782 + PD->getNameAsString(),
4783 "__DATA, __objc_const",
4784 OptClassMethods);
4785 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4786 0, PD, ObjCTypes);
4787 uint32_t Size =
4788 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4789 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4790 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4791 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4792 Values);
4793
4794 if (Entry) {
4795 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004796 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 Entry->setInitializer(Init);
4798 } else {
4799 Entry =
4800 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004801 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004802 Init,
4803 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4804 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004805 Entry->setAlignment(
4806 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004807 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004808 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004809 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4810
4811 // Use this protocol meta-data to build protocol list table in section
4812 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004813 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004814 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004815 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004816 Entry,
4817 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4818 +ProtocolName,
4819 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004820 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004821 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004822 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004823 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4824 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004825 return Entry;
4826}
4827
4828/// EmitProtocolList - Generate protocol list meta-data:
4829/// @code
4830/// struct _protocol_list_t {
4831/// long protocol_count; // Note, this is 32/64 bit
4832/// struct _protocol_t[protocol_count];
4833/// }
4834/// @endcode
4835///
4836llvm::Constant *
4837CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4838 ObjCProtocolDecl::protocol_iterator begin,
4839 ObjCProtocolDecl::protocol_iterator end) {
4840 std::vector<llvm::Constant*> ProtocolRefs;
4841
Fariborz Jahanianda320092009-01-29 19:24:30 +00004842 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004843 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004844 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4845
Daniel Dunbar948e2582009-02-15 07:36:20 +00004846 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004847 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4848 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004849 return llvm::ConstantExpr::getBitCast(GV,
4850 ObjCTypes.ProtocolListnfABIPtrTy);
4851
4852 for (; begin != end; ++begin)
4853 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4854
Fariborz Jahanianda320092009-01-29 19:24:30 +00004855 // This list is null terminated.
4856 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004857 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004858
4859 std::vector<llvm::Constant*> Values(2);
4860 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4861 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004862 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004863 ProtocolRefs.size()),
4864 ProtocolRefs);
4865
4866 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4867 GV = new llvm::GlobalVariable(Init->getType(), false,
4868 llvm::GlobalValue::InternalLinkage,
4869 Init,
4870 Name,
4871 &CGM.getModule());
4872 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004873 GV->setAlignment(
4874 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004875 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004876 return llvm::ConstantExpr::getBitCast(GV,
4877 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004878}
4879
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004880/// GetMethodDescriptionConstant - This routine build following meta-data:
4881/// struct _objc_method {
4882/// SEL _cmd;
4883/// char *method_type;
4884/// char *_imp;
4885/// }
4886
4887llvm::Constant *
4888CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4889 std::vector<llvm::Constant*> Desc(3);
4890 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4891 ObjCTypes.SelectorPtrTy);
4892 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004893 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004894 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4895 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4896}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004897
4898/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4899/// This code gen. amounts to generating code for:
4900/// @code
4901/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4902/// @encode
4903///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004904LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004905 CodeGen::CodeGenFunction &CGF,
4906 QualType ObjectTy,
4907 llvm::Value *BaseValue,
4908 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004909 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004910 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4911 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004912 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004913
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004914 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004915 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004916 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4917 // (char*)BaseValue + Offset_symbol
4918 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4919 // (type *)((char*)BaseValue + Offset_symbol)
4920 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004921 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004922 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4923 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004924
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004925 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004926 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004927 CodeGenTypes::BitFieldInfo bitFieldInfo =
4928 CGM.getTypes().getBitFieldInfo(Field);
4929 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004930 FieldTy->isSignedIntegerType(),
4931 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004932 }
4933
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004934 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004935 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4936 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004937 LValue::SetObjCIvar(LV, true);
4938 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004939}
4940
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004941llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4942 CodeGen::CodeGenFunction &CGF,
4943 ObjCInterfaceDecl *Interface,
4944 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004945 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4946 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004947}
4948
Fariborz Jahanian46551122009-02-04 00:22:57 +00004949CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4950 CodeGen::CodeGenFunction &CGF,
4951 QualType ResultType,
4952 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004953 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004954 QualType Arg0Ty,
4955 bool IsSuper,
4956 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004957 // FIXME. Even though IsSuper is passes. This function doese not
4958 // handle calls to 'super' receivers.
4959 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004960 llvm::Value *Arg0 = Receiver;
4961 if (!IsSuper)
4962 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004963
4964 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004965 // FIXME. This is too much work to get the ABI-specific result type
4966 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004967 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4968 llvm::SmallVector<QualType, 16>());
4969 llvm::Constant *Fn;
4970 std::string Name("\01l_");
4971 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004972#if 0
4973 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004974 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4975 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4976 // FIXME. Is there a better way of getting these names.
4977 // They are available in RuntimeFunctions vector pair.
4978 Name += "objc_msgSendId_stret_fixup";
4979 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004980 else
4981#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004982 if (IsSuper) {
4983 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4984 Name += "objc_msgSendSuper2_stret_fixup";
4985 }
4986 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004987 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004988 Fn = ObjCTypes.MessageSendStretFixupFn;
4989 Name += "objc_msgSend_stret_fixup";
4990 }
4991 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004992 else if (ResultType->isFloatingType() &&
4993 // Selection of frret API only happens in 32bit nonfragile ABI.
4994 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004995 Fn = ObjCTypes.MessageSendFpretFixupFn;
4996 Name += "objc_msgSend_fpret_fixup";
4997 }
4998 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004999#if 0
5000// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005001 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
5002 Fn = ObjCTypes.MessageSendIdFixupFn;
5003 Name += "objc_msgSendId_fixup";
5004 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005005 else
5006#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005007 if (IsSuper) {
5008 Fn = ObjCTypes.MessageSendSuper2FixupFn;
5009 Name += "objc_msgSendSuper2_fixup";
5010 }
5011 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005012 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005013 Fn = ObjCTypes.MessageSendFixupFn;
5014 Name += "objc_msgSend_fixup";
5015 }
5016 }
5017 Name += '_';
5018 std::string SelName(Sel.getAsString());
5019 // Replace all ':' in selector name with '_' ouch!
5020 for(unsigned i = 0; i < SelName.size(); i++)
5021 if (SelName[i] == ':')
5022 SelName[i] = '_';
5023 Name += SelName;
5024 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5025 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005026 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005027 std::vector<llvm::Constant*> Values(2);
5028 Values[0] = Fn;
5029 Values[1] = GetMethodVarName(Sel);
5030 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5031 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005032 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005033 Init,
5034 Name,
5035 &CGM.getModule());
5036 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005037 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005038 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005039 }
5040 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005041
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005042 CallArgList ActualArgs;
5043 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5044 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5045 ObjCTypes.MessageRefCPtrTy));
5046 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005047 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5048 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5049 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005050 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005051 Callee = CGF.Builder.CreateBitCast(Callee,
5052 llvm::PointerType::getUnqual(FTy));
5053 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005054}
5055
5056/// Generate code for a message send expression in the nonfragile abi.
5057CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5058 CodeGen::CodeGenFunction &CGF,
5059 QualType ResultType,
5060 Selector Sel,
5061 llvm::Value *Receiver,
5062 bool IsClassMessage,
5063 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005064 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005065 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005066 false, CallArgs);
5067}
5068
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005069llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005070CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005071 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5072
Daniel Dunbardfff2302009-03-02 05:18:14 +00005073 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005074 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5075 llvm::GlobalValue::ExternalLinkage,
5076 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005077 }
5078
5079 return GV;
5080}
5081
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005082llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005083 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005084 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5085
5086 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005087 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005088 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005089 Entry =
5090 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5091 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005092 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005093 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005094 &CGM.getModule());
5095 Entry->setAlignment(
5096 CGM.getTargetData().getPrefTypeAlignment(
5097 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005098 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5099 UsedGlobals.push_back(Entry);
5100 }
5101
5102 return Builder.CreateLoad(Entry, false, "tmp");
5103}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005104
Daniel Dunbar11394522009-04-18 08:51:00 +00005105llvm::Value *
5106CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5107 const ObjCInterfaceDecl *ID) {
5108 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5109
5110 if (!Entry) {
5111 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5112 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5113 Entry =
5114 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5115 llvm::GlobalValue::InternalLinkage,
5116 ClassGV,
5117 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5118 &CGM.getModule());
5119 Entry->setAlignment(
5120 CGM.getTargetData().getPrefTypeAlignment(
5121 ObjCTypes.ClassnfABIPtrTy));
5122 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005123 UsedGlobals.push_back(Entry);
5124 }
5125
5126 return Builder.CreateLoad(Entry, false, "tmp");
5127}
5128
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005129/// EmitMetaClassRef - Return a Value * of the address of _class_t
5130/// meta-data
5131///
5132llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5133 const ObjCInterfaceDecl *ID) {
5134 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5135 if (Entry)
5136 return Builder.CreateLoad(Entry, false, "tmp");
5137
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005138 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005139 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005140 Entry =
5141 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5142 llvm::GlobalValue::InternalLinkage,
5143 MetaClassGV,
5144 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5145 &CGM.getModule());
5146 Entry->setAlignment(
5147 CGM.getTargetData().getPrefTypeAlignment(
5148 ObjCTypes.ClassnfABIPtrTy));
5149
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005150 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005151 UsedGlobals.push_back(Entry);
5152
5153 return Builder.CreateLoad(Entry, false, "tmp");
5154}
5155
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005156/// GetClass - Return a reference to the class for the given interface
5157/// decl.
5158llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5159 const ObjCInterfaceDecl *ID) {
5160 return EmitClassRef(Builder, ID);
5161}
5162
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005163/// Generates a message send where the super is the receiver. This is
5164/// a message send to self with special delivery semantics indicating
5165/// which class's method should be called.
5166CodeGen::RValue
5167CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5168 QualType ResultType,
5169 Selector Sel,
5170 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005171 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005172 llvm::Value *Receiver,
5173 bool IsClassMessage,
5174 const CodeGen::CallArgList &CallArgs) {
5175 // ...
5176 // Create and init a super structure; this is a (receiver, class)
5177 // pair we will pass to objc_msgSendSuper.
5178 llvm::Value *ObjCSuper =
5179 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5180
5181 llvm::Value *ReceiverAsObject =
5182 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5183 CGF.Builder.CreateStore(ReceiverAsObject,
5184 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5185
5186 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005187 llvm::Value *Target;
5188 if (IsClassMessage) {
5189 if (isCategoryImpl) {
5190 // Message sent to "super' in a class method defined in
5191 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005192 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005193 Target = CGF.Builder.CreateStructGEP(Target, 0);
5194 Target = CGF.Builder.CreateLoad(Target);
5195 }
5196 else
5197 Target = EmitMetaClassRef(CGF.Builder, Class);
5198 }
5199 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005200 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005201
5202 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5203 // and ObjCTypes types.
5204 const llvm::Type *ClassTy =
5205 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5206 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5207 CGF.Builder.CreateStore(Target,
5208 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5209
5210 return EmitMessageSend(CGF, ResultType, Sel,
5211 ObjCSuper, ObjCTypes.SuperPtrCTy,
5212 true, CallArgs);
5213}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005214
5215llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5216 Selector Sel) {
5217 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5218
5219 if (!Entry) {
5220 llvm::Constant *Casted =
5221 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5222 ObjCTypes.SelectorPtrTy);
5223 Entry =
5224 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5225 llvm::GlobalValue::InternalLinkage,
5226 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5227 &CGM.getModule());
5228 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5229 UsedGlobals.push_back(Entry);
5230 }
5231
5232 return Builder.CreateLoad(Entry, false, "tmp");
5233}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005234/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5235/// objc_assign_ivar (id src, id *dst)
5236///
5237void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5238 llvm::Value *src, llvm::Value *dst)
5239{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005240 const llvm::Type * SrcTy = src->getType();
5241 if (!isa<llvm::PointerType>(SrcTy)) {
5242 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5243 assert(Size <= 8 && "does not support size > 8");
5244 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5245 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005246 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5247 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005248 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5249 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5250 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5251 src, dst, "assignivar");
5252 return;
5253}
5254
5255/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5256/// objc_assign_strongCast (id src, id *dst)
5257///
5258void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5259 CodeGen::CodeGenFunction &CGF,
5260 llvm::Value *src, llvm::Value *dst)
5261{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005262 const llvm::Type * SrcTy = src->getType();
5263 if (!isa<llvm::PointerType>(SrcTy)) {
5264 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5265 assert(Size <= 8 && "does not support size > 8");
5266 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5267 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005268 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5269 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005270 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5271 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5272 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5273 src, dst, "weakassign");
5274 return;
5275}
5276
5277/// EmitObjCWeakRead - Code gen for loading value of a __weak
5278/// object: objc_read_weak (id *src)
5279///
5280llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5281 CodeGen::CodeGenFunction &CGF,
5282 llvm::Value *AddrWeakObj)
5283{
Eli Friedman8339b352009-03-07 03:57:15 +00005284 const llvm::Type* DestTy =
5285 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005286 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5287 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5288 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005289 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005290 return read_weak;
5291}
5292
5293/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5294/// objc_assign_weak (id src, id *dst)
5295///
5296void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5297 llvm::Value *src, llvm::Value *dst)
5298{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005299 const llvm::Type * SrcTy = src->getType();
5300 if (!isa<llvm::PointerType>(SrcTy)) {
5301 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5302 assert(Size <= 8 && "does not support size > 8");
5303 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5304 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005305 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5306 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005307 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5308 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005309 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005310 src, dst, "weakassign");
5311 return;
5312}
5313
5314/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5315/// objc_assign_global (id src, id *dst)
5316///
5317void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5318 llvm::Value *src, llvm::Value *dst)
5319{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005320 const llvm::Type * SrcTy = src->getType();
5321 if (!isa<llvm::PointerType>(SrcTy)) {
5322 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5323 assert(Size <= 8 && "does not support size > 8");
5324 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5325 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005326 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5327 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005328 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5329 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5330 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5331 src, dst, "globalassign");
5332 return;
5333}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005334
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005335void
5336CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5337 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005338 bool isTry = isa<ObjCAtTryStmt>(S);
5339 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5340 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005341 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005342 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005343 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005344 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5345
5346 // For @synchronized, call objc_sync_enter(sync.expr). The
5347 // evaluation of the expression must occur before we enter the
5348 // @synchronized. We can safely avoid a temp here because jumps into
5349 // @synchronized are illegal & this will dominate uses.
5350 llvm::Value *SyncArg = 0;
5351 if (!isTry) {
5352 SyncArg =
5353 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5354 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005355 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005356 }
5357
5358 // Push an EH context entry, used for handling rethrows and jumps
5359 // through finally.
5360 CGF.PushCleanupBlock(FinallyBlock);
5361
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005362 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005363
5364 CGF.EmitBlock(TryBlock);
5365 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5366 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5367 CGF.EmitBranchThroughCleanup(FinallyEnd);
5368
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005369 // Emit the exception handler.
5370
5371 CGF.EmitBlock(TryHandler);
5372
5373 llvm::Value *llvm_eh_exception =
5374 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5375 llvm::Value *llvm_eh_selector_i64 =
5376 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5377 llvm::Value *llvm_eh_typeid_for_i64 =
5378 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5379 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5380 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5381
5382 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5383 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005384 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005385
5386 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005387 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005388 bool HasCatchAll = false;
5389 if (isTry) {
5390 if (const ObjCAtCatchStmt* CatchStmt =
5391 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5392 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005393 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005394 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005395
5396 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005397 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005398 // Use i8* null here to signal this is a catch all, not a cleanup.
5399 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5400 SelectorArgs.push_back(Null);
5401 HasCatchAll = true;
5402 break;
5403 }
5404
Daniel Dunbarede8de92009-03-06 00:01:21 +00005405 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5406 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005407 llvm::Value *IDEHType =
5408 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5409 if (!IDEHType)
5410 IDEHType =
5411 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5412 llvm::GlobalValue::ExternalLinkage,
5413 0, "OBJC_EHTYPE_id", &CGM.getModule());
5414 SelectorArgs.push_back(IDEHType);
5415 HasCatchAll = true;
5416 break;
5417 }
5418
5419 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005420 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005421 assert(PT && "Invalid @catch type.");
5422 const ObjCInterfaceType *IT =
5423 PT->getPointeeType()->getAsObjCInterfaceType();
5424 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005425 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005426 SelectorArgs.push_back(EHType);
5427 }
5428 }
5429 }
5430
5431 // We use a cleanup unless there was already a catch all.
5432 if (!HasCatchAll) {
5433 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005434 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005435 }
5436
5437 llvm::Value *Selector =
5438 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5439 SelectorArgs.begin(), SelectorArgs.end(),
5440 "selector");
5441 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005442 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005443 const Stmt *CatchBody = Handlers[i].second;
5444
5445 llvm::BasicBlock *Next = 0;
5446
5447 // The last handler always matches.
5448 if (i + 1 != e) {
5449 assert(CatchParam && "Only last handler can be a catch all.");
5450
5451 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5452 Next = CGF.createBasicBlock("catch.next");
5453 llvm::Value *Id =
5454 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5455 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5456 ObjCTypes.Int8PtrTy));
5457 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5458 Match, Next);
5459
5460 CGF.EmitBlock(Match);
5461 }
5462
5463 if (CatchBody) {
5464 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5465 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5466
5467 // Cleanups must call objc_end_catch.
5468 //
5469 // FIXME: It seems incorrect for objc_begin_catch to be inside
5470 // this context, but this matches gcc.
5471 CGF.PushCleanupBlock(MatchEnd);
5472 CGF.setInvokeDest(MatchHandler);
5473
5474 llvm::Value *ExcObject =
5475 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5476
5477 // Bind the catch parameter if it exists.
5478 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005479 ExcObject =
5480 CGF.Builder.CreateBitCast(ExcObject,
5481 CGF.ConvertType(CatchParam->getType()));
5482 // CatchParam is a ParmVarDecl because of the grammar
5483 // construction used to handle this, but for codegen purposes
5484 // we treat this as a local decl.
5485 CGF.EmitLocalBlockVarDecl(*CatchParam);
5486 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005487 }
5488
5489 CGF.ObjCEHValueStack.push_back(ExcObject);
5490 CGF.EmitStmt(CatchBody);
5491 CGF.ObjCEHValueStack.pop_back();
5492
5493 CGF.EmitBranchThroughCleanup(FinallyEnd);
5494
5495 CGF.EmitBlock(MatchHandler);
5496
5497 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5498 // We are required to emit this call to satisfy LLVM, even
5499 // though we don't use the result.
5500 llvm::SmallVector<llvm::Value*, 8> Args;
5501 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005502 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005503 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5504 0));
5505 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5506 CGF.Builder.CreateStore(Exc, RethrowPtr);
5507 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5508
5509 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5510
5511 CGF.EmitBlock(MatchEnd);
5512
5513 // Unfortunately, we also have to generate another EH frame here
5514 // in case this throws.
5515 llvm::BasicBlock *MatchEndHandler =
5516 CGF.createBasicBlock("match.end.handler");
5517 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5518 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5519 Cont, MatchEndHandler,
5520 Args.begin(), Args.begin());
5521
5522 CGF.EmitBlock(Cont);
5523 if (Info.SwitchBlock)
5524 CGF.EmitBlock(Info.SwitchBlock);
5525 if (Info.EndBlock)
5526 CGF.EmitBlock(Info.EndBlock);
5527
5528 CGF.EmitBlock(MatchEndHandler);
5529 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5530 // We are required to emit this call to satisfy LLVM, even
5531 // though we don't use the result.
5532 Args.clear();
5533 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005534 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005535 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5536 0));
5537 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5538 CGF.Builder.CreateStore(Exc, RethrowPtr);
5539 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5540
5541 if (Next)
5542 CGF.EmitBlock(Next);
5543 } else {
5544 assert(!Next && "catchup should be last handler.");
5545
5546 CGF.Builder.CreateStore(Exc, RethrowPtr);
5547 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5548 }
5549 }
5550
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005551 // Pop the cleanup entry, the @finally is outside this cleanup
5552 // scope.
5553 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5554 CGF.setInvokeDest(PrevLandingPad);
5555
5556 CGF.EmitBlock(FinallyBlock);
5557
5558 if (isTry) {
5559 if (const ObjCAtFinallyStmt* FinallyStmt =
5560 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5561 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5562 } else {
5563 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5564 // @synchronized.
5565 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005566 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005567
5568 if (Info.SwitchBlock)
5569 CGF.EmitBlock(Info.SwitchBlock);
5570 if (Info.EndBlock)
5571 CGF.EmitBlock(Info.EndBlock);
5572
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005573 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005574 CGF.EmitBranch(FinallyEnd);
5575
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005576 CGF.EmitBlock(FinallyRethrow);
5577 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5578 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005579 CGF.Builder.CreateUnreachable();
5580
5581 CGF.EmitBlock(FinallyEnd);
5582}
5583
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005584/// EmitThrowStmt - Generate code for a throw statement.
5585void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5586 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005587 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005588 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005589 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005590 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005591 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5592 "Unexpected rethrow outside @catch block.");
5593 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005594 }
5595
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005596 llvm::Value *ExceptionAsObject =
5597 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5598 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5599 if (InvokeDest) {
5600 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5601 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5602 Cont, InvokeDest,
5603 &ExceptionAsObject, &ExceptionAsObject + 1);
5604 CGF.EmitBlock(Cont);
5605 } else
5606 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5607 CGF.Builder.CreateUnreachable();
5608
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005609 // Clear the insertion point to indicate we are in unreachable code.
5610 CGF.Builder.ClearInsertionPoint();
5611}
Daniel Dunbare588b992009-03-01 04:46:24 +00005612
5613llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005614CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5615 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005616 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005617
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005618 // If we don't need a definition, return the entry if found or check
5619 // if we use an external reference.
5620 if (!ForDefinition) {
5621 if (Entry)
5622 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005623
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005624 // If this type (or a super class) has the __objc_exception__
5625 // attribute, emit an external reference.
5626 if (hasObjCExceptionAttribute(ID))
5627 return Entry =
5628 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5629 llvm::GlobalValue::ExternalLinkage,
5630 0,
5631 (std::string("OBJC_EHTYPE_$_") +
5632 ID->getIdentifier()->getName()),
5633 &CGM.getModule());
5634 }
5635
5636 // Otherwise we need to either make a new entry or fill in the
5637 // initializer.
5638 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005639 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005640 std::string VTableName = "objc_ehtype_vtable";
5641 llvm::GlobalVariable *VTableGV =
5642 CGM.getModule().getGlobalVariable(VTableName);
5643 if (!VTableGV)
5644 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5645 llvm::GlobalValue::ExternalLinkage,
5646 0, VTableName, &CGM.getModule());
5647
5648 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5649
5650 std::vector<llvm::Constant*> Values(3);
5651 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5652 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005653 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005654 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5655
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005656 if (Entry) {
5657 Entry->setInitializer(Init);
5658 } else {
5659 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5660 llvm::GlobalValue::WeakAnyLinkage,
5661 Init,
5662 (std::string("OBJC_EHTYPE_$_") +
5663 ID->getIdentifier()->getName()),
5664 &CGM.getModule());
5665 }
5666
Daniel Dunbar04d40782009-04-14 06:00:08 +00005667 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005668 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005669 Entry->setAlignment(8);
5670
5671 if (ForDefinition) {
5672 Entry->setSection("__DATA,__objc_const");
5673 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5674 } else {
5675 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5676 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005677
5678 return Entry;
5679}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005680
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005681/* *** */
5682
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005683CodeGen::CGObjCRuntime *
5684CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005685 return new CGObjCMac(CGM);
5686}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005687
5688CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005689CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005690 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005691}