blob: a0135612287d78e7833e4ca67e9cf0a6ceeae2ec [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 Lattner74391b42009-03-22 21:03:39 +000095 llvm::Constant *GcAssignWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000096
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +000098 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000099
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000101 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000104 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000107 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000110 llvm::Constant *getSyncEnterFn() {
111 // void objc_sync_enter (id)
112 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
113 llvm::FunctionType *FTy =
114 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
115 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
116 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000117
118 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000119 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000120
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000121 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
122 ~ObjCCommonTypesHelper(){}
123};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000124
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000125/// ObjCTypesHelper - Helper class that encapsulates lazy
126/// construction of varies types used during ObjC generation.
127class ObjCTypesHelper : public ObjCCommonTypesHelper {
128private:
129
Chris Lattner74391b42009-03-22 21:03:39 +0000130 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
131 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132 *MessageSendSuperFpretFn;
133
134public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000135 /// SymtabTy - LLVM type for struct objc_symtab.
136 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000137 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
138 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000139 /// ModuleTy - LLVM type for struct objc_module.
140 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000141
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000142 /// ProtocolTy - LLVM type for struct objc_protocol.
143 const llvm::StructType *ProtocolTy;
144 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
145 const llvm::Type *ProtocolPtrTy;
146 /// ProtocolExtensionTy - LLVM type for struct
147 /// objc_protocol_extension.
148 const llvm::StructType *ProtocolExtensionTy;
149 /// ProtocolExtensionTy - LLVM type for struct
150 /// objc_protocol_extension *.
151 const llvm::Type *ProtocolExtensionPtrTy;
152 /// MethodDescriptionTy - LLVM type for struct
153 /// objc_method_description.
154 const llvm::StructType *MethodDescriptionTy;
155 /// MethodDescriptionListTy - LLVM type for struct
156 /// objc_method_description_list.
157 const llvm::StructType *MethodDescriptionListTy;
158 /// MethodDescriptionListPtrTy - LLVM type for struct
159 /// objc_method_description_list *.
160 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000161 /// ProtocolListTy - LLVM type for struct objc_property_list.
162 const llvm::Type *ProtocolListTy;
163 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
164 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000165 /// CategoryTy - LLVM type for struct objc_category.
166 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000167 /// ClassTy - LLVM type for struct objc_class.
168 const llvm::StructType *ClassTy;
169 /// ClassPtrTy - LLVM type for struct objc_class *.
170 const llvm::Type *ClassPtrTy;
171 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
172 const llvm::StructType *ClassExtensionTy;
173 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
174 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 // IvarTy - LLVM type for struct objc_ivar.
176 const llvm::StructType *IvarTy;
177 /// IvarListTy - LLVM type for struct objc_ivar_list.
178 const llvm::Type *IvarListTy;
179 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
180 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000181 /// MethodListTy - LLVM type for struct objc_method_list.
182 const llvm::Type *MethodListTy;
183 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
184 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000185
186 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
187 const llvm::Type *ExceptionDataTy;
188
Anders Carlsson124526b2008-09-09 10:10:21 +0000189 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000190 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000191
192 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000193 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000194
195 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000196 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000197
198 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000199 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000200
201 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000202 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000203
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000204public:
205 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000206 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000207
208
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000210 return IsSuper ? MessageSendSuperFn : MessageSendFn;
211 }
212
Chris Lattner74391b42009-03-22 21:03:39 +0000213 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
215 }
216
Chris Lattner74391b42009-03-22 21:03:39 +0000217 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000218 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
219 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000220};
221
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000222/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000223/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000224class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000225public:
Chris Lattner74391b42009-03-22 21:03:39 +0000226 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000227 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
228 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
229 *MessageSendSuper2StretFixupFn;
230
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000231 // MethodListnfABITy - LLVM for struct _method_list_t
232 const llvm::StructType *MethodListnfABITy;
233
234 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
235 const llvm::Type *MethodListnfABIPtrTy;
236
237 // ProtocolnfABITy = LLVM for struct _protocol_t
238 const llvm::StructType *ProtocolnfABITy;
239
Daniel Dunbar948e2582009-02-15 07:36:20 +0000240 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
241 const llvm::Type *ProtocolnfABIPtrTy;
242
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000243 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
244 const llvm::StructType *ProtocolListnfABITy;
245
246 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
247 const llvm::Type *ProtocolListnfABIPtrTy;
248
249 // ClassnfABITy - LLVM for struct _class_t
250 const llvm::StructType *ClassnfABITy;
251
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000252 // ClassnfABIPtrTy - LLVM for struct _class_t*
253 const llvm::Type *ClassnfABIPtrTy;
254
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000255 // IvarnfABITy - LLVM for struct _ivar_t
256 const llvm::StructType *IvarnfABITy;
257
258 // IvarListnfABITy - LLVM for struct _ivar_list_t
259 const llvm::StructType *IvarListnfABITy;
260
261 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
262 const llvm::Type *IvarListnfABIPtrTy;
263
264 // ClassRonfABITy - LLVM for struct _class_ro_t
265 const llvm::StructType *ClassRonfABITy;
266
267 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
268 const llvm::Type *ImpnfABITy;
269
270 // CategorynfABITy - LLVM for struct _category_t
271 const llvm::StructType *CategorynfABITy;
272
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000273 // New types for nonfragile abi messaging.
274
275 // MessageRefTy - LLVM for:
276 // struct _message_ref_t {
277 // IMP messenger;
278 // SEL name;
279 // };
280 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000281 // MessageRefCTy - clang type for struct _message_ref_t
282 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000283
284 // MessageRefPtrTy - LLVM for struct _message_ref_t*
285 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000286 // MessageRefCPtrTy - clang type for struct _message_ref_t*
287 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000288
Fariborz Jahanianef163782009-02-05 01:13:09 +0000289 // MessengerTy - Type of the messenger (shown as IMP above)
290 const llvm::FunctionType *MessengerTy;
291
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000292 // SuperMessageRefTy - LLVM for:
293 // struct _super_message_ref_t {
294 // SUPER_IMP messenger;
295 // SEL name;
296 // };
297 const llvm::StructType *SuperMessageRefTy;
298
299 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
300 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000301
302 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
303 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000304 llvm::Value *getEHPersonalityPtr() {
305 llvm::Constant *Personality =
306 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
307 std::vector<const llvm::Type*>(),
308 true),
309 "__objc_personality_v0");
310 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
311 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000312
Chris Lattner74391b42009-03-22 21:03:39 +0000313 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000314
315 const llvm::StructType *EHTypeTy;
316 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000317
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000318 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
319 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000320};
321
322class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000323public:
324 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000325 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000326 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000327 unsigned int ivar_bytepos;
328 unsigned int ivar_size;
329 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
330 };
331
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000332 class SKIP_SCAN {
333 public:
334 unsigned int skip;
335 unsigned int scan;
336 SKIP_SCAN() : skip(0), scan(0) {}
337 };
338
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000339protected:
340 CodeGen::CodeGenModule &CGM;
341 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000342 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000343
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000344 // gc ivar layout bitmap calculation helper caches.
345 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
346 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
347 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000348
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000349 /// LazySymbols - Symbols to generate a lazy reference for. See
350 /// DefinedSymbols and FinishModule().
351 std::set<IdentifierInfo*> LazySymbols;
352
353 /// DefinedSymbols - External symbols which are defined by this
354 /// module. The symbols in this list and LazySymbols are used to add
355 /// special linker symbols which ensure that Objective-C modules are
356 /// linked properly.
357 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000358
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000359 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000360 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000361
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000362 /// MethodVarNames - uniqued method variable names.
363 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000364
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000365 /// MethodVarTypes - uniqued method type signatures. We have to use
366 /// a StringMap here because have no other unique reference.
367 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000369 /// MethodDefinitions - map of methods which have been defined in
370 /// this translation unit.
371 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000372
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000373 /// PropertyNames - uniqued method variable names.
374 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000376 /// ClassReferences - uniqued class references.
377 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000378
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000379 /// SelectorReferences - uniqued selector references.
380 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000381
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382 /// Protocols - Protocols for which an objc_protocol structure has
383 /// been emitted. Forward declarations are handled by creating an
384 /// empty structure whose initializer is filled in when/if defined.
385 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000386
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000387 /// DefinedProtocols - Protocols which have actually been
388 /// defined. We should not need this, see FIXME in GenerateProtocol.
389 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000390
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 /// DefinedClasses - List of defined classes.
392 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000394 /// DefinedCategories - List of defined categories.
395 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000396
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000397 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000398 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000399 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000400
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000401 /// GetNameForMethod - Return a name for the given method.
402 /// \param[out] NameOut - The return value.
403 void GetNameForMethod(const ObjCMethodDecl *OMD,
404 const ObjCContainerDecl *CD,
405 std::string &NameOut);
406
407 /// GetMethodVarName - Return a unique constant for the given
408 /// selector's name. The return value has type char *.
409 llvm::Constant *GetMethodVarName(Selector Sel);
410 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
411 llvm::Constant *GetMethodVarName(const std::string &Name);
412
413 /// GetMethodVarType - Return a unique constant for the given
414 /// selector's name. The return value has type char *.
415
416 // FIXME: This is a horrible name.
417 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000418 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000419
420 /// GetPropertyName - Return a unique constant for the given
421 /// name. The return value has type char *.
422 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
423
424 // FIXME: This can be dropped once string functions are unified.
425 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
426 const Decl *Container);
427
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000428 /// GetClassName - Return a unique constant for the given selector's
429 /// name. The return value has type char *.
430 llvm::Constant *GetClassName(IdentifierInfo *Ident);
431
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000432 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
433 /// interface declaration.
434 const llvm::StructLayout *GetInterfaceDeclStructLayout(
435 const ObjCInterfaceDecl *ID) const;
436
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000437 /// BuildIvarLayout - Builds ivar layout bitmap for the class
438 /// implementation for the __strong or __weak case.
439 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000440 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
441 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000442
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000443 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
444 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000445 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000446 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000447 unsigned int BytePos, bool ForStrongLayout,
448 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000449
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000450 /// GetIvarLayoutName - Returns a unique constant for the given
451 /// ivar layout bitmap.
452 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
453 const ObjCCommonTypesHelper &ObjCTypes);
454
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000455 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
456 RecordDecl::field_iterator &FIV,
457 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000458 /// EmitPropertyList - Emit the given property list. The return
459 /// value has type PropertyListPtrTy.
460 llvm::Constant *EmitPropertyList(const std::string &Name,
461 const Decl *Container,
462 const ObjCContainerDecl *OCD,
463 const ObjCCommonTypesHelper &ObjCTypes);
464
Fariborz Jahanianda320092009-01-29 19:24:30 +0000465 /// GetProtocolRef - Return a reference to the internal protocol
466 /// description, creating an empty one if it has not been
467 /// defined. The return value has type ProtocolPtrTy.
468 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000469
470 /// GetIvarBaseOffset - returns ivars byte offset.
471 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000472 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000473
Chris Lattnercd0ee142009-03-31 08:33:16 +0000474 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000475 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
476 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000477 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000478
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000479 /// CreateMetadataVar - Create a global variable with internal
480 /// linkage for use by the Objective-C runtime.
481 ///
482 /// This is a convenience wrapper which not only creates the
483 /// variable, but also sets the section and alignment and adds the
484 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000485 ///
486 /// \param Name - The variable name.
487 /// \param Init - The variable initializer; this is also used to
488 /// define the type of the variable.
489 /// \param Section - The section the variable should go into, or 0.
490 /// \param Align - The alignment for the variable, or 0.
491 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000492 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000493 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
494 llvm::Constant *Init,
495 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000496 unsigned Align,
497 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000498
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000499public:
500 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
501 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000502
Steve Naroff33fdb732009-03-31 16:53:37 +0000503 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000504
505 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
506 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000507
508 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
509
510 /// GetOrEmitProtocol - Get the protocol object for the given
511 /// declaration, emitting it if necessary. The return value has type
512 /// ProtocolPtrTy.
513 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
514
515 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
516 /// object for the given declaration, emitting it if needed. These
517 /// forward references will be filled in with empty bodies if no
518 /// definition is seen. The return value has type ProtocolPtrTy.
519 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000520};
521
522class CGObjCMac : public CGObjCCommonMac {
523private:
524 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000525 /// EmitImageInfo - Emit the image info marker used to encode some module
526 /// level information.
527 void EmitImageInfo();
528
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000529 /// EmitModuleInfo - Another marker encoding module level
530 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000531 void EmitModuleInfo();
532
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000533 /// EmitModuleSymols - Emit module symbols, the list of defined
534 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000535 llvm::Constant *EmitModuleSymbols();
536
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000537 /// FinishModule - Write out global data structures at the end of
538 /// processing a translation unit.
539 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000540
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000541 /// EmitClassExtension - Generate the class extension structure used
542 /// to store the weak ivar layout and properties. The return value
543 /// has type ClassExtensionPtrTy.
544 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
545
546 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
547 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000548 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000549 const ObjCInterfaceDecl *ID);
550
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000551 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000552 QualType ResultType,
553 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000554 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000555 QualType Arg0Ty,
556 bool IsSuper,
557 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000558
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000559 /// EmitIvarList - Emit the ivar list for the given
560 /// implementation. If ForClass is true the list of class ivars
561 /// (i.e. metaclass ivars) is emitted, otherwise the list of
562 /// interface ivars will be emitted. The return value has type
563 /// IvarListPtrTy.
564 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000565 bool ForClass);
566
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000567 /// EmitMetaClass - Emit a forward reference to the class structure
568 /// for the metaclass of the given interface. The return value has
569 /// type ClassPtrTy.
570 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
571
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000572 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000573 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000574 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
575 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000576 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000577 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000578
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000579 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000580
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000581 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000582
583 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000584 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000585 llvm::Constant *EmitMethodList(const std::string &Name,
586 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000587 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000588
589 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000590 /// method declarations.
591 /// - TypeName: The name for the type containing the methods.
592 /// - IsProtocol: True iff these methods are for a protocol.
593 /// - ClassMethds: True iff these are class methods.
594 /// - Required: When true, only "required" methods are
595 /// listed. Similarly, when false only "optional" methods are
596 /// listed. For classes this should always be true.
597 /// - begin, end: The method list to output.
598 ///
599 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000600 llvm::Constant *EmitMethodDescList(const std::string &Name,
601 const char *Section,
602 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000603
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000604 /// GetOrEmitProtocol - Get the protocol object for the given
605 /// declaration, emitting it if necessary. The return value has type
606 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000607 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000608
609 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
610 /// object for the given declaration, emitting it if needed. These
611 /// forward references will be filled in with empty bodies if no
612 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000613 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000614
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000615 /// EmitProtocolExtension - Generate the protocol extension
616 /// structure used to store optional instance and class methods, and
617 /// protocol properties. The return value has type
618 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000619 llvm::Constant *
620 EmitProtocolExtension(const ObjCProtocolDecl *PD,
621 const ConstantVector &OptInstanceMethods,
622 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000623
624 /// EmitProtocolList - Generate the list of referenced
625 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000626 llvm::Constant *EmitProtocolList(const std::string &Name,
627 ObjCProtocolDecl::protocol_iterator begin,
628 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000629
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000630 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
631 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000632 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000633
Fariborz Jahanianda320092009-01-29 19:24:30 +0000634 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000635 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000636
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000637 virtual llvm::Function *ModuleInitFunction();
638
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000639 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000640 QualType ResultType,
641 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000642 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000643 bool IsClassMessage,
644 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000645
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000646 virtual CodeGen::RValue
647 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000648 QualType ResultType,
649 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000650 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000651 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000652 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000653 bool IsClassMessage,
654 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000655
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000656 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000657 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000658
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000659 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000660
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000661 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000662
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000663 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000664
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000665 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000666 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000667
Chris Lattner74391b42009-03-22 21:03:39 +0000668 virtual llvm::Constant *GetPropertyGetFunction();
669 virtual llvm::Constant *GetPropertySetFunction();
670 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000671
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000672 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
673 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000674 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
675 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000676 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000677 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000678 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
679 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000680 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
681 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000682 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
683 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000684 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
685 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000686
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000687 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
688 QualType ObjectTy,
689 llvm::Value *BaseValue,
690 const ObjCIvarDecl *Ivar,
691 const FieldDecl *Field,
692 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000693 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
694 ObjCInterfaceDecl *Interface,
695 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000696};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000697
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000698class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000699private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000700 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000701 llvm::GlobalVariable* ObjCEmptyCacheVar;
702 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000703
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000704 /// MetaClassReferences - uniqued meta class references.
705 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000706
707 /// EHTypeReferences - uniqued class ehtype references.
708 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000709
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000710 /// FinishNonFragileABIModule - Write out global data structures at the end of
711 /// processing a translation unit.
712 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000713
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000714 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
715 unsigned InstanceStart,
716 unsigned InstanceSize,
717 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000718 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
719 llvm::Constant *IsAGV,
720 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000721 llvm::Constant *ClassRoGV,
722 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000723
724 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
725
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000726 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
727
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000728 /// EmitMethodList - Emit the method list for the given
729 /// implementation. The return value has type MethodListnfABITy.
730 llvm::Constant *EmitMethodList(const std::string &Name,
731 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000732 const ConstantVector &Methods);
733 /// EmitIvarList - Emit the ivar list for the given
734 /// implementation. If ForClass is true the list of class ivars
735 /// (i.e. metaclass ivars) is emitted, otherwise the list of
736 /// interface ivars will be emitted. The return value has type
737 /// IvarListnfABIPtrTy.
738 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000739
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000740 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000741 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000742 unsigned long int offset);
743
Fariborz Jahanianda320092009-01-29 19:24:30 +0000744 /// GetOrEmitProtocol - Get the protocol object for the given
745 /// declaration, emitting it if necessary. The return value has type
746 /// ProtocolPtrTy.
747 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
748
749 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
750 /// object for the given declaration, emitting it if needed. These
751 /// forward references will be filled in with empty bodies if no
752 /// definition is seen. The return value has type ProtocolPtrTy.
753 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
754
755 /// EmitProtocolList - Generate the list of referenced
756 /// protocols. The return value has type ProtocolListPtrTy.
757 llvm::Constant *EmitProtocolList(const std::string &Name,
758 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000759 ObjCProtocolDecl::protocol_iterator end);
760
761 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
762 QualType ResultType,
763 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000764 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000765 QualType Arg0Ty,
766 bool IsSuper,
767 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000768
769 /// GetClassGlobal - Return the global variable for the Objective-C
770 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000771 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
772
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000773 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
774 /// for the given class.
775 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000776 const ObjCInterfaceDecl *ID,
777 bool IsSuper = false);
778
779 /// EmitMetaClassRef - Return a Value * of the address of _class_t
780 /// meta-data
781 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
782 const ObjCInterfaceDecl *ID);
783
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000784 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
785 /// the given ivar.
786 ///
787 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000788 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000789 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000790
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000791 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
792 /// for the given selector.
793 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000794
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000795 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000796 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000797 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
798 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000799
800 const char *getMetaclassSymbolPrefix() const {
801 return "OBJC_METACLASS_$_";
802 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000803
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000804 const char *getClassSymbolPrefix() const {
805 return "OBJC_CLASS_$_";
806 }
807
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000808public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000809 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000810 // FIXME. All stubs for now!
811 virtual llvm::Function *ModuleInitFunction();
812
813 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
814 QualType ResultType,
815 Selector Sel,
816 llvm::Value *Receiver,
817 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000818 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000819
820 virtual CodeGen::RValue
821 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
822 QualType ResultType,
823 Selector Sel,
824 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000825 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000826 llvm::Value *Receiver,
827 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000828 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000829
830 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000831 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000832
833 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000834 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000835
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000836 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000837
838 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000839 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000840 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000841
Chris Lattner74391b42009-03-22 21:03:39 +0000842 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000843 return ObjCTypes.GetPropertyFn;
844 }
Chris Lattner74391b42009-03-22 21:03:39 +0000845 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000846 return ObjCTypes.SetPropertyFn;
847 }
Chris Lattner74391b42009-03-22 21:03:39 +0000848 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000849 return ObjCTypes.EnumerationMutationFn;
850 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000851
852 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000853 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000854 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000855 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000856 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000857 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000858 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000859 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000860 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000861 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000862 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000863 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000864 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000865 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000866 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
867 QualType ObjectTy,
868 llvm::Value *BaseValue,
869 const ObjCIvarDecl *Ivar,
870 const FieldDecl *Field,
871 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000872 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
873 ObjCInterfaceDecl *Interface,
874 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000875};
876
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000877} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000878
879/* *** Helper Functions *** */
880
881/// getConstantGEP() - Help routine to construct simple GEPs.
882static llvm::Constant *getConstantGEP(llvm::Constant *C,
883 unsigned idx0,
884 unsigned idx1) {
885 llvm::Value *Idxs[] = {
886 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
887 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
888 };
889 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
890}
891
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000892/// hasObjCExceptionAttribute - Return true if this class or any super
893/// class has the __objc_exception__ attribute.
894static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000895 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000896 return true;
897 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
898 return hasObjCExceptionAttribute(Super);
899 return false;
900}
901
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000902/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000903
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000904CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
905 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000906{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000907 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000908 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000909}
910
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000911/// GetClass - Return a reference to the class for the given interface
912/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000913llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000914 const ObjCInterfaceDecl *ID) {
915 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000916}
917
918/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000919llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000920 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000921}
922
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000923/// Generate a constant CFString object.
924/*
925 struct __builtin_CFString {
926 const int *isa; // point to __CFConstantStringClassReference
927 int flags;
928 const char *str;
929 long length;
930 };
931*/
932
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000933llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000934 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000935 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000936}
937
938/// Generates a message send where the super is the receiver. This is
939/// a message send to self with special delivery semantics indicating
940/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000941CodeGen::RValue
942CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000943 QualType ResultType,
944 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000945 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000946 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000947 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000948 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000949 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000950 // Create and init a super structure; this is a (receiver, class)
951 // pair we will pass to objc_msgSendSuper.
952 llvm::Value *ObjCSuper =
953 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
954 llvm::Value *ReceiverAsObject =
955 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
956 CGF.Builder.CreateStore(ReceiverAsObject,
957 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000958
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000959 // If this is a class message the metaclass is passed as the target.
960 llvm::Value *Target;
961 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000962 if (isCategoryImpl) {
963 // Message sent to 'super' in a class method defined in a category
964 // implementation requires an odd treatment.
965 // If we are in a class method, we must retrieve the
966 // _metaclass_ for the current class, pointed at by
967 // the class's "isa" pointer. The following assumes that
968 // isa" is the first ivar in a class (which it must be).
969 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
970 Target = CGF.Builder.CreateStructGEP(Target, 0);
971 Target = CGF.Builder.CreateLoad(Target);
972 }
973 else {
974 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
975 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
976 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
977 Target = Super;
978 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000979 } else {
980 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
981 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000982 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
983 // and ObjCTypes types.
984 const llvm::Type *ClassTy =
985 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000986 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000987 CGF.Builder.CreateStore(Target,
988 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
989
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000990 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000991 ObjCSuper, ObjCTypes.SuperPtrCTy,
992 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000993}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000994
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000995/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000996CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000997 QualType ResultType,
998 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000999 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001000 bool IsClassMessage,
1001 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001002 llvm::Value *Arg0 =
1003 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001004 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001005 Arg0, CGF.getContext().getObjCIdType(),
1006 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001007}
1008
1009CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001010 QualType ResultType,
1011 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001012 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001013 QualType Arg0Ty,
1014 bool IsSuper,
1015 const CallArgList &CallArgs) {
1016 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001017 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1018 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1019 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001020 CGF.getContext().getObjCSelType()));
1021 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001022
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001023 CodeGenTypes &Types = CGM.getTypes();
1024 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1025 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001026
1027 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001028 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001029 Fn = ObjCTypes.getSendStretFn(IsSuper);
1030 } else if (ResultType->isFloatingType()) {
1031 // FIXME: Sadly, this is wrong. This actually depends on the
1032 // architecture. This happens to be right for x86-32 though.
1033 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1034 } else {
1035 Fn = ObjCTypes.getSendFn(IsSuper);
1036 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001037 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001038 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001039}
1040
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001041llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001042 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001043 // FIXME: I don't understand why gcc generates this, or where it is
1044 // resolved. Investigate. Its also wasteful to look this up over and
1045 // over.
1046 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1047
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001048 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1049 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001050}
1051
Fariborz Jahanianda320092009-01-29 19:24:30 +00001052void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001053 // FIXME: We shouldn't need this, the protocol decl should contain
1054 // enough information to tell us whether this was a declaration or a
1055 // definition.
1056 DefinedProtocols.insert(PD->getIdentifier());
1057
1058 // If we have generated a forward reference to this protocol, emit
1059 // it now. Otherwise do nothing, the protocol objects are lazily
1060 // emitted.
1061 if (Protocols.count(PD->getIdentifier()))
1062 GetOrEmitProtocol(PD);
1063}
1064
Fariborz Jahanianda320092009-01-29 19:24:30 +00001065llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001066 if (DefinedProtocols.count(PD->getIdentifier()))
1067 return GetOrEmitProtocol(PD);
1068 return GetOrEmitProtocolRef(PD);
1069}
1070
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001071/*
1072 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1073 struct _objc_protocol {
1074 struct _objc_protocol_extension *isa;
1075 char *protocol_name;
1076 struct _objc_protocol_list *protocol_list;
1077 struct _objc__method_prototype_list *instance_methods;
1078 struct _objc__method_prototype_list *class_methods
1079 };
1080
1081 See EmitProtocolExtension().
1082*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001083llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1084 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1085
1086 // Early exit if a defining object has already been generated.
1087 if (Entry && Entry->hasInitializer())
1088 return Entry;
1089
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001090 // FIXME: I don't understand why gcc generates this, or where it is
1091 // resolved. Investigate. Its also wasteful to look this up over and
1092 // over.
1093 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1094
Chris Lattner8ec03f52008-11-24 03:54:41 +00001095 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001096
1097 // Construct method lists.
1098 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1099 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001100 for (ObjCProtocolDecl::instmeth_iterator
1101 i = PD->instmeth_begin(CGM.getContext()),
1102 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103 ObjCMethodDecl *MD = *i;
1104 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1105 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1106 OptInstanceMethods.push_back(C);
1107 } else {
1108 InstanceMethods.push_back(C);
1109 }
1110 }
1111
Douglas Gregor6ab35242009-04-09 21:40:53 +00001112 for (ObjCProtocolDecl::classmeth_iterator
1113 i = PD->classmeth_begin(CGM.getContext()),
1114 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001115 ObjCMethodDecl *MD = *i;
1116 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1117 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1118 OptClassMethods.push_back(C);
1119 } else {
1120 ClassMethods.push_back(C);
1121 }
1122 }
1123
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001124 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001125 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001126 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001127 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001128 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001129 PD->protocol_begin(),
1130 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001131 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001132 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1133 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001134 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1135 InstanceMethods);
1136 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001137 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1138 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001139 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1140 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001141 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1142 Values);
1143
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001144 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001145 // Already created, fix the linkage and update the initializer.
1146 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001147 Entry->setInitializer(Init);
1148 } else {
1149 Entry =
1150 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1151 llvm::GlobalValue::InternalLinkage,
1152 Init,
1153 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1154 &CGM.getModule());
1155 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001156 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001157 UsedGlobals.push_back(Entry);
1158 // FIXME: Is this necessary? Why only for protocol?
1159 Entry->setAlignment(4);
1160 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001161
1162 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001163}
1164
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001165llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001166 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1167
1168 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001169 // We use the initializer as a marker of whether this is a forward
1170 // reference or not. At module finalization we add the empty
1171 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001172 Entry =
1173 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001174 llvm::GlobalValue::ExternalLinkage,
1175 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001176 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001177 &CGM.getModule());
1178 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001179 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001180 UsedGlobals.push_back(Entry);
1181 // FIXME: Is this necessary? Why only for protocol?
1182 Entry->setAlignment(4);
1183 }
1184
1185 return Entry;
1186}
1187
1188/*
1189 struct _objc_protocol_extension {
1190 uint32_t size;
1191 struct objc_method_description_list *optional_instance_methods;
1192 struct objc_method_description_list *optional_class_methods;
1193 struct objc_property_list *instance_properties;
1194 };
1195*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001196llvm::Constant *
1197CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1198 const ConstantVector &OptInstanceMethods,
1199 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001200 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001201 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001202 std::vector<llvm::Constant*> Values(4);
1203 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001204 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001205 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1206 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001207 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1208 OptInstanceMethods);
1209 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001210 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1211 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001212 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1213 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001214 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1215 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001216 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001217
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001218 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001219 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1220 Values[3]->isNullValue())
1221 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1222
1223 llvm::Constant *Init =
1224 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001225
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001226 // No special section, but goes in llvm.used
1227 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1228 Init,
1229 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001230}
1231
1232/*
1233 struct objc_protocol_list {
1234 struct objc_protocol_list *next;
1235 long count;
1236 Protocol *list[];
1237 };
1238*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001239llvm::Constant *
1240CGObjCMac::EmitProtocolList(const std::string &Name,
1241 ObjCProtocolDecl::protocol_iterator begin,
1242 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001243 std::vector<llvm::Constant*> ProtocolRefs;
1244
Daniel Dunbardbc933702008-08-21 21:57:41 +00001245 for (; begin != end; ++begin)
1246 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001247
1248 // Just return null for empty protocol lists
1249 if (ProtocolRefs.empty())
1250 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1251
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001252 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001253 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1254
1255 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001256 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1258 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1259 Values[2] =
1260 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1261 ProtocolRefs.size()),
1262 ProtocolRefs);
1263
1264 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1265 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001266 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001267 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001268 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1269}
1270
1271/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001272 struct _objc_property {
1273 const char * const name;
1274 const char * const attributes;
1275 };
1276
1277 struct _objc_property_list {
1278 uint32_t entsize; // sizeof (struct _objc_property)
1279 uint32_t prop_count;
1280 struct _objc_property[prop_count];
1281 };
1282*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001283llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1284 const Decl *Container,
1285 const ObjCContainerDecl *OCD,
1286 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001287 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001288 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1289 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001290 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001291 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001292 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001293 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1294 Prop));
1295 }
1296
1297 // Return null for empty list.
1298 if (Properties.empty())
1299 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1300
1301 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001302 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001303 std::vector<llvm::Constant*> Values(3);
1304 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1305 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1306 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1307 Properties.size());
1308 Values[2] = llvm::ConstantArray::get(AT, Properties);
1309 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1310
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001311 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001312 llvm::GlobalVariable *GV =
1313 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1314 0, true);
1315 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001316}
1317
1318/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001319 struct objc_method_description_list {
1320 int count;
1321 struct objc_method_description list[];
1322 };
1323*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001324llvm::Constant *
1325CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1326 std::vector<llvm::Constant*> Desc(2);
1327 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1328 ObjCTypes.SelectorPtrTy);
1329 Desc[1] = GetMethodVarType(MD);
1330 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1331 Desc);
1332}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001333
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001334llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1335 const char *Section,
1336 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001337 // Return null for empty list.
1338 if (Methods.empty())
1339 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1340
1341 std::vector<llvm::Constant*> Values(2);
1342 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1343 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1344 Methods.size());
1345 Values[1] = llvm::ConstantArray::get(AT, Methods);
1346 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1347
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001348 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001349 return llvm::ConstantExpr::getBitCast(GV,
1350 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001351}
1352
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001353/*
1354 struct _objc_category {
1355 char *category_name;
1356 char *class_name;
1357 struct _objc_method_list *instance_methods;
1358 struct _objc_method_list *class_methods;
1359 struct _objc_protocol_list *protocols;
1360 uint32_t size; // <rdar://4585769>
1361 struct _objc_property_list *instance_properties;
1362 };
1363 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001364void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001365 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001366
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001367 // FIXME: This is poor design, the OCD should have a pointer to the
1368 // category decl. Additionally, note that Category can be null for
1369 // the @implementation w/o an @interface case. Sema should just
1370 // create one for us as it does for @implementation so everyone else
1371 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001372 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001373 const ObjCCategoryDecl *Category =
1374 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001375 std::string ExtName(Interface->getNameAsString() + "_" +
1376 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001377
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001378 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1379 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1380 e = OCD->instmeth_end(); i != e; ++i) {
1381 // Instance methods should always be defined.
1382 InstanceMethods.push_back(GetMethodConstant(*i));
1383 }
1384 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1385 e = OCD->classmeth_end(); i != e; ++i) {
1386 // Class methods should always be defined.
1387 ClassMethods.push_back(GetMethodConstant(*i));
1388 }
1389
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001390 std::vector<llvm::Constant*> Values(7);
1391 Values[0] = GetClassName(OCD->getIdentifier());
1392 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001393 Values[2] =
1394 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1395 ExtName,
1396 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001397 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001398 Values[3] =
1399 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1400 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001401 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001402 if (Category) {
1403 Values[4] =
1404 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1405 Category->protocol_begin(),
1406 Category->protocol_end());
1407 } else {
1408 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1409 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001410 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001411
1412 // If there is no category @interface then there can be no properties.
1413 if (Category) {
1414 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001415 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001416 } else {
1417 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1418 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001419
1420 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1421 Values);
1422
1423 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001424 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1425 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001426 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001427 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001428}
1429
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001430// FIXME: Get from somewhere?
1431enum ClassFlags {
1432 eClassFlags_Factory = 0x00001,
1433 eClassFlags_Meta = 0x00002,
1434 // <rdr://5142207>
1435 eClassFlags_HasCXXStructors = 0x02000,
1436 eClassFlags_Hidden = 0x20000,
1437 eClassFlags_ABI2_Hidden = 0x00010,
1438 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1439};
1440
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001441/*
1442 struct _objc_class {
1443 Class isa;
1444 Class super_class;
1445 const char *name;
1446 long version;
1447 long info;
1448 long instance_size;
1449 struct _objc_ivar_list *ivars;
1450 struct _objc_method_list *methods;
1451 struct _objc_cache *cache;
1452 struct _objc_protocol_list *protocols;
1453 // Objective-C 1.0 extensions (<rdr://4585769>)
1454 const char *ivar_layout;
1455 struct _objc_class_ext *ext;
1456 };
1457
1458 See EmitClassExtension();
1459 */
1460void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001461 DefinedSymbols.insert(ID->getIdentifier());
1462
Chris Lattner8ec03f52008-11-24 03:54:41 +00001463 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001464 // FIXME: Gross
1465 ObjCInterfaceDecl *Interface =
1466 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001467 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001468 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001469 Interface->protocol_begin(),
1470 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001471 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001472 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001473 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001474 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001475
1476 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001477 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001478 Flags |= eClassFlags_Hidden;
1479
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001480 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1481 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1482 e = ID->instmeth_end(); i != e; ++i) {
1483 // Instance methods should always be defined.
1484 InstanceMethods.push_back(GetMethodConstant(*i));
1485 }
1486 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1487 e = ID->classmeth_end(); i != e; ++i) {
1488 // Class methods should always be defined.
1489 ClassMethods.push_back(GetMethodConstant(*i));
1490 }
1491
1492 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1493 e = ID->propimpl_end(); i != e; ++i) {
1494 ObjCPropertyImplDecl *PID = *i;
1495
1496 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1497 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1498
1499 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1500 if (llvm::Constant *C = GetMethodConstant(MD))
1501 InstanceMethods.push_back(C);
1502 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1503 if (llvm::Constant *C = GetMethodConstant(MD))
1504 InstanceMethods.push_back(C);
1505 }
1506 }
1507
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001509 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001510 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001511 // Record a reference to the super class.
1512 LazySymbols.insert(Super->getIdentifier());
1513
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001514 Values[ 1] =
1515 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1516 ObjCTypes.ClassPtrTy);
1517 } else {
1518 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1519 }
1520 Values[ 2] = GetClassName(ID->getIdentifier());
1521 // Version is always 0.
1522 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1523 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1524 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001525 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001526 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001527 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001528 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001529 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001530 // cache is always NULL.
1531 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1532 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001533 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001534 // Values[10] = BuildIvarLayout(ID, true);
1535 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001536 Values[11] = EmitClassExtension(ID);
1537 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1538 Values);
1539
1540 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001541 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1542 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001543 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001544 DefinedClasses.push_back(GV);
1545}
1546
1547llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1548 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001549 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001550 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001551 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001552 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001553
Daniel Dunbar04d40782009-04-14 06:00:08 +00001554 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001555 Flags |= eClassFlags_Hidden;
1556
1557 std::vector<llvm::Constant*> Values(12);
1558 // The isa for the metaclass is the root of the hierarchy.
1559 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1560 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1561 Root = Super;
1562 Values[ 0] =
1563 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1564 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001565 // The super class for the metaclass is emitted as the name of the
1566 // super class. The runtime fixes this up to point to the
1567 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001568 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1569 Values[ 1] =
1570 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1571 ObjCTypes.ClassPtrTy);
1572 } else {
1573 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1574 }
1575 Values[ 2] = GetClassName(ID->getIdentifier());
1576 // Version is always 0.
1577 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1578 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1579 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001580 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001581 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001582 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001583 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001584 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001585 // cache is always NULL.
1586 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1587 Values[ 9] = Protocols;
1588 // ivar_layout for metaclass is always NULL.
1589 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1590 // The class extension is always unused for metaclasses.
1591 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1592 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1593 Values);
1594
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001595 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001596 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001597
1598 // Check for a forward reference.
1599 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1600 if (GV) {
1601 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1602 "Forward metaclass reference has incorrect type.");
1603 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1604 GV->setInitializer(Init);
1605 } else {
1606 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1607 llvm::GlobalValue::InternalLinkage,
1608 Init, Name,
1609 &CGM.getModule());
1610 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001611 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001612 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001613 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001614
1615 return GV;
1616}
1617
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001618llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001619 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001620
1621 // FIXME: Should we look these up somewhere other than the
1622 // module. Its a bit silly since we only generate these while
1623 // processing an implementation, so exactly one pointer would work
1624 // if know when we entered/exitted an implementation block.
1625
1626 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001627 // Previously, metaclass with internal linkage may have been defined.
1628 // pass 'true' as 2nd argument so it is returned.
1629 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001630 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1631 "Forward metaclass reference has incorrect type.");
1632 return GV;
1633 } else {
1634 // Generate as an external reference to keep a consistent
1635 // module. This will be patched up when we emit the metaclass.
1636 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1637 llvm::GlobalValue::ExternalLinkage,
1638 0,
1639 Name,
1640 &CGM.getModule());
1641 }
1642}
1643
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001644/*
1645 struct objc_class_ext {
1646 uint32_t size;
1647 const char *weak_ivar_layout;
1648 struct _objc_property_list *properties;
1649 };
1650*/
1651llvm::Constant *
1652CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1653 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001654 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001655
1656 std::vector<llvm::Constant*> Values(3);
1657 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001658 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001659 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001660 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001661 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001662 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001663
1664 // Return null if no extension bits are used.
1665 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1666 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1667
1668 llvm::Constant *Init =
1669 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001670 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1671 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001672}
1673
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001674/// countInheritedIvars - count number of ivars in class and its super class(s)
1675///
Douglas Gregor6ab35242009-04-09 21:40:53 +00001676static int countInheritedIvars(const ObjCInterfaceDecl *OI,
1677 ASTContext &Context) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001678 int count = 0;
1679 if (!OI)
1680 return 0;
1681 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1682 if (SuperClass)
Douglas Gregor6ab35242009-04-09 21:40:53 +00001683 count += countInheritedIvars(SuperClass, Context);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001684 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1685 E = OI->ivar_end(); I != E; ++I)
1686 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001687 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001688 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1689 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian18191882009-03-31 18:11:23 +00001690 if ((*I)->getPropertyIvarDecl())
1691 ++count;
1692 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001693 return count;
1694}
1695
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001696/// getInterfaceDeclForIvar - Get the interface declaration node where
1697/// this ivar is declared in.
1698/// FIXME. Ideally, this info should be in the ivar node. But currently
1699/// it is not and prevailing wisdom is that ASTs should not have more
1700/// info than is absolutely needed, even though this info reflects the
1701/// source language.
1702///
1703static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1704 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001705 const ObjCIvarDecl *IVD,
1706 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001707 if (!OI)
1708 return 0;
1709 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1710 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1711 E = OI->ivar_end(); I != E; ++I)
1712 if ((*I)->getIdentifier() == IVD->getIdentifier())
1713 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001714 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001715 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1716 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001717 ObjCPropertyDecl *PDecl = (*I);
1718 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1719 if (IV->getIdentifier() == IVD->getIdentifier())
1720 return OI;
1721 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001722 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001723}
1724
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001725/*
1726 struct objc_ivar {
1727 char *ivar_name;
1728 char *ivar_type;
1729 int ivar_offset;
1730 };
1731
1732 struct objc_ivar_list {
1733 int ivar_count;
1734 struct objc_ivar list[count];
1735 };
1736 */
1737llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001738 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001739 std::vector<llvm::Constant*> Ivars, Ivar(3);
1740
1741 // When emitting the root class GCC emits ivar entries for the
1742 // actual class structure. It is not clear if we need to follow this
1743 // behavior; for now lets try and get away with not doing it. If so,
1744 // the cleanest solution would be to make up an ObjCInterfaceDecl
1745 // for the class.
1746 if (ForClass)
1747 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001748
1749 ObjCInterfaceDecl *OID =
1750 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001751 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001752
1753 RecordDecl::field_iterator ifield, pfield;
1754 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001755 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
1756 ifield != e; ++ifield) {
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001757 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001758 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001759 if (Field->getIdentifier())
1760 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1761 else
1762 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001763 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001764 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001765 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001766 }
1767
1768 // Return null for empty list.
1769 if (Ivars.empty())
1770 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1771
1772 std::vector<llvm::Constant*> Values(2);
1773 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1774 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1775 Ivars.size());
1776 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1777 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1778
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001779 llvm::GlobalVariable *GV;
1780 if (ForClass)
1781 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001782 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1783 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001784 else
1785 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1786 + ID->getNameAsString(),
1787 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1788 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001789 return llvm::ConstantExpr::getBitCast(GV,
1790 ObjCTypes.IvarListPtrTy);
1791}
1792
1793/*
1794 struct objc_method {
1795 SEL method_name;
1796 char *method_types;
1797 void *method;
1798 };
1799
1800 struct objc_method_list {
1801 struct objc_method_list *obsolete;
1802 int count;
1803 struct objc_method methods_list[count];
1804 };
1805*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001806
1807/// GetMethodConstant - Return a struct objc_method constant for the
1808/// given method if it has been defined. The result is null if the
1809/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001810llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001811 // FIXME: Use DenseMap::lookup
1812 llvm::Function *Fn = MethodDefinitions[MD];
1813 if (!Fn)
1814 return 0;
1815
1816 std::vector<llvm::Constant*> Method(3);
1817 Method[0] =
1818 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1819 ObjCTypes.SelectorPtrTy);
1820 Method[1] = GetMethodVarType(MD);
1821 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1822 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1823}
1824
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001825llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1826 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001827 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001828 // Return null for empty list.
1829 if (Methods.empty())
1830 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1831
1832 std::vector<llvm::Constant*> Values(3);
1833 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1834 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1835 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1836 Methods.size());
1837 Values[2] = llvm::ConstantArray::get(AT, Methods);
1838 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1839
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001840 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001841 return llvm::ConstantExpr::getBitCast(GV,
1842 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001843}
1844
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001845llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001846 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001847 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001848 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001849
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001850 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001851 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001852 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001853 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001854 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001855 llvm::GlobalValue::InternalLinkage,
1856 Name,
1857 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001858 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001859
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001860 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001861}
1862
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001863uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001864 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001865 if (!Field->isBitField())
1866 return Layout->getElementOffset(
1867 CGM.getTypes().getLLVMFieldNo(Field));
1868 // FIXME. Must be a better way of getting a bitfield base offset.
1869 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1870 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1871 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1872 offset = (offset*size)/8;
1873 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001874}
1875
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001876/// GetFieldBaseOffset - return's field byt offset.
1877uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1878 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001879 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001880 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001881 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1882 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001883}
1884
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001885llvm::GlobalVariable *
1886CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1887 llvm::Constant *Init,
1888 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001889 unsigned Align,
1890 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001891 const llvm::Type *Ty = Init->getType();
1892 llvm::GlobalVariable *GV =
1893 new llvm::GlobalVariable(Ty, false,
1894 llvm::GlobalValue::InternalLinkage,
1895 Init,
1896 Name,
1897 &CGM.getModule());
1898 if (Section)
1899 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001900 if (Align)
1901 GV->setAlignment(Align);
1902 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001903 UsedGlobals.push_back(GV);
1904 return GV;
1905}
1906
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001907llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001908 // Abuse this interface function as a place to finalize.
1909 FinishModule();
1910
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001911 return NULL;
1912}
1913
Chris Lattner74391b42009-03-22 21:03:39 +00001914llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001915 return ObjCTypes.GetPropertyFn;
1916}
1917
Chris Lattner74391b42009-03-22 21:03:39 +00001918llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001919 return ObjCTypes.SetPropertyFn;
1920}
1921
Chris Lattner74391b42009-03-22 21:03:39 +00001922llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001923 return ObjCTypes.EnumerationMutationFn;
1924}
1925
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001926/*
1927
1928Objective-C setjmp-longjmp (sjlj) Exception Handling
1929--
1930
1931The basic framework for a @try-catch-finally is as follows:
1932{
1933 objc_exception_data d;
1934 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001935 bool _call_try_exit = true;
1936
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001937 objc_exception_try_enter(&d);
1938 if (!setjmp(d.jmp_buf)) {
1939 ... try body ...
1940 } else {
1941 // exception path
1942 id _caught = objc_exception_extract(&d);
1943
1944 // enter new try scope for handlers
1945 if (!setjmp(d.jmp_buf)) {
1946 ... match exception and execute catch blocks ...
1947
1948 // fell off end, rethrow.
1949 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001950 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001951 } else {
1952 // exception in catch block
1953 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001954 _call_try_exit = false;
1955 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001956 }
1957 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001958 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001959
1960finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001961 if (_call_try_exit)
1962 objc_exception_try_exit(&d);
1963
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001964 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001965 ... dispatch to finally destination ...
1966
1967finally_rethrow:
1968 objc_exception_throw(_rethrow);
1969
1970finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001971}
1972
1973This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001974uses _rethrow to determine if objc_exception_try_exit should be called
1975and if the object should be rethrown. This breaks in the face of
1976throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001977
1978We specialize this framework for a few particular circumstances:
1979
1980 - If there are no catch blocks, then we avoid emitting the second
1981 exception handling context.
1982
1983 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1984 e)) we avoid emitting the code to rethrow an uncaught exception.
1985
1986 - FIXME: If there is no @finally block we can do a few more
1987 simplifications.
1988
1989Rethrows and Jumps-Through-Finally
1990--
1991
1992Support for implicit rethrows and jumping through the finally block is
1993handled by storing the current exception-handling context in
1994ObjCEHStack.
1995
Daniel Dunbar898d5082008-09-30 01:06:03 +00001996In order to implement proper @finally semantics, we support one basic
1997mechanism for jumping through the finally block to an arbitrary
1998destination. Constructs which generate exits from a @try or @catch
1999block use this mechanism to implement the proper semantics by chaining
2000jumps, as necessary.
2001
2002This mechanism works like the one used for indirect goto: we
2003arbitrarily assign an ID to each destination and store the ID for the
2004destination in a variable prior to entering the finally block. At the
2005end of the finally block we simply create a switch to the proper
2006destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002007
2008Code gen for @synchronized(expr) stmt;
2009Effectively generating code for:
2010objc_sync_enter(expr);
2011@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002012*/
2013
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002014void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2015 const Stmt &S) {
2016 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002017 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002018 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002019 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002020 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2021 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2022 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002023
2024 // For @synchronized, call objc_sync_enter(sync.expr). The
2025 // evaluation of the expression must occur before we enter the
2026 // @synchronized. We can safely avoid a temp here because jumps into
2027 // @synchronized are illegal & this will dominate uses.
2028 llvm::Value *SyncArg = 0;
2029 if (!isTry) {
2030 SyncArg =
2031 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2032 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002033 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002034 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002035
2036 // Push an EH context entry, used for handling rethrows and jumps
2037 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002038 CGF.PushCleanupBlock(FinallyBlock);
2039
Anders Carlsson273558f2009-02-07 21:37:21 +00002040 CGF.ObjCEHValueStack.push_back(0);
2041
Daniel Dunbar898d5082008-09-30 01:06:03 +00002042 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002043 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2044 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002045 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2046 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002047 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2048 "_call_try_exit");
2049 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2050
Anders Carlsson80f25672008-09-09 17:59:25 +00002051 // Enter a new try block and call setjmp.
2052 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2053 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2054 "jmpbufarray");
2055 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2056 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2057 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002058
Daniel Dunbar55e87422008-11-11 02:29:29 +00002059 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2060 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002061 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002062 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002063
2064 // Emit the @try block.
2065 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002066 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2067 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002068 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002069
2070 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002071 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002072
2073 // Retrieve the exception object. We may emit multiple blocks but
2074 // nothing can cross this so the value is already in SSA form.
2075 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2076 ExceptionData,
2077 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002078 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002079 if (!isTry)
2080 {
2081 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002082 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002083 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002084 }
2085 else if (const ObjCAtCatchStmt* CatchStmt =
2086 cast<ObjCAtTryStmt>(S).getCatchStmts())
2087 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002088 // Enter a new exception try block (in case a @catch block throws
2089 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002090 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002091
Anders Carlsson80f25672008-09-09 17:59:25 +00002092 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2093 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002094 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002095
Daniel Dunbar55e87422008-11-11 02:29:29 +00002096 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2097 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002098 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002099
2100 CGF.EmitBlock(CatchBlock);
2101
Daniel Dunbar55e40722008-09-27 07:03:52 +00002102 // Handle catch list. As a special case we check if everything is
2103 // matched and avoid generating code for falling off the end if
2104 // so.
2105 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002106 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002107 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002108
Steve Naroff7ba138a2009-03-03 19:52:17 +00002109 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002110 const PointerType *PT = 0;
2111
Anders Carlsson80f25672008-09-09 17:59:25 +00002112 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002113 if (!CatchParam) {
2114 AllMatched = true;
2115 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002116 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002117
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002118 // catch(id e) always matches.
2119 // FIXME: For the time being we also match id<X>; this should
2120 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002121 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002122 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002123 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002124 }
2125
Daniel Dunbar55e40722008-09-27 07:03:52 +00002126 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002127 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002128 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002129 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002130 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002131 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002132
Anders Carlssondde0a942008-09-11 09:15:33 +00002133 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002134 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002135 break;
2136 }
2137
Daniel Dunbar129271a2008-09-27 07:36:24 +00002138 assert(PT && "Unexpected non-pointer type in @catch");
2139 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002140 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002141 assert(ObjCType && "Catch parameter must have Objective-C type!");
2142
2143 // Check if the @catch block matches the exception object.
2144 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2145
Anders Carlsson80f25672008-09-09 17:59:25 +00002146 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2147 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002148
Daniel Dunbar55e87422008-11-11 02:29:29 +00002149 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002150
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002151 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002152 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002153
2154 // Emit the @catch block.
2155 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002156 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002157 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002158
2159 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002160 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002161 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002162 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002163
2164 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002165 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002166
2167 CGF.EmitBlock(NextCatchBlock);
2168 }
2169
Daniel Dunbar55e40722008-09-27 07:03:52 +00002170 if (!AllMatched) {
2171 // None of the handlers caught the exception, so store it to be
2172 // rethrown at the end of the @finally block.
2173 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002174 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002175 }
2176
2177 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002178 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002179 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2180 ExceptionData),
2181 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002182 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002183 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002184 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002185 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002186 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002187 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002188 }
2189
Daniel Dunbar898d5082008-09-30 01:06:03 +00002190 // Pop the exception-handling stack entry. It is important to do
2191 // this now, because the code in the @finally block is not in this
2192 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002193 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2194
Anders Carlsson273558f2009-02-07 21:37:21 +00002195 CGF.ObjCEHValueStack.pop_back();
2196
Anders Carlsson80f25672008-09-09 17:59:25 +00002197 // Emit the @finally block.
2198 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002199 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2200
2201 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2202
2203 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002204 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002205
2206 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002207 if (isTry) {
2208 if (const ObjCAtFinallyStmt* FinallyStmt =
2209 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2210 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002211 } else {
2212 // Emit objc_sync_exit(expr); as finally's sole statement for
2213 // @synchronized.
2214 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002215 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002216
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002217 // Emit the switch block
2218 if (Info.SwitchBlock)
2219 CGF.EmitBlock(Info.SwitchBlock);
2220 if (Info.EndBlock)
2221 CGF.EmitBlock(Info.EndBlock);
2222
Daniel Dunbar898d5082008-09-30 01:06:03 +00002223 CGF.EmitBlock(FinallyRethrow);
2224 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2225 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002226 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002227
2228 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002229}
2230
2231void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002232 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002233 llvm::Value *ExceptionAsObject;
2234
2235 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2236 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2237 ExceptionAsObject =
2238 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2239 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002240 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002241 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002242 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002243 }
2244
2245 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002246 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002247
2248 // Clear the insertion point to indicate we are in unreachable code.
2249 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002250}
2251
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002252/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002253/// object: objc_read_weak (id *src)
2254///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002255llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002256 llvm::Value *AddrWeakObj)
2257{
Eli Friedman8339b352009-03-07 03:57:15 +00002258 const llvm::Type* DestTy =
2259 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002260 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002261 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002262 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002263 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002264 return read_weak;
2265}
2266
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002267/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2268/// objc_assign_weak (id src, id *dst)
2269///
2270void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2271 llvm::Value *src, llvm::Value *dst)
2272{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002273 const llvm::Type * SrcTy = src->getType();
2274 if (!isa<llvm::PointerType>(SrcTy)) {
2275 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2276 assert(Size <= 8 && "does not support size > 8");
2277 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2278 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002279 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2280 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002281 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2282 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002283 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2284 src, dst, "weakassign");
2285 return;
2286}
2287
Fariborz Jahanian58626502008-11-19 00:59:10 +00002288/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2289/// objc_assign_global (id src, id *dst)
2290///
2291void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2292 llvm::Value *src, llvm::Value *dst)
2293{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002294 const llvm::Type * SrcTy = src->getType();
2295 if (!isa<llvm::PointerType>(SrcTy)) {
2296 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2297 assert(Size <= 8 && "does not support size > 8");
2298 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2299 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002300 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2301 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002302 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2303 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002304 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2305 src, dst, "globalassign");
2306 return;
2307}
2308
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002309/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2310/// objc_assign_ivar (id src, id *dst)
2311///
2312void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2313 llvm::Value *src, llvm::Value *dst)
2314{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002315 const llvm::Type * SrcTy = src->getType();
2316 if (!isa<llvm::PointerType>(SrcTy)) {
2317 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2318 assert(Size <= 8 && "does not support size > 8");
2319 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2320 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002321 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2322 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002323 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2324 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2325 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2326 src, dst, "assignivar");
2327 return;
2328}
2329
Fariborz Jahanian58626502008-11-19 00:59:10 +00002330/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2331/// objc_assign_strongCast (id src, id *dst)
2332///
2333void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2334 llvm::Value *src, llvm::Value *dst)
2335{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002336 const llvm::Type * SrcTy = src->getType();
2337 if (!isa<llvm::PointerType>(SrcTy)) {
2338 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2339 assert(Size <= 8 && "does not support size > 8");
2340 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2341 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002342 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2343 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002344 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2345 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002346 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2347 src, dst, "weakassign");
2348 return;
2349}
2350
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002351/// EmitObjCValueForIvar - Code Gen for ivar reference.
2352///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002353LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2354 QualType ObjectTy,
2355 llvm::Value *BaseValue,
2356 const ObjCIvarDecl *Ivar,
2357 const FieldDecl *Field,
2358 unsigned CVRQualifiers) {
2359 if (Ivar->isBitField())
2360 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2361 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002362 // TODO: Add a special case for isa (index 0)
2363 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2364 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002365 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002366 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2367 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002368 LValue::SetObjCIvar(LV, true);
2369 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002370}
2371
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002372llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2373 ObjCInterfaceDecl *Interface,
2374 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002375 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002376 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002377 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002378 return llvm::ConstantInt::get(
2379 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2380 Offset);
2381}
2382
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002383/* *** Private Interface *** */
2384
2385/// EmitImageInfo - Emit the image info marker used to encode some module
2386/// level information.
2387///
2388/// See: <rdr://4810609&4810587&4810587>
2389/// struct IMAGE_INFO {
2390/// unsigned version;
2391/// unsigned flags;
2392/// };
2393enum ImageInfoFlags {
2394 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2395 eImageInfo_GarbageCollected = (1 << 1),
2396 eImageInfo_GCOnly = (1 << 2)
2397};
2398
2399void CGObjCMac::EmitImageInfo() {
2400 unsigned version = 0; // Version is unused?
2401 unsigned flags = 0;
2402
2403 // FIXME: Fix and continue?
2404 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2405 flags |= eImageInfo_GarbageCollected;
2406 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2407 flags |= eImageInfo_GCOnly;
2408
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002409 // Emitted as int[2];
2410 llvm::Constant *values[2] = {
2411 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2412 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2413 };
2414 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002415
2416 const char *Section;
2417 if (ObjCABI == 1)
2418 Section = "__OBJC, __image_info,regular";
2419 else
2420 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002421 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002422 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2423 llvm::ConstantArray::get(AT, values, 2),
2424 Section,
2425 0,
2426 true);
2427 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002428}
2429
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002430
2431// struct objc_module {
2432// unsigned long version;
2433// unsigned long size;
2434// const char *name;
2435// Symtab symtab;
2436// };
2437
2438// FIXME: Get from somewhere
2439static const int ModuleVersion = 7;
2440
2441void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002442 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002443
2444 std::vector<llvm::Constant*> Values(4);
2445 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2446 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002447 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002448 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002449 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002450 CreateMetadataVar("\01L_OBJC_MODULES",
2451 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2452 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002453 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002454}
2455
2456llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002457 unsigned NumClasses = DefinedClasses.size();
2458 unsigned NumCategories = DefinedCategories.size();
2459
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002460 // Return null if no symbols were defined.
2461 if (!NumClasses && !NumCategories)
2462 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2463
2464 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002465 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2466 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2467 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2468 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2469
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002470 // The runtime expects exactly the list of defined classes followed
2471 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002472 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002473 for (unsigned i=0; i<NumClasses; i++)
2474 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2475 ObjCTypes.Int8PtrTy);
2476 for (unsigned i=0; i<NumCategories; i++)
2477 Symbols[NumClasses + i] =
2478 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2479 ObjCTypes.Int8PtrTy);
2480
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002481 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002482 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002483 NumClasses + NumCategories),
2484 Symbols);
2485
2486 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2487
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002488 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002489 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2490 "__OBJC,__symbols,regular,no_dead_strip",
2491 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002492 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2493}
2494
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002495llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002496 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002497 LazySymbols.insert(ID->getIdentifier());
2498
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002499 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2500
2501 if (!Entry) {
2502 llvm::Constant *Casted =
2503 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2504 ObjCTypes.ClassPtrTy);
2505 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002506 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2507 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2508 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002509 }
2510
2511 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002512}
2513
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002514llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002515 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2516
2517 if (!Entry) {
2518 llvm::Constant *Casted =
2519 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2520 ObjCTypes.SelectorPtrTy);
2521 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002522 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2523 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2524 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002525 }
2526
2527 return Builder.CreateLoad(Entry, false, "tmp");
2528}
2529
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002530llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002531 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002532
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002533 if (!Entry)
2534 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2535 llvm::ConstantArray::get(Ident->getName()),
2536 "__TEXT,__cstring,cstring_literals",
2537 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002538
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002539 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002540}
2541
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002542/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2543/// interface declaration.
2544const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2545 const ObjCInterfaceDecl *OID) const {
2546 const llvm::Type *InterfaceTy =
2547 CGM.getTypes().ConvertType(
2548 CGM.getContext().getObjCInterfaceType(
2549 const_cast<ObjCInterfaceDecl*>(OID)));
2550 const llvm::StructLayout *Layout =
2551 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2552 return Layout;
2553}
2554
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002555/// GetIvarLayoutName - Returns a unique constant for the given
2556/// ivar layout bitmap.
2557llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2558 const ObjCCommonTypesHelper &ObjCTypes) {
2559 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2560}
2561
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002562void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2563 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002564 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002565 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002566 unsigned int BytePos, bool ForStrongLayout,
2567 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002568 bool IsUnion = (RD && RD->isUnion());
2569 uint64_t MaxUnionIvarSize = 0;
2570 uint64_t MaxSkippedUnionIvarSize = 0;
2571 FieldDecl *MaxField = 0;
2572 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002573 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002574 if (RecFields.empty())
2575 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002576 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002577 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002578 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2579 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2580
2581 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2582
2583 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002584 FieldDecl *Field = RecFields[i];
2585 // Skip over unnamed or bitfields
2586 if (!Field->getIdentifier() || Field->isBitField())
2587 continue;
2588 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002589 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002590 if (FQT->isUnionType())
2591 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002592 else
2593 assert(FQT->isRecordType() &&
2594 "only union/record is supported for ivar layout bitmap");
2595
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002596 const RecordType *RT = FQT->getAsRecordType();
2597 const RecordDecl *RD = RT->getDecl();
2598 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002599 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2600 RD->field_end(CGM.getContext()));
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002601 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002602 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002603 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002604 ForStrongLayout, Index, SkIndex,
2605 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002606 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002607 continue;
2608 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002609
2610 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002611 const ConstantArrayType *CArray =
2612 dyn_cast_or_null<ConstantArrayType>(Array);
2613 assert(CArray && "only array with know element size is supported");
2614 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002615 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2616 const ConstantArrayType *CArray =
2617 dyn_cast_or_null<ConstantArrayType>(Array);
2618 FQT = CArray->getElementType();
2619 }
2620
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002621 assert(!FQT->isUnionType() &&
2622 "layout for array of unions not supported");
2623 if (FQT->isRecordType()) {
2624 uint64_t ElCount = CArray->getSize().getZExtValue();
2625 int OldIndex = Index;
2626 int OldSkIndex = SkIndex;
2627
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002628 // FIXME - Use a common routine with the above!
2629 const RecordType *RT = FQT->getAsRecordType();
2630 const RecordDecl *RD = RT->getDecl();
2631 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002632 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2633 RD->field_end(CGM.getContext()));
Chris Lattnerf1690852009-03-31 08:48:01 +00002634
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002635 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002636 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002637 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002638 ForStrongLayout, Index, SkIndex,
2639 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002640 TmpRecFields.clear();
2641
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002642 // Replicate layout information for each array element. Note that
2643 // one element is already done.
2644 uint64_t ElIx = 1;
2645 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2646 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002647 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002648 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2649 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002650 GC_IVAR gcivar;
2651 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2652 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2653 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002654 }
2655
Chris Lattnerf1690852009-03-31 08:48:01 +00002656 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002657 GC_IVAR skivar;
2658 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2659 skivar.ivar_size = SkipIvars[i].ivar_size;
2660 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002661 }
2662 }
2663 continue;
2664 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002665 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002666 // At this point, we are done with Record/Union and array there of.
2667 // For other arrays we are down to its element type.
2668 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2669 do {
2670 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2671 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2672 break;
2673 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002674 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002675 GCAttr = QualType::Strong;
2676 break;
2677 }
2678 else if (const PointerType *PT = FQT->getAsPointerType()) {
2679 FQT = PT->getPointeeType();
2680 }
2681 else {
2682 break;
2683 }
2684 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002685
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002686 if ((ForStrongLayout && GCAttr == QualType::Strong)
2687 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2688 if (IsUnion)
2689 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002690 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2691 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002692 if (UnionIvarSize > MaxUnionIvarSize)
2693 {
2694 MaxUnionIvarSize = UnionIvarSize;
2695 MaxField = Field;
2696 }
2697 }
2698 else
2699 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002700 GC_IVAR gcivar;
2701 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2702 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2703 WordSizeInBits;
2704 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002705 }
2706 }
2707 else if ((ForStrongLayout &&
2708 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2709 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2710 if (IsUnion)
2711 {
2712 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2713 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2714 {
2715 MaxSkippedUnionIvarSize = UnionIvarSize;
2716 MaxSkippedField = Field;
2717 }
2718 }
2719 else
2720 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002721 GC_IVAR skivar;
2722 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2723 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2724 WordSizeInBits;
2725 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002726 }
2727 }
2728 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002729 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002730 GC_IVAR gcivar;
2731 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2732 gcivar.ivar_size = MaxUnionIvarSize;
2733 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002734 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002735
2736 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002737 GC_IVAR skivar;
2738 skivar.ivar_bytepos = BytePos +
2739 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2740 skivar.ivar_size = MaxSkippedUnionIvarSize;
2741 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002742 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002743}
2744
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002745static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002746IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002747{
2748 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2749 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2750
2751 if (sa < sb)
2752 return -1;
2753 if (sa > sb)
2754 return 1;
2755 return 0;
2756}
2757
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002758/// BuildIvarLayout - Builds ivar layout bitmap for the class
2759/// implementation for the __strong or __weak case.
2760/// The layout map displays which words in ivar list must be skipped
2761/// and which must be scanned by GC (see below). String is built of bytes.
2762/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2763/// of words to skip and right nibble is count of words to scan. So, each
2764/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2765/// represented by a 0x00 byte which also ends the string.
2766/// 1. when ForStrongLayout is true, following ivars are scanned:
2767/// - id, Class
2768/// - object *
2769/// - __strong anything
2770///
2771/// 2. When ForStrongLayout is false, following ivars are scanned:
2772/// - __weak anything
2773///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002774llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002775 const ObjCImplementationDecl *OMD,
2776 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002777 int Index = -1;
2778 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002779 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002780 int SkipScan;
2781 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002782 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2783 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2784 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002785
Chris Lattnerf1690852009-03-31 08:48:01 +00002786 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002787 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002788 CGM.getContext().CollectObjCIvars(OI, RecFields);
2789 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002790 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002791
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002792 SkipIvars.clear();
2793 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002794
2795 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002796 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2797 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002798 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002799 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002800
2801 // Sort on byte position in case we encounterred a union nested in
2802 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002803 if (hasUnion && !IvarsInfo.empty())
2804 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2805 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002806 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2807
2808 // Build the string of skip/scan nibbles
2809 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002810 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002811 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002813 if (IvarsInfo[0].ivar_bytepos == 0) {
2814 WordsToSkip = 0;
2815 WordsToScan = IvarsInfo[0].ivar_size;
2816 }
2817 else {
2818 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2819 WordsToScan = IvarsInfo[0].ivar_size;
2820 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002821 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002822 {
2823 unsigned int TailPrevGCObjC =
2824 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2825 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2826 {
2827 // consecutive 'scanned' object pointers.
2828 WordsToScan += IvarsInfo[i].ivar_size;
2829 }
2830 else
2831 {
2832 // Skip over 'gc'able object pointer which lay over each other.
2833 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2834 continue;
2835 // Must skip over 1 or more words. We save current skip/scan values
2836 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002837 SKIP_SCAN SkScan;
2838 SkScan.skip = WordsToSkip;
2839 SkScan.scan = WordsToScan;
2840 SkipScanIvars.push_back(SkScan); ++SkipScan;
2841
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002842 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002843 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2844 SkScan.scan = 0;
2845 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002846 WordsToSkip = 0;
2847 WordsToScan = IvarsInfo[i].ivar_size;
2848 }
2849 }
2850 if (WordsToScan > 0)
2851 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002852 SKIP_SCAN SkScan;
2853 SkScan.skip = WordsToSkip;
2854 SkScan.scan = WordsToScan;
2855 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002856 }
2857
2858 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002859 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002860 {
2861 int LastByteSkipped =
2862 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2863 int LastByteScanned =
2864 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2865 BytesSkipped = (LastByteSkipped > LastByteScanned);
2866 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2867 if (BytesSkipped)
2868 {
2869 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002870 SKIP_SCAN SkScan;
2871 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2872 SkScan.scan = 0;
2873 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002874 }
2875 }
2876 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2877 // as 0xMN.
2878 for (int i = 0; i <= SkipScan; i++)
2879 {
2880 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2881 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2882 // 0xM0 followed by 0x0N detected.
2883 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2884 for (int j = i+1; j < SkipScan; j++)
2885 SkipScanIvars[j] = SkipScanIvars[j+1];
2886 --SkipScan;
2887 }
2888 }
2889
2890 // Generate the string.
2891 std::string BitMap;
2892 for (int i = 0; i <= SkipScan; i++)
2893 {
2894 unsigned char byte;
2895 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2896 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2897 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2898 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2899
2900 if (skip_small > 0 || skip_big > 0)
2901 BytesSkipped = true;
2902 // first skip big.
2903 for (unsigned int ix = 0; ix < skip_big; ix++)
2904 BitMap += (unsigned char)(0xf0);
2905
2906 // next (skip small, scan)
2907 if (skip_small)
2908 {
2909 byte = skip_small << 4;
2910 if (scan_big > 0)
2911 {
2912 byte |= 0xf;
2913 --scan_big;
2914 }
2915 else if (scan_small)
2916 {
2917 byte |= scan_small;
2918 scan_small = 0;
2919 }
2920 BitMap += byte;
2921 }
2922 // next scan big
2923 for (unsigned int ix = 0; ix < scan_big; ix++)
2924 BitMap += (unsigned char)(0x0f);
2925 // last scan small
2926 if (scan_small)
2927 {
2928 byte = scan_small;
2929 BitMap += byte;
2930 }
2931 }
2932 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002933 unsigned char zero = 0;
2934 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002935 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2936 // final layout.
2937 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002938 return llvm::Constant::getNullValue(PtrTy);
2939 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2940 llvm::ConstantArray::get(BitMap.c_str()),
2941 "__TEXT,__cstring,cstring_literals",
2942 0, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002943 // FIXME. Need a commomand-line option for this eventually.
2944 if (ForStrongLayout)
2945 printf("\nstrong ivar layout: ");
2946 else
2947 printf("\nweak ivar layout: ");
2948 const unsigned char *s = (unsigned char*)BitMap.c_str();
2949 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002950 if (!(s[i] & 0xf0))
2951 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2952 else
2953 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002954 printf("\n");
2955
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002956 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002957}
2958
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002959llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002960 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2961
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002962 // FIXME: Avoid std::string copying.
2963 if (!Entry)
2964 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2965 llvm::ConstantArray::get(Sel.getAsString()),
2966 "__TEXT,__cstring,cstring_literals",
2967 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002968
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002969 return getConstantGEP(Entry, 0, 0);
2970}
2971
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002972// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002973llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002974 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2975}
2976
2977// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002978llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002979 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2980}
2981
Devang Patel7794bb82009-03-04 18:21:39 +00002982llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2983 std::string TypeStr;
2984 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2985
2986 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002987
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002988 if (!Entry)
2989 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2990 llvm::ConstantArray::get(TypeStr),
2991 "__TEXT,__cstring,cstring_literals",
2992 0, true);
2993
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002994 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002995}
2996
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002997llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002998 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002999 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3000 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003001
3002 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3003
3004 if (!Entry) {
3005 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
3006 Entry =
3007 new llvm::GlobalVariable(C->getType(), false,
3008 llvm::GlobalValue::InternalLinkage,
3009 C, "\01L_OBJC_METH_VAR_TYPE_",
3010 &CGM.getModule());
3011 Entry->setSection("__TEXT,__cstring,cstring_literals");
3012 UsedGlobals.push_back(Entry);
3013 }
3014
3015 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003016}
3017
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003018// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003019llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003020 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3021
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003022 if (!Entry)
3023 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3024 llvm::ConstantArray::get(Ident->getName()),
3025 "__TEXT,__cstring,cstring_literals",
3026 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003027
3028 return getConstantGEP(Entry, 0, 0);
3029}
3030
3031// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003032// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003033llvm::Constant *
3034 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3035 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003036 std::string TypeStr;
3037 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003038 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3039}
3040
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003041void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3042 const ObjCContainerDecl *CD,
3043 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003044 NameOut = '\01';
3045 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003046 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003047 assert (CD && "Missing container decl in GetNameForMethod");
3048 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00003049 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
3050 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00003051 NameOut += ' ';
3052 NameOut += D->getSelector().getAsString();
3053 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003054}
3055
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003056/// GetFirstIvarInRecord - This routine returns the record for the
3057/// implementation of the fiven class OID. It also returns field
3058/// corresponding to the first ivar in the class in FIV. It also
3059/// returns the one before the first ivar.
3060///
3061const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3062 const ObjCInterfaceDecl *OID,
3063 RecordDecl::field_iterator &FIV,
3064 RecordDecl::field_iterator &PIV) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00003065 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
3066 CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003067 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Douglas Gregor6ab35242009-04-09 21:40:53 +00003068 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext());
3069 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003070 while (countSuperClassIvars-- > 0) {
3071 pfield = ifield;
3072 ++ifield;
3073 }
3074 FIV = ifield;
3075 PIV = pfield;
3076 return RD;
3077}
3078
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003079void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003080 EmitModuleInfo();
3081
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003082 // Emit the dummy bodies for any protocols which were referenced but
3083 // never defined.
3084 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3085 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3086 if (i->second->hasInitializer())
3087 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003088
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003089 std::vector<llvm::Constant*> Values(5);
3090 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3091 Values[1] = GetClassName(i->first);
3092 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3093 Values[3] = Values[4] =
3094 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3095 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3096 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3097 Values));
3098 }
3099
3100 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003101 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003102 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003103 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003104 }
3105
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003106 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003107 llvm::GlobalValue *GV =
3108 new llvm::GlobalVariable(AT, false,
3109 llvm::GlobalValue::AppendingLinkage,
3110 llvm::ConstantArray::get(AT, Used),
3111 "llvm.used",
3112 &CGM.getModule());
3113
3114 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003115
3116 // Add assembler directives to add lazy undefined symbol references
3117 // for classes which are referenced but not defined. This is
3118 // important for correct linker interaction.
3119
3120 // FIXME: Uh, this isn't particularly portable.
3121 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003122
3123 if (!CGM.getModule().getModuleInlineAsm().empty())
3124 s << "\n";
3125
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003126 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3127 e = LazySymbols.end(); i != e; ++i) {
3128 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3129 }
3130 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3131 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003132 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003133 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3134 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003135
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003136 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003137}
3138
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003139CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003140 : CGObjCCommonMac(cgm),
3141 ObjCTypes(cgm)
3142{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003143 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003144 ObjCABI = 2;
3145}
3146
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003147/* *** */
3148
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003149ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3150: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003151{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003152 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3153 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003154
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003155 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003156 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003157 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003158 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003159 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3160
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003161 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003162 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003163 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003164
3165 // FIXME: It would be nice to unify this with the opaque type, so
3166 // that the IR comes out a bit cleaner.
3167 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3168 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003169
3170 // I'm not sure I like this. The implicit coordination is a bit
3171 // gross. We should solve this in a reasonable fashion because this
3172 // is a pretty common task (match some runtime data structure with
3173 // an LLVM data structure).
3174
3175 // FIXME: This is leaked.
3176 // FIXME: Merge with rewriter code?
3177
3178 // struct _objc_super {
3179 // id self;
3180 // Class cls;
3181 // }
3182 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3183 SourceLocation(),
3184 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003185 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3186 Ctx.getObjCIdType(), 0, false));
3187 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3188 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003189 RD->completeDefinition(Ctx);
3190
3191 SuperCTy = Ctx.getTagDeclType(RD);
3192 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3193
3194 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003195 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3196
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003197 // struct _prop_t {
3198 // char *name;
3199 // char *attributes;
3200 // }
3201 PropertyTy = llvm::StructType::get(Int8PtrTy,
3202 Int8PtrTy,
3203 NULL);
3204 CGM.getModule().addTypeName("struct._prop_t",
3205 PropertyTy);
3206
3207 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003208 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003209 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003210 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003211 // }
3212 PropertyListTy = llvm::StructType::get(IntTy,
3213 IntTy,
3214 llvm::ArrayType::get(PropertyTy, 0),
3215 NULL);
3216 CGM.getModule().addTypeName("struct._prop_list_t",
3217 PropertyListTy);
3218 // struct _prop_list_t *
3219 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3220
3221 // struct _objc_method {
3222 // SEL _cmd;
3223 // char *method_type;
3224 // char *_imp;
3225 // }
3226 MethodTy = llvm::StructType::get(SelectorPtrTy,
3227 Int8PtrTy,
3228 Int8PtrTy,
3229 NULL);
3230 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003231
3232 // struct _objc_cache *
3233 CacheTy = llvm::OpaqueType::get();
3234 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3235 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003236
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003237 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003238
3239 QualType IdType = Ctx.getObjCIdType();
3240 QualType SelType = Ctx.getObjCSelType();
3241 llvm::SmallVector<QualType,16> Params;
3242 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003243
3244 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003245 Params.push_back(IdType);
3246 Params.push_back(SelType);
3247 Params.push_back(Ctx.LongTy);
3248 Params.push_back(Ctx.BoolTy);
3249 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3250 false);
3251 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003252
3253 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3254 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003255 Params.push_back(IdType);
3256 Params.push_back(SelType);
3257 Params.push_back(Ctx.LongTy);
3258 Params.push_back(IdType);
3259 Params.push_back(Ctx.BoolTy);
3260 Params.push_back(Ctx.BoolTy);
3261 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3262 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3263
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003264 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003265
3266 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003267 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003268 Params.push_back(IdType);
3269 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3270 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3271 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003272
3273 // gc's API
3274 // id objc_read_weak (id *)
3275 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003276 Params.push_back(Ctx.getPointerType(IdType));
3277 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3278 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3279
3280 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003281 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003282 Params.push_back(IdType);
3283 Params.push_back(Ctx.getPointerType(IdType));
3284
3285 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3286 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3287 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3288 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3289 GcAssignStrongCastFn =
3290 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003291
3292 // void objc_exception_throw(id)
3293 Params.clear();
3294 Params.push_back(IdType);
3295
3296 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003297 ExceptionThrowFn =
3298 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003299
3300 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003301 // void objc_sync_exit (id)
3302 Params.clear();
3303 Params.push_back(IdType);
3304
3305 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003306 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003307}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003308
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003309ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3310 : ObjCCommonTypesHelper(cgm)
3311{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003312 // struct _objc_method_description {
3313 // SEL name;
3314 // char *types;
3315 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003316 MethodDescriptionTy =
3317 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003318 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003319 NULL);
3320 CGM.getModule().addTypeName("struct._objc_method_description",
3321 MethodDescriptionTy);
3322
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003323 // struct _objc_method_description_list {
3324 // int count;
3325 // struct _objc_method_description[1];
3326 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003327 MethodDescriptionListTy =
3328 llvm::StructType::get(IntTy,
3329 llvm::ArrayType::get(MethodDescriptionTy, 0),
3330 NULL);
3331 CGM.getModule().addTypeName("struct._objc_method_description_list",
3332 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003333
3334 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003335 MethodDescriptionListPtrTy =
3336 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3337
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003338 // Protocol description structures
3339
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003340 // struct _objc_protocol_extension {
3341 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3342 // struct _objc_method_description_list *optional_instance_methods;
3343 // struct _objc_method_description_list *optional_class_methods;
3344 // struct _objc_property_list *instance_properties;
3345 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003346 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003347 llvm::StructType::get(IntTy,
3348 MethodDescriptionListPtrTy,
3349 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003350 PropertyListPtrTy,
3351 NULL);
3352 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3353 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003354
3355 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003356 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3357
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003358 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003359
3360 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3361 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3362
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003363 const llvm::Type *T =
3364 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3365 LongTy,
3366 llvm::ArrayType::get(ProtocolTyHolder, 0),
3367 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003368 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3369
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003370 // struct _objc_protocol {
3371 // struct _objc_protocol_extension *isa;
3372 // char *protocol_name;
3373 // struct _objc_protocol **_objc_protocol_list;
3374 // struct _objc_method_description_list *instance_methods;
3375 // struct _objc_method_description_list *class_methods;
3376 // }
3377 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003378 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003379 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3380 MethodDescriptionListPtrTy,
3381 MethodDescriptionListPtrTy,
3382 NULL);
3383 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3384
3385 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3386 CGM.getModule().addTypeName("struct._objc_protocol_list",
3387 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003388 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003389 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3390
3391 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003392 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003393 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003394
3395 // Class description structures
3396
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003397 // struct _objc_ivar {
3398 // char *ivar_name;
3399 // char *ivar_type;
3400 // int ivar_offset;
3401 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003402 IvarTy = llvm::StructType::get(Int8PtrTy,
3403 Int8PtrTy,
3404 IntTy,
3405 NULL);
3406 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3407
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003408 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003409 IvarListTy = llvm::OpaqueType::get();
3410 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3411 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3412
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003413 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003414 MethodListTy = llvm::OpaqueType::get();
3415 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3416 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3417
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003418 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003419 ClassExtensionTy =
3420 llvm::StructType::get(IntTy,
3421 Int8PtrTy,
3422 PropertyListPtrTy,
3423 NULL);
3424 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3425 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3426
3427 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3428
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003429 // struct _objc_class {
3430 // Class isa;
3431 // Class super_class;
3432 // char *name;
3433 // long version;
3434 // long info;
3435 // long instance_size;
3436 // struct _objc_ivar_list *ivars;
3437 // struct _objc_method_list *methods;
3438 // struct _objc_cache *cache;
3439 // struct _objc_protocol_list *protocols;
3440 // char *ivar_layout;
3441 // struct _objc_class_ext *ext;
3442 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003443 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3444 llvm::PointerType::getUnqual(ClassTyHolder),
3445 Int8PtrTy,
3446 LongTy,
3447 LongTy,
3448 LongTy,
3449 IvarListPtrTy,
3450 MethodListPtrTy,
3451 CachePtrTy,
3452 ProtocolListPtrTy,
3453 Int8PtrTy,
3454 ClassExtensionPtrTy,
3455 NULL);
3456 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3457
3458 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3459 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3460 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3461
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003462 // struct _objc_category {
3463 // char *category_name;
3464 // char *class_name;
3465 // struct _objc_method_list *instance_method;
3466 // struct _objc_method_list *class_method;
3467 // uint32_t size; // sizeof(struct _objc_category)
3468 // struct _objc_property_list *instance_properties;// category's @property
3469 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003470 CategoryTy = llvm::StructType::get(Int8PtrTy,
3471 Int8PtrTy,
3472 MethodListPtrTy,
3473 MethodListPtrTy,
3474 ProtocolListPtrTy,
3475 IntTy,
3476 PropertyListPtrTy,
3477 NULL);
3478 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3479
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003480 // Global metadata structures
3481
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003482 // struct _objc_symtab {
3483 // long sel_ref_cnt;
3484 // SEL *refs;
3485 // short cls_def_cnt;
3486 // short cat_def_cnt;
3487 // char *defs[cls_def_cnt + cat_def_cnt];
3488 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003489 SymtabTy = llvm::StructType::get(LongTy,
3490 SelectorPtrTy,
3491 ShortTy,
3492 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003493 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003494 NULL);
3495 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3496 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3497
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003498 // struct _objc_module {
3499 // long version;
3500 // long size; // sizeof(struct _objc_module)
3501 // char *name;
3502 // struct _objc_symtab* symtab;
3503 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003504 ModuleTy =
3505 llvm::StructType::get(LongTy,
3506 LongTy,
3507 Int8PtrTy,
3508 SymtabPtrTy,
3509 NULL);
3510 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003511
Daniel Dunbar49f66022008-09-24 03:38:44 +00003512 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003513
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003514 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003515 std::vector<const llvm::Type*> Params;
3516 Params.push_back(ObjectPtrTy);
3517 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003518 MessageSendFn =
3519 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3520 Params,
3521 true),
3522 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003523
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003524 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003525 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003526 Params.push_back(ObjectPtrTy);
3527 Params.push_back(SelectorPtrTy);
3528 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003529 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3530 Params,
3531 true),
3532 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003533
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003534 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003535 Params.clear();
3536 Params.push_back(ObjectPtrTy);
3537 Params.push_back(SelectorPtrTy);
3538 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003539 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003540 MessageSendFpretFn =
3541 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3542 Params,
3543 true),
3544 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003545
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003546 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003547 Params.clear();
3548 Params.push_back(SuperPtrTy);
3549 Params.push_back(SelectorPtrTy);
3550 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003551 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3552 Params,
3553 true),
3554 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003555
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003556 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3557 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003558 Params.clear();
3559 Params.push_back(Int8PtrTy);
3560 Params.push_back(SuperPtrTy);
3561 Params.push_back(SelectorPtrTy);
3562 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003563 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3564 Params,
3565 true),
3566 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003567
3568 // There is no objc_msgSendSuper_fpret? How can that work?
3569 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003570
Anders Carlsson124526b2008-09-09 10:10:21 +00003571 // FIXME: This is the size of the setjmp buffer and should be
3572 // target specific. 18 is what's used on 32-bit X86.
3573 uint64_t SetJmpBufferSize = 18;
3574
3575 // Exceptions
3576 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003577 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003578
3579 ExceptionDataTy =
3580 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3581 SetJmpBufferSize),
3582 StackPtrTy, NULL);
3583 CGM.getModule().addTypeName("struct._objc_exception_data",
3584 ExceptionDataTy);
3585
3586 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003587 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3588 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003589 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3590 Params,
3591 false),
3592 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003593 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003594 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3595 Params,
3596 false),
3597 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003598 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003599 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3600 Params,
3601 false),
3602 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003603
3604 Params.clear();
3605 Params.push_back(ClassPtrTy);
3606 Params.push_back(ObjectPtrTy);
3607 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003608 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3609 Params,
3610 false),
3611 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003612
Anders Carlsson124526b2008-09-09 10:10:21 +00003613 Params.clear();
3614 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3615 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003616 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3617 Params,
3618 false),
3619 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003620
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003621}
3622
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003623ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003624: ObjCCommonTypesHelper(cgm)
3625{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003626 // struct _method_list_t {
3627 // uint32_t entsize; // sizeof(struct _objc_method)
3628 // uint32_t method_count;
3629 // struct _objc_method method_list[method_count];
3630 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003631 MethodListnfABITy = llvm::StructType::get(IntTy,
3632 IntTy,
3633 llvm::ArrayType::get(MethodTy, 0),
3634 NULL);
3635 CGM.getModule().addTypeName("struct.__method_list_t",
3636 MethodListnfABITy);
3637 // struct method_list_t *
3638 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003639
3640 // struct _protocol_t {
3641 // id isa; // NULL
3642 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003643 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003644 // const struct method_list_t * const instance_methods;
3645 // const struct method_list_t * const class_methods;
3646 // const struct method_list_t *optionalInstanceMethods;
3647 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003648 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003649 // const uint32_t size; // sizeof(struct _protocol_t)
3650 // const uint32_t flags; // = 0
3651 // }
3652
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003653 // Holder for struct _protocol_list_t *
3654 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3655
3656 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3657 Int8PtrTy,
3658 llvm::PointerType::getUnqual(
3659 ProtocolListTyHolder),
3660 MethodListnfABIPtrTy,
3661 MethodListnfABIPtrTy,
3662 MethodListnfABIPtrTy,
3663 MethodListnfABIPtrTy,
3664 PropertyListPtrTy,
3665 IntTy,
3666 IntTy,
3667 NULL);
3668 CGM.getModule().addTypeName("struct._protocol_t",
3669 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003670
3671 // struct _protocol_t*
3672 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003673
Fariborz Jahanianda320092009-01-29 19:24:30 +00003674 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003675 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003676 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003677 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003678 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3679 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003680 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003681 NULL);
3682 CGM.getModule().addTypeName("struct._objc_protocol_list",
3683 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003684 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3685 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003686
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003687 // struct _objc_protocol_list*
3688 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003689
3690 // struct _ivar_t {
3691 // unsigned long int *offset; // pointer to ivar offset location
3692 // char *name;
3693 // char *type;
3694 // uint32_t alignment;
3695 // uint32_t size;
3696 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003697 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3698 Int8PtrTy,
3699 Int8PtrTy,
3700 IntTy,
3701 IntTy,
3702 NULL);
3703 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3704
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003705 // struct _ivar_list_t {
3706 // uint32 entsize; // sizeof(struct _ivar_t)
3707 // uint32 count;
3708 // struct _iver_t list[count];
3709 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003710 IvarListnfABITy = llvm::StructType::get(IntTy,
3711 IntTy,
3712 llvm::ArrayType::get(
3713 IvarnfABITy, 0),
3714 NULL);
3715 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3716
3717 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003718
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003719 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003720 // uint32_t const flags;
3721 // uint32_t const instanceStart;
3722 // uint32_t const instanceSize;
3723 // uint32_t const reserved; // only when building for 64bit targets
3724 // const uint8_t * const ivarLayout;
3725 // const char *const name;
3726 // const struct _method_list_t * const baseMethods;
3727 // const struct _objc_protocol_list *const baseProtocols;
3728 // const struct _ivar_list_t *const ivars;
3729 // const uint8_t * const weakIvarLayout;
3730 // const struct _prop_list_t * const properties;
3731 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003732
3733 // FIXME. Add 'reserved' field in 64bit abi mode!
3734 ClassRonfABITy = llvm::StructType::get(IntTy,
3735 IntTy,
3736 IntTy,
3737 Int8PtrTy,
3738 Int8PtrTy,
3739 MethodListnfABIPtrTy,
3740 ProtocolListnfABIPtrTy,
3741 IvarListnfABIPtrTy,
3742 Int8PtrTy,
3743 PropertyListPtrTy,
3744 NULL);
3745 CGM.getModule().addTypeName("struct._class_ro_t",
3746 ClassRonfABITy);
3747
3748 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3749 std::vector<const llvm::Type*> Params;
3750 Params.push_back(ObjectPtrTy);
3751 Params.push_back(SelectorPtrTy);
3752 ImpnfABITy = llvm::PointerType::getUnqual(
3753 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3754
3755 // struct _class_t {
3756 // struct _class_t *isa;
3757 // struct _class_t * const superclass;
3758 // void *cache;
3759 // IMP *vtable;
3760 // struct class_ro_t *ro;
3761 // }
3762
3763 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3764 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3765 llvm::PointerType::getUnqual(ClassTyHolder),
3766 CachePtrTy,
3767 llvm::PointerType::getUnqual(ImpnfABITy),
3768 llvm::PointerType::getUnqual(
3769 ClassRonfABITy),
3770 NULL);
3771 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3772
3773 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3774 ClassnfABITy);
3775
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003776 // LLVM for struct _class_t *
3777 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3778
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003779 // struct _category_t {
3780 // const char * const name;
3781 // struct _class_t *const cls;
3782 // const struct _method_list_t * const instance_methods;
3783 // const struct _method_list_t * const class_methods;
3784 // const struct _protocol_list_t * const protocols;
3785 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003786 // }
3787 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003788 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003789 MethodListnfABIPtrTy,
3790 MethodListnfABIPtrTy,
3791 ProtocolListnfABIPtrTy,
3792 PropertyListPtrTy,
3793 NULL);
3794 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003795
3796 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003797 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3798 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003799
3800 // MessageRefTy - LLVM for:
3801 // struct _message_ref_t {
3802 // IMP messenger;
3803 // SEL name;
3804 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003805
3806 // First the clang type for struct _message_ref_t
3807 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3808 SourceLocation(),
3809 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003810 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3811 Ctx.VoidPtrTy, 0, false));
3812 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3813 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003814 RD->completeDefinition(Ctx);
3815
3816 MessageRefCTy = Ctx.getTagDeclType(RD);
3817 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3818 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003819
3820 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3821 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3822
3823 // SuperMessageRefTy - LLVM for:
3824 // struct _super_message_ref_t {
3825 // SUPER_IMP messenger;
3826 // SEL name;
3827 // };
3828 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3829 SelectorPtrTy,
3830 NULL);
3831 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3832
3833 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3834 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3835
3836 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3837 Params.clear();
3838 Params.push_back(ObjectPtrTy);
3839 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003840 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3841 Params,
3842 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003843 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003844 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003845 "objc_msgSend_fixup");
3846
3847 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3848 MessageSendFpretFixupFn =
3849 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3850 Params,
3851 true),
3852 "objc_msgSend_fpret_fixup");
3853
3854 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3855 MessageSendStretFixupFn =
3856 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3857 Params,
3858 true),
3859 "objc_msgSend_stret_fixup");
3860
3861 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3862 MessageSendIdFixupFn =
3863 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3864 Params,
3865 true),
3866 "objc_msgSendId_fixup");
3867
3868
3869 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3870 MessageSendIdStretFixupFn =
3871 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3872 Params,
3873 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003874 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003875
3876 // id objc_msgSendSuper2_fixup (struct objc_super *,
3877 // struct _super_message_ref_t*, ...)
3878 Params.clear();
3879 Params.push_back(SuperPtrTy);
3880 Params.push_back(SuperMessageRefPtrTy);
3881 MessageSendSuper2FixupFn =
3882 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3883 Params,
3884 true),
3885 "objc_msgSendSuper2_fixup");
3886
3887
3888 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3889 // struct _super_message_ref_t*, ...)
3890 MessageSendSuper2StretFixupFn =
3891 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3892 Params,
3893 true),
3894 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003895
3896 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003897 Params.push_back(Int8PtrTy);
3898 UnwindResumeOrRethrowFn =
3899 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3900 Params,
3901 false),
3902 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003903 ObjCBeginCatchFn =
3904 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3905 Params,
3906 false),
3907 "objc_begin_catch");
3908
3909 Params.clear();
3910 ObjCEndCatchFn =
3911 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3912 Params,
3913 false),
3914 "objc_end_catch");
3915
3916 // struct objc_typeinfo {
3917 // const void** vtable; // objc_ehtype_vtable + 2
3918 // const char* name; // c++ typeinfo string
3919 // Class cls;
3920 // };
3921 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3922 Int8PtrTy,
3923 ClassnfABIPtrTy,
3924 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003925 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003926 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003927}
3928
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003929llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3930 FinishNonFragileABIModule();
3931
3932 return NULL;
3933}
3934
3935void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3936 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003937
3938 // Build list of all implemented classe addresses in array
3939 // L_OBJC_LABEL_CLASS_$.
3940 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3941 // list of 'nonlazy' implementations (defined as those with a +load{}
3942 // method!!).
3943 unsigned NumClasses = DefinedClasses.size();
3944 if (NumClasses) {
3945 std::vector<llvm::Constant*> Symbols(NumClasses);
3946 for (unsigned i=0; i<NumClasses; i++)
3947 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3948 ObjCTypes.Int8PtrTy);
3949 llvm::Constant* Init =
3950 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3951 NumClasses),
3952 Symbols);
3953
3954 llvm::GlobalVariable *GV =
3955 new llvm::GlobalVariable(Init->getType(), false,
3956 llvm::GlobalValue::InternalLinkage,
3957 Init,
3958 "\01L_OBJC_LABEL_CLASS_$",
3959 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003960 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003961 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3962 UsedGlobals.push_back(GV);
3963 }
3964
3965 // Build list of all implemented category addresses in array
3966 // L_OBJC_LABEL_CATEGORY_$.
3967 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3968 // list of 'nonlazy' category implementations (defined as those with a +load{}
3969 // method!!).
3970 unsigned NumCategory = DefinedCategories.size();
3971 if (NumCategory) {
3972 std::vector<llvm::Constant*> Symbols(NumCategory);
3973 for (unsigned i=0; i<NumCategory; i++)
3974 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3975 ObjCTypes.Int8PtrTy);
3976 llvm::Constant* Init =
3977 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3978 NumCategory),
3979 Symbols);
3980
3981 llvm::GlobalVariable *GV =
3982 new llvm::GlobalVariable(Init->getType(), false,
3983 llvm::GlobalValue::InternalLinkage,
3984 Init,
3985 "\01L_OBJC_LABEL_CATEGORY_$",
3986 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003987 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003988 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3989 UsedGlobals.push_back(GV);
3990 }
3991
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003992 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3993 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3994 std::vector<llvm::Constant*> Values(2);
3995 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003996 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003997 // FIXME: Fix and continue?
3998 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3999 flags |= eImageInfo_GarbageCollected;
4000 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4001 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004002 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004003 llvm::Constant* Init = llvm::ConstantArray::get(
4004 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4005 Values);
4006 llvm::GlobalVariable *IMGV =
4007 new llvm::GlobalVariable(Init->getType(), false,
4008 llvm::GlobalValue::InternalLinkage,
4009 Init,
4010 "\01L_OBJC_IMAGE_INFO",
4011 &CGM.getModule());
4012 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4013 UsedGlobals.push_back(IMGV);
4014
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004015 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004016
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004017 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4018 e = UsedGlobals.end(); i != e; ++i) {
4019 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4020 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004021
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004022 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4023 llvm::GlobalValue *GV =
4024 new llvm::GlobalVariable(AT, false,
4025 llvm::GlobalValue::AppendingLinkage,
4026 llvm::ConstantArray::get(AT, Used),
4027 "llvm.used",
4028 &CGM.getModule());
4029
4030 GV->setSection("llvm.metadata");
4031
4032}
4033
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004034// Metadata flags
4035enum MetaDataDlags {
4036 CLS = 0x0,
4037 CLS_META = 0x1,
4038 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004039 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004040 CLS_EXCEPTION = 0x20
4041};
4042/// BuildClassRoTInitializer - generate meta-data for:
4043/// struct _class_ro_t {
4044/// uint32_t const flags;
4045/// uint32_t const instanceStart;
4046/// uint32_t const instanceSize;
4047/// uint32_t const reserved; // only when building for 64bit targets
4048/// const uint8_t * const ivarLayout;
4049/// const char *const name;
4050/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004051/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004052/// const struct _ivar_list_t *const ivars;
4053/// const uint8_t * const weakIvarLayout;
4054/// const struct _prop_list_t * const properties;
4055/// }
4056///
4057llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4058 unsigned flags,
4059 unsigned InstanceStart,
4060 unsigned InstanceSize,
4061 const ObjCImplementationDecl *ID) {
4062 std::string ClassName = ID->getNameAsString();
4063 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4064 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4065 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4066 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4067 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004068 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004069 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004070 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004071 // const struct _method_list_t * const baseMethods;
4072 std::vector<llvm::Constant*> Methods;
4073 std::string MethodListName("\01l_OBJC_$_");
4074 if (flags & CLS_META) {
4075 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4076 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4077 e = ID->classmeth_end(); i != e; ++i) {
4078 // Class methods should always be defined.
4079 Methods.push_back(GetMethodConstant(*i));
4080 }
4081 } else {
4082 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4083 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4084 e = ID->instmeth_end(); i != e; ++i) {
4085 // Instance methods should always be defined.
4086 Methods.push_back(GetMethodConstant(*i));
4087 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004088 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4089 e = ID->propimpl_end(); i != e; ++i) {
4090 ObjCPropertyImplDecl *PID = *i;
4091
4092 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4093 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4094
4095 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4096 if (llvm::Constant *C = GetMethodConstant(MD))
4097 Methods.push_back(C);
4098 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4099 if (llvm::Constant *C = GetMethodConstant(MD))
4100 Methods.push_back(C);
4101 }
4102 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004103 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004104 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004105 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004106
4107 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4108 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4109 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4110 + OID->getNameAsString(),
4111 OID->protocol_begin(),
4112 OID->protocol_end());
4113
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004114 if (flags & CLS_META)
4115 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4116 else
4117 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004118 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004119 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004120 if (flags & CLS_META)
4121 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4122 else
4123 Values[ 9] =
4124 EmitPropertyList(
4125 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4126 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004127 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4128 Values);
4129 llvm::GlobalVariable *CLASS_RO_GV =
4130 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4131 llvm::GlobalValue::InternalLinkage,
4132 Init,
4133 (flags & CLS_META) ?
4134 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4135 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4136 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004137 CLASS_RO_GV->setAlignment(
4138 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004139 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004140 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004141
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004142}
4143
4144/// BuildClassMetaData - This routine defines that to-level meta-data
4145/// for the given ClassName for:
4146/// struct _class_t {
4147/// struct _class_t *isa;
4148/// struct _class_t * const superclass;
4149/// void *cache;
4150/// IMP *vtable;
4151/// struct class_ro_t *ro;
4152/// }
4153///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004154llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4155 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004156 llvm::Constant *IsAGV,
4157 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004158 llvm::Constant *ClassRoGV,
4159 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004160 std::vector<llvm::Constant*> Values(5);
4161 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004162 Values[1] = SuperClassGV
4163 ? SuperClassGV
4164 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004165 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4166 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4167 Values[4] = ClassRoGV; // &CLASS_RO_GV
4168 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4169 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004170 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4171 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004172 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004173 GV->setAlignment(
4174 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004175 if (HiddenVisibility)
4176 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004177 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004178}
4179
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004180void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4181 std::string ClassName = ID->getNameAsString();
4182 if (!ObjCEmptyCacheVar) {
4183 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004184 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004185 false,
4186 llvm::GlobalValue::ExternalLinkage,
4187 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004188 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004189 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004190
4191 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004192 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004193 false,
4194 llvm::GlobalValue::ExternalLinkage,
4195 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004196 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004197 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004198 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004199 assert(ID->getClassInterface() &&
4200 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004201 uint32_t InstanceStart =
4202 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4203 uint32_t InstanceSize = InstanceStart;
4204 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004205 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4206 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004207
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004208 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004209
Daniel Dunbar04d40782009-04-14 06:00:08 +00004210 bool classIsHidden =
4211 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004212 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004213 flags |= OBJC2_CLS_HIDDEN;
4214 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004215 // class is root
4216 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004217 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004218 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004219 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004220 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004221 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4222 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4223 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004224 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004225 // work on super class metadata symbol.
4226 std::string SuperClassName =
4227 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004228 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004229 }
4230 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4231 InstanceStart,
4232 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004233 std::string TClassName = ObjCMetaClassName + ClassName;
4234 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004235 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4236 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004237
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004238 // Metadata for the class
4239 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004240 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004241 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004242
4243 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4244 flags |= CLS_EXCEPTION;
4245
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004246 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004247 flags |= CLS_ROOT;
4248 SuperClassGV = 0;
4249 }
4250 else {
4251 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004252 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004253 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004254 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004255 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004256 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004257 InstanceStart = InstanceSize = 0;
4258 if (ObjCInterfaceDecl *OID =
4259 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4260 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004261 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004262
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004263 RecordDecl::field_iterator firstField, lastField;
4264 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004265
Douglas Gregor6ab35242009-04-09 21:40:53 +00004266 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004267 ifield = firstField; ifield != e; ++ifield)
4268 lastField = ifield;
4269
Douglas Gregor6ab35242009-04-09 21:40:53 +00004270 if (lastField != RD->field_end(CGM.getContext())) {
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004271 FieldDecl *Field = *lastField;
4272 const llvm::Type *FieldTy =
4273 CGM.getTypes().ConvertTypeForMem(Field->getType());
4274 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004275 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004276 if (firstField == RD->field_end(CGM.getContext()))
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004277 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004278 else {
4279 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004280 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004281 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004282 }
4283 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004284 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004285 InstanceStart,
4286 InstanceSize,
4287 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004288
4289 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004290 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004291 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4292 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004293 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004294
4295 // Force the definition of the EHType if necessary.
4296 if (flags & CLS_EXCEPTION)
4297 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004298}
4299
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004300/// GenerateProtocolRef - This routine is called to generate code for
4301/// a protocol reference expression; as in:
4302/// @code
4303/// @protocol(Proto1);
4304/// @endcode
4305/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4306/// which will hold address of the protocol meta-data.
4307///
4308llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4309 const ObjCProtocolDecl *PD) {
4310
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004311 // This routine is called for @protocol only. So, we must build definition
4312 // of protocol's meta-data (not a reference to it!)
4313 //
4314 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004315 ObjCTypes.ExternalProtocolPtrTy);
4316
4317 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4318 ProtocolName += PD->getNameAsCString();
4319
4320 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4321 if (PTGV)
4322 return Builder.CreateLoad(PTGV, false, "tmp");
4323 PTGV = new llvm::GlobalVariable(
4324 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004325 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004326 Init,
4327 ProtocolName,
4328 &CGM.getModule());
4329 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4330 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4331 UsedGlobals.push_back(PTGV);
4332 return Builder.CreateLoad(PTGV, false, "tmp");
4333}
4334
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004335/// GenerateCategory - Build metadata for a category implementation.
4336/// struct _category_t {
4337/// const char * const name;
4338/// struct _class_t *const cls;
4339/// const struct _method_list_t * const instance_methods;
4340/// const struct _method_list_t * const class_methods;
4341/// const struct _protocol_list_t * const protocols;
4342/// const struct _prop_list_t * const properties;
4343/// }
4344///
4345void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4346{
4347 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004348 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4349 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004350 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004351 std::string ExtClassName(getClassSymbolPrefix() +
4352 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004353
4354 std::vector<llvm::Constant*> Values(6);
4355 Values[0] = GetClassName(OCD->getIdentifier());
4356 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004357 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004358 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004359 std::vector<llvm::Constant*> Methods;
4360 std::string MethodListName(Prefix);
4361 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4362 "_$_" + OCD->getNameAsString();
4363
4364 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4365 e = OCD->instmeth_end(); i != e; ++i) {
4366 // Instance methods should always be defined.
4367 Methods.push_back(GetMethodConstant(*i));
4368 }
4369
4370 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004371 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004372 Methods);
4373
4374 MethodListName = Prefix;
4375 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4376 OCD->getNameAsString();
4377 Methods.clear();
4378 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4379 e = OCD->classmeth_end(); i != e; ++i) {
4380 // Class methods should always be defined.
4381 Methods.push_back(GetMethodConstant(*i));
4382 }
4383
4384 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004385 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004386 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004387 const ObjCCategoryDecl *Category =
4388 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004389 if (Category) {
4390 std::string ExtName(Interface->getNameAsString() + "_$_" +
4391 OCD->getNameAsString());
4392 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4393 + Interface->getNameAsString() + "_$_"
4394 + Category->getNameAsString(),
4395 Category->protocol_begin(),
4396 Category->protocol_end());
4397 Values[5] =
4398 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4399 OCD, Category, ObjCTypes);
4400 }
4401 else {
4402 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4403 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4404 }
4405
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004406 llvm::Constant *Init =
4407 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4408 Values);
4409 llvm::GlobalVariable *GCATV
4410 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4411 false,
4412 llvm::GlobalValue::InternalLinkage,
4413 Init,
4414 ExtCatName,
4415 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004416 GCATV->setAlignment(
4417 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004418 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004419 UsedGlobals.push_back(GCATV);
4420 DefinedCategories.push_back(GCATV);
4421}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004422
4423/// GetMethodConstant - Return a struct objc_method constant for the
4424/// given method if it has been defined. The result is null if the
4425/// method has not been defined. The return value has type MethodPtrTy.
4426llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4427 const ObjCMethodDecl *MD) {
4428 // FIXME: Use DenseMap::lookup
4429 llvm::Function *Fn = MethodDefinitions[MD];
4430 if (!Fn)
4431 return 0;
4432
4433 std::vector<llvm::Constant*> Method(3);
4434 Method[0] =
4435 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4436 ObjCTypes.SelectorPtrTy);
4437 Method[1] = GetMethodVarType(MD);
4438 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4439 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4440}
4441
4442/// EmitMethodList - Build meta-data for method declarations
4443/// struct _method_list_t {
4444/// uint32_t entsize; // sizeof(struct _objc_method)
4445/// uint32_t method_count;
4446/// struct _objc_method method_list[method_count];
4447/// }
4448///
4449llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4450 const std::string &Name,
4451 const char *Section,
4452 const ConstantVector &Methods) {
4453 // Return null for empty list.
4454 if (Methods.empty())
4455 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4456
4457 std::vector<llvm::Constant*> Values(3);
4458 // sizeof(struct _objc_method)
4459 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4460 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4461 // method_count
4462 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4463 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4464 Methods.size());
4465 Values[2] = llvm::ConstantArray::get(AT, Methods);
4466 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4467
4468 llvm::GlobalVariable *GV =
4469 new llvm::GlobalVariable(Init->getType(), false,
4470 llvm::GlobalValue::InternalLinkage,
4471 Init,
4472 Name,
4473 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004474 GV->setAlignment(
4475 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004476 GV->setSection(Section);
4477 UsedGlobals.push_back(GV);
4478 return llvm::ConstantExpr::getBitCast(GV,
4479 ObjCTypes.MethodListnfABIPtrTy);
4480}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004481
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004482/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4483/// the given ivar.
4484///
4485llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4486 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004487 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004488 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004489 Name += "\01_OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004490 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4491 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004492 llvm::GlobalVariable *IvarOffsetGV =
4493 CGM.getModule().getGlobalVariable(Name);
4494 if (!IvarOffsetGV)
4495 IvarOffsetGV =
4496 new llvm::GlobalVariable(ObjCTypes.LongTy,
4497 false,
4498 llvm::GlobalValue::ExternalLinkage,
4499 0,
4500 Name,
4501 &CGM.getModule());
4502 return IvarOffsetGV;
4503}
4504
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004505llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004506 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004507 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004508 unsigned long int Offset) {
4509
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004510 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004511 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004512 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004513 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004514 llvm::GlobalVariable *IvarOffsetGV =
4515 CGM.getModule().getGlobalVariable(ExternalName);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004516 if (IvarOffsetGV)
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004517 // ivar offset symbol already built due to user code referencing it.
4518 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004519 else
4520 IvarOffsetGV =
4521 new llvm::GlobalVariable(Init->getType(),
4522 false,
4523 llvm::GlobalValue::ExternalLinkage,
4524 Init,
4525 ExternalName,
4526 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004527 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004528 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004529 // @private and @package have hidden visibility.
4530 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
Daniel Dunbar04d40782009-04-14 06:00:08 +00004531 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4532 if (!globalVisibility || CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004533 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004534 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004535 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004536 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004537 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004538}
4539
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004540/// EmitIvarList - Emit the ivar list for the given
4541/// implementation. If ForClass is true the list of class ivars
4542/// (i.e. metaclass ivars) is emitted, otherwise the list of
4543/// interface ivars will be emitted. The return value has type
4544/// IvarListnfABIPtrTy.
4545/// struct _ivar_t {
4546/// unsigned long int *offset; // pointer to ivar offset location
4547/// char *name;
4548/// char *type;
4549/// uint32_t alignment;
4550/// uint32_t size;
4551/// }
4552/// struct _ivar_list_t {
4553/// uint32 entsize; // sizeof(struct _ivar_t)
4554/// uint32 count;
4555/// struct _iver_t list[count];
4556/// }
4557///
4558llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4559 const ObjCImplementationDecl *ID) {
4560
4561 std::vector<llvm::Constant*> Ivars, Ivar(5);
4562
4563 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4564 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4565
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004566 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004567 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004568
4569 RecordDecl::field_iterator i,p;
4570 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004571 // collect declared and synthesized ivars in a small vector.
4572 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4573 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4574 E = OID->ivar_end(); I != E; ++I)
4575 OIvars.push_back(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00004576 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4577 E = OID->prop_end(CGM.getContext()); I != E; ++I)
Fariborz Jahanian18191882009-03-31 18:11:23 +00004578 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4579 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004580
Fariborz Jahanian18191882009-03-31 18:11:23 +00004581 unsigned iv = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004582 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext());
4583 i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004584 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004585 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004586 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004587 if (Field->getIdentifier())
4588 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4589 else
4590 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004591 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004592 const llvm::Type *FieldTy =
4593 CGM.getTypes().ConvertTypeForMem(Field->getType());
4594 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4595 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4596 Field->getType().getTypePtr()) >> 3;
4597 Align = llvm::Log2_32(Align);
4598 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004599 // NOTE. Size of a bitfield does not match gcc's, because of the way
4600 // bitfields are treated special in each. But I am told that 'size'
4601 // for bitfield ivars is ignored by the runtime so it does not matter.
4602 // (even if it matters, some day, there is enough info. to get the bitfield
4603 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004604 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4605 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4606 }
4607 // Return null for empty list.
4608 if (Ivars.empty())
4609 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4610 std::vector<llvm::Constant*> Values(3);
4611 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4612 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4613 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4614 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4615 Ivars.size());
4616 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4617 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4618 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4619 llvm::GlobalVariable *GV =
4620 new llvm::GlobalVariable(Init->getType(), false,
4621 llvm::GlobalValue::InternalLinkage,
4622 Init,
4623 Prefix + OID->getNameAsString(),
4624 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004625 GV->setAlignment(
4626 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004627 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004628
4629 UsedGlobals.push_back(GV);
4630 return llvm::ConstantExpr::getBitCast(GV,
4631 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004632}
4633
4634llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4635 const ObjCProtocolDecl *PD) {
4636 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4637
4638 if (!Entry) {
4639 // We use the initializer as a marker of whether this is a forward
4640 // reference or not. At module finalization we add the empty
4641 // contents for protocols which were referenced but never defined.
4642 Entry =
4643 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4644 llvm::GlobalValue::ExternalLinkage,
4645 0,
4646 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4647 &CGM.getModule());
4648 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4649 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004650 }
4651
4652 return Entry;
4653}
4654
4655/// GetOrEmitProtocol - Generate the protocol meta-data:
4656/// @code
4657/// struct _protocol_t {
4658/// id isa; // NULL
4659/// const char * const protocol_name;
4660/// const struct _protocol_list_t * protocol_list; // super protocols
4661/// const struct method_list_t * const instance_methods;
4662/// const struct method_list_t * const class_methods;
4663/// const struct method_list_t *optionalInstanceMethods;
4664/// const struct method_list_t *optionalClassMethods;
4665/// const struct _prop_list_t * properties;
4666/// const uint32_t size; // sizeof(struct _protocol_t)
4667/// const uint32_t flags; // = 0
4668/// }
4669/// @endcode
4670///
4671
4672llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4673 const ObjCProtocolDecl *PD) {
4674 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4675
4676 // Early exit if a defining object has already been generated.
4677 if (Entry && Entry->hasInitializer())
4678 return Entry;
4679
4680 const char *ProtocolName = PD->getNameAsCString();
4681
4682 // Construct method lists.
4683 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4684 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004685 for (ObjCProtocolDecl::instmeth_iterator
4686 i = PD->instmeth_begin(CGM.getContext()),
4687 e = PD->instmeth_end(CGM.getContext());
4688 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004689 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004690 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004691 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4692 OptInstanceMethods.push_back(C);
4693 } else {
4694 InstanceMethods.push_back(C);
4695 }
4696 }
4697
Douglas Gregor6ab35242009-04-09 21:40:53 +00004698 for (ObjCProtocolDecl::classmeth_iterator
4699 i = PD->classmeth_begin(CGM.getContext()),
4700 e = PD->classmeth_end(CGM.getContext());
4701 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004702 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004703 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004704 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4705 OptClassMethods.push_back(C);
4706 } else {
4707 ClassMethods.push_back(C);
4708 }
4709 }
4710
4711 std::vector<llvm::Constant*> Values(10);
4712 // isa is NULL
4713 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4714 Values[1] = GetClassName(PD->getIdentifier());
4715 Values[2] = EmitProtocolList(
4716 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4717 PD->protocol_begin(),
4718 PD->protocol_end());
4719
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004720 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004721 + PD->getNameAsString(),
4722 "__DATA, __objc_const",
4723 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004724 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004725 + PD->getNameAsString(),
4726 "__DATA, __objc_const",
4727 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004728 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004729 + PD->getNameAsString(),
4730 "__DATA, __objc_const",
4731 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004732 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004733 + PD->getNameAsString(),
4734 "__DATA, __objc_const",
4735 OptClassMethods);
4736 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4737 0, PD, ObjCTypes);
4738 uint32_t Size =
4739 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4740 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4741 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4742 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4743 Values);
4744
4745 if (Entry) {
4746 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004747 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004748 Entry->setInitializer(Init);
4749 } else {
4750 Entry =
4751 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004752 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 Init,
4754 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4755 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004756 Entry->setAlignment(
4757 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004758 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004759 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004760 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4761
4762 // Use this protocol meta-data to build protocol list table in section
4763 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004764 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004765 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004766 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004767 Entry,
4768 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4769 +ProtocolName,
4770 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004771 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004772 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004773 PTGV->setSection("__DATA, __objc_protolist");
4774 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4775 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004776 return Entry;
4777}
4778
4779/// EmitProtocolList - Generate protocol list meta-data:
4780/// @code
4781/// struct _protocol_list_t {
4782/// long protocol_count; // Note, this is 32/64 bit
4783/// struct _protocol_t[protocol_count];
4784/// }
4785/// @endcode
4786///
4787llvm::Constant *
4788CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4789 ObjCProtocolDecl::protocol_iterator begin,
4790 ObjCProtocolDecl::protocol_iterator end) {
4791 std::vector<llvm::Constant*> ProtocolRefs;
4792
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004794 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004795 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4796
Daniel Dunbar948e2582009-02-15 07:36:20 +00004797 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004798 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4799 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004800 return llvm::ConstantExpr::getBitCast(GV,
4801 ObjCTypes.ProtocolListnfABIPtrTy);
4802
4803 for (; begin != end; ++begin)
4804 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4805
Fariborz Jahanianda320092009-01-29 19:24:30 +00004806 // This list is null terminated.
4807 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004808 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004809
4810 std::vector<llvm::Constant*> Values(2);
4811 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4812 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004813 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004814 ProtocolRefs.size()),
4815 ProtocolRefs);
4816
4817 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4818 GV = new llvm::GlobalVariable(Init->getType(), false,
4819 llvm::GlobalValue::InternalLinkage,
4820 Init,
4821 Name,
4822 &CGM.getModule());
4823 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004824 GV->setAlignment(
4825 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004826 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004827 return llvm::ConstantExpr::getBitCast(GV,
4828 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004829}
4830
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004831/// GetMethodDescriptionConstant - This routine build following meta-data:
4832/// struct _objc_method {
4833/// SEL _cmd;
4834/// char *method_type;
4835/// char *_imp;
4836/// }
4837
4838llvm::Constant *
4839CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4840 std::vector<llvm::Constant*> Desc(3);
4841 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4842 ObjCTypes.SelectorPtrTy);
4843 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004844 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004845 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4846 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4847}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004848
4849/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4850/// This code gen. amounts to generating code for:
4851/// @code
4852/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4853/// @encode
4854///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004855LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004856 CodeGen::CodeGenFunction &CGF,
4857 QualType ObjectTy,
4858 llvm::Value *BaseValue,
4859 const ObjCIvarDecl *Ivar,
4860 const FieldDecl *Field,
4861 unsigned CVRQualifiers) {
4862 assert(ObjectTy->isObjCInterfaceType() &&
4863 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004864 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004865 std::string ExternalName;
4866 llvm::GlobalVariable *IvarOffsetGV =
4867 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004868
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004869 // (char *) BaseValue
4870 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4871 ObjCTypes.Int8PtrTy);
4872 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4873 // (char*)BaseValue + Offset_symbol
4874 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4875 // (type *)((char*)BaseValue + Offset_symbol)
4876 const llvm::Type *IvarTy =
4877 CGM.getTypes().ConvertType(Ivar->getType());
4878 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4879 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004880
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004881 if (Ivar->isBitField()) {
4882 CodeGenTypes::BitFieldInfo bitFieldInfo =
4883 CGM.getTypes().getBitFieldInfo(Field);
4884 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4885 Field->getType()->isSignedIntegerType(),
4886 Field->getType().getCVRQualifiers()|CVRQualifiers);
4887 }
4888
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004889 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004890 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4891 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004892 LValue::SetObjCIvar(LV, true);
4893 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004894}
4895
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004896llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4897 CodeGen::CodeGenFunction &CGF,
4898 ObjCInterfaceDecl *Interface,
4899 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004900 std::string ExternalName;
4901 llvm::GlobalVariable *IvarOffsetGV =
4902 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4903
4904 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004905}
4906
Fariborz Jahanian46551122009-02-04 00:22:57 +00004907CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4908 CodeGen::CodeGenFunction &CGF,
4909 QualType ResultType,
4910 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004911 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004912 QualType Arg0Ty,
4913 bool IsSuper,
4914 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004915 // FIXME. Even though IsSuper is passes. This function doese not
4916 // handle calls to 'super' receivers.
4917 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004918 llvm::Value *Arg0 = Receiver;
4919 if (!IsSuper)
4920 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004921
4922 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004923 // FIXME. This is too much work to get the ABI-specific result type
4924 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004925 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4926 llvm::SmallVector<QualType, 16>());
4927 llvm::Constant *Fn;
4928 std::string Name("\01l_");
4929 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004930#if 0
4931 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004932 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4933 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4934 // FIXME. Is there a better way of getting these names.
4935 // They are available in RuntimeFunctions vector pair.
4936 Name += "objc_msgSendId_stret_fixup";
4937 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004938 else
4939#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004940 if (IsSuper) {
4941 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4942 Name += "objc_msgSendSuper2_stret_fixup";
4943 }
4944 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004945 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004946 Fn = ObjCTypes.MessageSendStretFixupFn;
4947 Name += "objc_msgSend_stret_fixup";
4948 }
4949 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004950 else if (ResultType->isFloatingType() &&
4951 // Selection of frret API only happens in 32bit nonfragile ABI.
4952 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004953 Fn = ObjCTypes.MessageSendFpretFixupFn;
4954 Name += "objc_msgSend_fpret_fixup";
4955 }
4956 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004957#if 0
4958// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004959 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4960 Fn = ObjCTypes.MessageSendIdFixupFn;
4961 Name += "objc_msgSendId_fixup";
4962 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004963 else
4964#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004965 if (IsSuper) {
4966 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4967 Name += "objc_msgSendSuper2_fixup";
4968 }
4969 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004970 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004971 Fn = ObjCTypes.MessageSendFixupFn;
4972 Name += "objc_msgSend_fixup";
4973 }
4974 }
4975 Name += '_';
4976 std::string SelName(Sel.getAsString());
4977 // Replace all ':' in selector name with '_' ouch!
4978 for(unsigned i = 0; i < SelName.size(); i++)
4979 if (SelName[i] == ':')
4980 SelName[i] = '_';
4981 Name += SelName;
4982 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4983 if (!GV) {
4984 // Build messafe ref table entry.
4985 std::vector<llvm::Constant*> Values(2);
4986 Values[0] = Fn;
4987 Values[1] = GetMethodVarName(Sel);
4988 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4989 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004990 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004991 Init,
4992 Name,
4993 &CGM.getModule());
4994 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4995 GV->setAlignment(
4996 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4997 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4998 UsedGlobals.push_back(GV);
4999 }
5000 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005001
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005002 CallArgList ActualArgs;
5003 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5004 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5005 ObjCTypes.MessageRefCPtrTy));
5006 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005007 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5008 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5009 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005010 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005011 Callee = CGF.Builder.CreateBitCast(Callee,
5012 llvm::PointerType::getUnqual(FTy));
5013 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005014}
5015
5016/// Generate code for a message send expression in the nonfragile abi.
5017CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5018 CodeGen::CodeGenFunction &CGF,
5019 QualType ResultType,
5020 Selector Sel,
5021 llvm::Value *Receiver,
5022 bool IsClassMessage,
5023 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005024 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005025 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005026 false, CallArgs);
5027}
5028
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005029llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005030CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005031 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5032
Daniel Dunbardfff2302009-03-02 05:18:14 +00005033 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005034 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5035 llvm::GlobalValue::ExternalLinkage,
5036 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005037 }
5038
5039 return GV;
5040}
5041
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005042llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005043 const ObjCInterfaceDecl *ID,
5044 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005045
5046 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5047
5048 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005049 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005050 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005051 Entry =
5052 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5053 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005054 ClassGV,
5055 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5056 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005057 &CGM.getModule());
5058 Entry->setAlignment(
5059 CGM.getTargetData().getPrefTypeAlignment(
5060 ObjCTypes.ClassnfABIPtrTy));
5061
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005062 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005063 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005064 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005065 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005066 UsedGlobals.push_back(Entry);
5067 }
5068
5069 return Builder.CreateLoad(Entry, false, "tmp");
5070}
5071
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005072/// EmitMetaClassRef - Return a Value * of the address of _class_t
5073/// meta-data
5074///
5075llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5076 const ObjCInterfaceDecl *ID) {
5077 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5078 if (Entry)
5079 return Builder.CreateLoad(Entry, false, "tmp");
5080
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005081 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005082 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005083 Entry =
5084 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5085 llvm::GlobalValue::InternalLinkage,
5086 MetaClassGV,
5087 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5088 &CGM.getModule());
5089 Entry->setAlignment(
5090 CGM.getTargetData().getPrefTypeAlignment(
5091 ObjCTypes.ClassnfABIPtrTy));
5092
5093 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
5094 UsedGlobals.push_back(Entry);
5095
5096 return Builder.CreateLoad(Entry, false, "tmp");
5097}
5098
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005099/// GetClass - Return a reference to the class for the given interface
5100/// decl.
5101llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5102 const ObjCInterfaceDecl *ID) {
5103 return EmitClassRef(Builder, ID);
5104}
5105
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005106/// Generates a message send where the super is the receiver. This is
5107/// a message send to self with special delivery semantics indicating
5108/// which class's method should be called.
5109CodeGen::RValue
5110CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5111 QualType ResultType,
5112 Selector Sel,
5113 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005114 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005115 llvm::Value *Receiver,
5116 bool IsClassMessage,
5117 const CodeGen::CallArgList &CallArgs) {
5118 // ...
5119 // Create and init a super structure; this is a (receiver, class)
5120 // pair we will pass to objc_msgSendSuper.
5121 llvm::Value *ObjCSuper =
5122 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5123
5124 llvm::Value *ReceiverAsObject =
5125 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5126 CGF.Builder.CreateStore(ReceiverAsObject,
5127 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5128
5129 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005130 llvm::Value *Target;
5131 if (IsClassMessage) {
5132 if (isCategoryImpl) {
5133 // Message sent to "super' in a class method defined in
5134 // a category implementation.
5135 Target = EmitClassRef(CGF.Builder, Class, false);
5136 Target = CGF.Builder.CreateStructGEP(Target, 0);
5137 Target = CGF.Builder.CreateLoad(Target);
5138 }
5139 else
5140 Target = EmitMetaClassRef(CGF.Builder, Class);
5141 }
5142 else
5143 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005144
5145 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5146 // and ObjCTypes types.
5147 const llvm::Type *ClassTy =
5148 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5149 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5150 CGF.Builder.CreateStore(Target,
5151 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5152
5153 return EmitMessageSend(CGF, ResultType, Sel,
5154 ObjCSuper, ObjCTypes.SuperPtrCTy,
5155 true, CallArgs);
5156}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005157
5158llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5159 Selector Sel) {
5160 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5161
5162 if (!Entry) {
5163 llvm::Constant *Casted =
5164 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5165 ObjCTypes.SelectorPtrTy);
5166 Entry =
5167 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5168 llvm::GlobalValue::InternalLinkage,
5169 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5170 &CGM.getModule());
5171 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5172 UsedGlobals.push_back(Entry);
5173 }
5174
5175 return Builder.CreateLoad(Entry, false, "tmp");
5176}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005177/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5178/// objc_assign_ivar (id src, id *dst)
5179///
5180void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5181 llvm::Value *src, llvm::Value *dst)
5182{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005183 const llvm::Type * SrcTy = src->getType();
5184 if (!isa<llvm::PointerType>(SrcTy)) {
5185 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5186 assert(Size <= 8 && "does not support size > 8");
5187 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5188 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005189 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5190 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005191 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5192 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5193 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5194 src, dst, "assignivar");
5195 return;
5196}
5197
5198/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5199/// objc_assign_strongCast (id src, id *dst)
5200///
5201void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5202 CodeGen::CodeGenFunction &CGF,
5203 llvm::Value *src, llvm::Value *dst)
5204{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005205 const llvm::Type * SrcTy = src->getType();
5206 if (!isa<llvm::PointerType>(SrcTy)) {
5207 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5208 assert(Size <= 8 && "does not support size > 8");
5209 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5210 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005211 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5212 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005213 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5214 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5215 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5216 src, dst, "weakassign");
5217 return;
5218}
5219
5220/// EmitObjCWeakRead - Code gen for loading value of a __weak
5221/// object: objc_read_weak (id *src)
5222///
5223llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5224 CodeGen::CodeGenFunction &CGF,
5225 llvm::Value *AddrWeakObj)
5226{
Eli Friedman8339b352009-03-07 03:57:15 +00005227 const llvm::Type* DestTy =
5228 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005229 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5230 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5231 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005232 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005233 return read_weak;
5234}
5235
5236/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5237/// objc_assign_weak (id src, id *dst)
5238///
5239void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5240 llvm::Value *src, llvm::Value *dst)
5241{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005242 const llvm::Type * SrcTy = src->getType();
5243 if (!isa<llvm::PointerType>(SrcTy)) {
5244 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5245 assert(Size <= 8 && "does not support size > 8");
5246 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5247 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005248 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5249 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005250 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5251 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5252 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5253 src, dst, "weakassign");
5254 return;
5255}
5256
5257/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5258/// objc_assign_global (id src, id *dst)
5259///
5260void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5261 llvm::Value *src, llvm::Value *dst)
5262{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005263 const llvm::Type * SrcTy = src->getType();
5264 if (!isa<llvm::PointerType>(SrcTy)) {
5265 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5266 assert(Size <= 8 && "does not support size > 8");
5267 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5268 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005269 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5270 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005271 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5272 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5273 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5274 src, dst, "globalassign");
5275 return;
5276}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005277
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005278void
5279CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5280 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005281 bool isTry = isa<ObjCAtTryStmt>(S);
5282 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5283 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005284 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005285 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005286 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005287 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5288
5289 // For @synchronized, call objc_sync_enter(sync.expr). The
5290 // evaluation of the expression must occur before we enter the
5291 // @synchronized. We can safely avoid a temp here because jumps into
5292 // @synchronized are illegal & this will dominate uses.
5293 llvm::Value *SyncArg = 0;
5294 if (!isTry) {
5295 SyncArg =
5296 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5297 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005298 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005299 }
5300
5301 // Push an EH context entry, used for handling rethrows and jumps
5302 // through finally.
5303 CGF.PushCleanupBlock(FinallyBlock);
5304
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005305 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005306
5307 CGF.EmitBlock(TryBlock);
5308 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5309 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5310 CGF.EmitBranchThroughCleanup(FinallyEnd);
5311
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005312 // Emit the exception handler.
5313
5314 CGF.EmitBlock(TryHandler);
5315
5316 llvm::Value *llvm_eh_exception =
5317 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5318 llvm::Value *llvm_eh_selector_i64 =
5319 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5320 llvm::Value *llvm_eh_typeid_for_i64 =
5321 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5322 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5323 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5324
5325 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5326 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005327 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005328
5329 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005330 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005331 bool HasCatchAll = false;
5332 if (isTry) {
5333 if (const ObjCAtCatchStmt* CatchStmt =
5334 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5335 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005336 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005337 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005338
5339 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005340 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005341 // Use i8* null here to signal this is a catch all, not a cleanup.
5342 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5343 SelectorArgs.push_back(Null);
5344 HasCatchAll = true;
5345 break;
5346 }
5347
Daniel Dunbarede8de92009-03-06 00:01:21 +00005348 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5349 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005350 llvm::Value *IDEHType =
5351 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5352 if (!IDEHType)
5353 IDEHType =
5354 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5355 llvm::GlobalValue::ExternalLinkage,
5356 0, "OBJC_EHTYPE_id", &CGM.getModule());
5357 SelectorArgs.push_back(IDEHType);
5358 HasCatchAll = true;
5359 break;
5360 }
5361
5362 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005363 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005364 assert(PT && "Invalid @catch type.");
5365 const ObjCInterfaceType *IT =
5366 PT->getPointeeType()->getAsObjCInterfaceType();
5367 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005368 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005369 SelectorArgs.push_back(EHType);
5370 }
5371 }
5372 }
5373
5374 // We use a cleanup unless there was already a catch all.
5375 if (!HasCatchAll) {
5376 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005377 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005378 }
5379
5380 llvm::Value *Selector =
5381 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5382 SelectorArgs.begin(), SelectorArgs.end(),
5383 "selector");
5384 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005385 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005386 const Stmt *CatchBody = Handlers[i].second;
5387
5388 llvm::BasicBlock *Next = 0;
5389
5390 // The last handler always matches.
5391 if (i + 1 != e) {
5392 assert(CatchParam && "Only last handler can be a catch all.");
5393
5394 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5395 Next = CGF.createBasicBlock("catch.next");
5396 llvm::Value *Id =
5397 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5398 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5399 ObjCTypes.Int8PtrTy));
5400 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5401 Match, Next);
5402
5403 CGF.EmitBlock(Match);
5404 }
5405
5406 if (CatchBody) {
5407 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5408 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5409
5410 // Cleanups must call objc_end_catch.
5411 //
5412 // FIXME: It seems incorrect for objc_begin_catch to be inside
5413 // this context, but this matches gcc.
5414 CGF.PushCleanupBlock(MatchEnd);
5415 CGF.setInvokeDest(MatchHandler);
5416
5417 llvm::Value *ExcObject =
5418 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5419
5420 // Bind the catch parameter if it exists.
5421 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005422 ExcObject =
5423 CGF.Builder.CreateBitCast(ExcObject,
5424 CGF.ConvertType(CatchParam->getType()));
5425 // CatchParam is a ParmVarDecl because of the grammar
5426 // construction used to handle this, but for codegen purposes
5427 // we treat this as a local decl.
5428 CGF.EmitLocalBlockVarDecl(*CatchParam);
5429 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005430 }
5431
5432 CGF.ObjCEHValueStack.push_back(ExcObject);
5433 CGF.EmitStmt(CatchBody);
5434 CGF.ObjCEHValueStack.pop_back();
5435
5436 CGF.EmitBranchThroughCleanup(FinallyEnd);
5437
5438 CGF.EmitBlock(MatchHandler);
5439
5440 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5441 // We are required to emit this call to satisfy LLVM, even
5442 // though we don't use the result.
5443 llvm::SmallVector<llvm::Value*, 8> Args;
5444 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005445 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005446 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5447 0));
5448 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5449 CGF.Builder.CreateStore(Exc, RethrowPtr);
5450 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5451
5452 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5453
5454 CGF.EmitBlock(MatchEnd);
5455
5456 // Unfortunately, we also have to generate another EH frame here
5457 // in case this throws.
5458 llvm::BasicBlock *MatchEndHandler =
5459 CGF.createBasicBlock("match.end.handler");
5460 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5461 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5462 Cont, MatchEndHandler,
5463 Args.begin(), Args.begin());
5464
5465 CGF.EmitBlock(Cont);
5466 if (Info.SwitchBlock)
5467 CGF.EmitBlock(Info.SwitchBlock);
5468 if (Info.EndBlock)
5469 CGF.EmitBlock(Info.EndBlock);
5470
5471 CGF.EmitBlock(MatchEndHandler);
5472 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5473 // We are required to emit this call to satisfy LLVM, even
5474 // though we don't use the result.
5475 Args.clear();
5476 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005477 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005478 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5479 0));
5480 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5481 CGF.Builder.CreateStore(Exc, RethrowPtr);
5482 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5483
5484 if (Next)
5485 CGF.EmitBlock(Next);
5486 } else {
5487 assert(!Next && "catchup should be last handler.");
5488
5489 CGF.Builder.CreateStore(Exc, RethrowPtr);
5490 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5491 }
5492 }
5493
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005494 // Pop the cleanup entry, the @finally is outside this cleanup
5495 // scope.
5496 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5497 CGF.setInvokeDest(PrevLandingPad);
5498
5499 CGF.EmitBlock(FinallyBlock);
5500
5501 if (isTry) {
5502 if (const ObjCAtFinallyStmt* FinallyStmt =
5503 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5504 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5505 } else {
5506 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5507 // @synchronized.
5508 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005509 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005510
5511 if (Info.SwitchBlock)
5512 CGF.EmitBlock(Info.SwitchBlock);
5513 if (Info.EndBlock)
5514 CGF.EmitBlock(Info.EndBlock);
5515
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005516 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005517 CGF.EmitBranch(FinallyEnd);
5518
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005519 CGF.EmitBlock(FinallyRethrow);
5520 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5521 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005522 CGF.Builder.CreateUnreachable();
5523
5524 CGF.EmitBlock(FinallyEnd);
5525}
5526
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005527/// EmitThrowStmt - Generate code for a throw statement.
5528void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5529 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005530 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005531 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005532 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005533 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005534 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5535 "Unexpected rethrow outside @catch block.");
5536 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005537 }
5538
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005539 llvm::Value *ExceptionAsObject =
5540 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5541 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5542 if (InvokeDest) {
5543 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5544 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5545 Cont, InvokeDest,
5546 &ExceptionAsObject, &ExceptionAsObject + 1);
5547 CGF.EmitBlock(Cont);
5548 } else
5549 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5550 CGF.Builder.CreateUnreachable();
5551
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005552 // Clear the insertion point to indicate we are in unreachable code.
5553 CGF.Builder.ClearInsertionPoint();
5554}
Daniel Dunbare588b992009-03-01 04:46:24 +00005555
5556llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005557CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5558 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005559 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005560
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005561 // If we don't need a definition, return the entry if found or check
5562 // if we use an external reference.
5563 if (!ForDefinition) {
5564 if (Entry)
5565 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005566
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005567 // If this type (or a super class) has the __objc_exception__
5568 // attribute, emit an external reference.
5569 if (hasObjCExceptionAttribute(ID))
5570 return Entry =
5571 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5572 llvm::GlobalValue::ExternalLinkage,
5573 0,
5574 (std::string("OBJC_EHTYPE_$_") +
5575 ID->getIdentifier()->getName()),
5576 &CGM.getModule());
5577 }
5578
5579 // Otherwise we need to either make a new entry or fill in the
5580 // initializer.
5581 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005582 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005583 std::string VTableName = "objc_ehtype_vtable";
5584 llvm::GlobalVariable *VTableGV =
5585 CGM.getModule().getGlobalVariable(VTableName);
5586 if (!VTableGV)
5587 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5588 llvm::GlobalValue::ExternalLinkage,
5589 0, VTableName, &CGM.getModule());
5590
5591 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5592
5593 std::vector<llvm::Constant*> Values(3);
5594 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5595 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005596 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005597 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5598
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005599 if (Entry) {
5600 Entry->setInitializer(Init);
5601 } else {
5602 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5603 llvm::GlobalValue::WeakAnyLinkage,
5604 Init,
5605 (std::string("OBJC_EHTYPE_$_") +
5606 ID->getIdentifier()->getName()),
5607 &CGM.getModule());
5608 }
5609
Daniel Dunbar04d40782009-04-14 06:00:08 +00005610 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005611 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005612 Entry->setAlignment(8);
5613
5614 if (ForDefinition) {
5615 Entry->setSection("__DATA,__objc_const");
5616 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5617 } else {
5618 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5619 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005620
5621 return Entry;
5622}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005623
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005624/* *** */
5625
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005626CodeGen::CGObjCRuntime *
5627CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005628 return new CGObjCMac(CGM);
5629}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005630
5631CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005632CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005633 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005634}