blob: cf2d8da022ea36ad79b7911f0911b12a1a2f6f46 [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
492 /// llvm.
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();
713
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.
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000771 llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
772 bool AddToUsed = true);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000773
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000774 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
775 /// for the given class.
776 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000777 const ObjCInterfaceDecl *ID,
778 bool IsSuper = false);
779
780 /// EmitMetaClassRef - Return a Value * of the address of _class_t
781 /// meta-data
782 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
783 const ObjCInterfaceDecl *ID);
784
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000785 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
786 /// the given ivar.
787 ///
788 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000789 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000790 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000791
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000792 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
793 /// for the given selector.
794 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000795
796 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
797 /// interface. The return value has type EHTypePtrTy.
798 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
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
892/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000893
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000894CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
895 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000896{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000897 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000898 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000899}
900
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000901/// GetClass - Return a reference to the class for the given interface
902/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000903llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000904 const ObjCInterfaceDecl *ID) {
905 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000906}
907
908/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000909llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000910 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000911}
912
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000913/// Generate a constant CFString object.
914/*
915 struct __builtin_CFString {
916 const int *isa; // point to __CFConstantStringClassReference
917 int flags;
918 const char *str;
919 long length;
920 };
921*/
922
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000923llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000924 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000925 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000926}
927
928/// Generates a message send where the super is the receiver. This is
929/// a message send to self with special delivery semantics indicating
930/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000931CodeGen::RValue
932CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000933 QualType ResultType,
934 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000935 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000936 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000937 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000938 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000939 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000940 // Create and init a super structure; this is a (receiver, class)
941 // pair we will pass to objc_msgSendSuper.
942 llvm::Value *ObjCSuper =
943 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
944 llvm::Value *ReceiverAsObject =
945 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
946 CGF.Builder.CreateStore(ReceiverAsObject,
947 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000948
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000949 // If this is a class message the metaclass is passed as the target.
950 llvm::Value *Target;
951 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000952 if (isCategoryImpl) {
953 // Message sent to 'super' in a class method defined in a category
954 // implementation requires an odd treatment.
955 // If we are in a class method, we must retrieve the
956 // _metaclass_ for the current class, pointed at by
957 // the class's "isa" pointer. The following assumes that
958 // isa" is the first ivar in a class (which it must be).
959 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
960 Target = CGF.Builder.CreateStructGEP(Target, 0);
961 Target = CGF.Builder.CreateLoad(Target);
962 }
963 else {
964 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
965 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
966 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
967 Target = Super;
968 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000969 } else {
970 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
971 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000972 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
973 // and ObjCTypes types.
974 const llvm::Type *ClassTy =
975 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000976 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000977 CGF.Builder.CreateStore(Target,
978 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
979
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000980 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000981 ObjCSuper, ObjCTypes.SuperPtrCTy,
982 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000983}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000984
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000985/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000986CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000987 QualType ResultType,
988 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000989 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000990 bool IsClassMessage,
991 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000992 llvm::Value *Arg0 =
993 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000994 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000995 Arg0, CGF.getContext().getObjCIdType(),
996 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000997}
998
999CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001000 QualType ResultType,
1001 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001002 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001003 QualType Arg0Ty,
1004 bool IsSuper,
1005 const CallArgList &CallArgs) {
1006 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001007 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1008 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1009 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001010 CGF.getContext().getObjCSelType()));
1011 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001012
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001013 CodeGenTypes &Types = CGM.getTypes();
1014 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1015 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001016
1017 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001018 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001019 Fn = ObjCTypes.getSendStretFn(IsSuper);
1020 } else if (ResultType->isFloatingType()) {
1021 // FIXME: Sadly, this is wrong. This actually depends on the
1022 // architecture. This happens to be right for x86-32 though.
1023 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1024 } else {
1025 Fn = ObjCTypes.getSendFn(IsSuper);
1026 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001027 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001028 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001029}
1030
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001031llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001032 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001033 // FIXME: I don't understand why gcc generates this, or where it is
1034 // resolved. Investigate. Its also wasteful to look this up over and
1035 // over.
1036 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1037
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001038 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1039 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001040}
1041
Fariborz Jahanianda320092009-01-29 19:24:30 +00001042void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001043 // FIXME: We shouldn't need this, the protocol decl should contain
1044 // enough information to tell us whether this was a declaration or a
1045 // definition.
1046 DefinedProtocols.insert(PD->getIdentifier());
1047
1048 // If we have generated a forward reference to this protocol, emit
1049 // it now. Otherwise do nothing, the protocol objects are lazily
1050 // emitted.
1051 if (Protocols.count(PD->getIdentifier()))
1052 GetOrEmitProtocol(PD);
1053}
1054
Fariborz Jahanianda320092009-01-29 19:24:30 +00001055llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001056 if (DefinedProtocols.count(PD->getIdentifier()))
1057 return GetOrEmitProtocol(PD);
1058 return GetOrEmitProtocolRef(PD);
1059}
1060
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001061/*
1062 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1063 struct _objc_protocol {
1064 struct _objc_protocol_extension *isa;
1065 char *protocol_name;
1066 struct _objc_protocol_list *protocol_list;
1067 struct _objc__method_prototype_list *instance_methods;
1068 struct _objc__method_prototype_list *class_methods
1069 };
1070
1071 See EmitProtocolExtension().
1072*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001073llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1074 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1075
1076 // Early exit if a defining object has already been generated.
1077 if (Entry && Entry->hasInitializer())
1078 return Entry;
1079
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001080 // FIXME: I don't understand why gcc generates this, or where it is
1081 // resolved. Investigate. Its also wasteful to look this up over and
1082 // over.
1083 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1084
Chris Lattner8ec03f52008-11-24 03:54:41 +00001085 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001086
1087 // Construct method lists.
1088 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1089 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1090 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1091 e = PD->instmeth_end(); i != e; ++i) {
1092 ObjCMethodDecl *MD = *i;
1093 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1094 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1095 OptInstanceMethods.push_back(C);
1096 } else {
1097 InstanceMethods.push_back(C);
1098 }
1099 }
1100
1101 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1102 e = PD->classmeth_end(); i != e; ++i) {
1103 ObjCMethodDecl *MD = *i;
1104 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1105 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1106 OptClassMethods.push_back(C);
1107 } else {
1108 ClassMethods.push_back(C);
1109 }
1110 }
1111
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001112 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001113 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001114 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001115 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001116 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001117 PD->protocol_begin(),
1118 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001119 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1121 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001122 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1123 InstanceMethods);
1124 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001125 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1126 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001127 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1128 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001129 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1130 Values);
1131
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001132 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001133 // Already created, fix the linkage and update the initializer.
1134 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001135 Entry->setInitializer(Init);
1136 } else {
1137 Entry =
1138 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1139 llvm::GlobalValue::InternalLinkage,
1140 Init,
1141 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1142 &CGM.getModule());
1143 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001144 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001145 UsedGlobals.push_back(Entry);
1146 // FIXME: Is this necessary? Why only for protocol?
1147 Entry->setAlignment(4);
1148 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001149
1150 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001151}
1152
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001153llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001154 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1155
1156 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001157 // We use the initializer as a marker of whether this is a forward
1158 // reference or not. At module finalization we add the empty
1159 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001160 Entry =
1161 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001162 llvm::GlobalValue::ExternalLinkage,
1163 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001164 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001165 &CGM.getModule());
1166 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001167 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001168 UsedGlobals.push_back(Entry);
1169 // FIXME: Is this necessary? Why only for protocol?
1170 Entry->setAlignment(4);
1171 }
1172
1173 return Entry;
1174}
1175
1176/*
1177 struct _objc_protocol_extension {
1178 uint32_t size;
1179 struct objc_method_description_list *optional_instance_methods;
1180 struct objc_method_description_list *optional_class_methods;
1181 struct objc_property_list *instance_properties;
1182 };
1183*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001184llvm::Constant *
1185CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1186 const ConstantVector &OptInstanceMethods,
1187 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001188 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001189 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001190 std::vector<llvm::Constant*> Values(4);
1191 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001192 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001193 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1194 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001195 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1196 OptInstanceMethods);
1197 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001198 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1199 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001200 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1201 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001202 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1203 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001204 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001205
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001206 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001207 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1208 Values[3]->isNullValue())
1209 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1210
1211 llvm::Constant *Init =
1212 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001213
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001214 // No special section, but goes in llvm.used
1215 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1216 Init,
1217 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001218}
1219
1220/*
1221 struct objc_protocol_list {
1222 struct objc_protocol_list *next;
1223 long count;
1224 Protocol *list[];
1225 };
1226*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001227llvm::Constant *
1228CGObjCMac::EmitProtocolList(const std::string &Name,
1229 ObjCProtocolDecl::protocol_iterator begin,
1230 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001231 std::vector<llvm::Constant*> ProtocolRefs;
1232
Daniel Dunbardbc933702008-08-21 21:57:41 +00001233 for (; begin != end; ++begin)
1234 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001235
1236 // Just return null for empty protocol lists
1237 if (ProtocolRefs.empty())
1238 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1239
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001240 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001241 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1242
1243 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001244 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001245 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1246 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1247 Values[2] =
1248 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1249 ProtocolRefs.size()),
1250 ProtocolRefs);
1251
1252 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1253 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001254 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001255 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001256 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1257}
1258
1259/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001260 struct _objc_property {
1261 const char * const name;
1262 const char * const attributes;
1263 };
1264
1265 struct _objc_property_list {
1266 uint32_t entsize; // sizeof (struct _objc_property)
1267 uint32_t prop_count;
1268 struct _objc_property[prop_count];
1269 };
1270*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001271llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1272 const Decl *Container,
1273 const ObjCContainerDecl *OCD,
1274 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001275 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001276 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1277 E = OCD->prop_end(); I != E; ++I) {
1278 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001279 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001280 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001281 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1282 Prop));
1283 }
1284
1285 // Return null for empty list.
1286 if (Properties.empty())
1287 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1288
1289 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001290 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001291 std::vector<llvm::Constant*> Values(3);
1292 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1293 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1294 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1295 Properties.size());
1296 Values[2] = llvm::ConstantArray::get(AT, Properties);
1297 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1298
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001299 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001300 llvm::GlobalVariable *GV =
1301 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1302 0, true);
1303 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001304}
1305
1306/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001307 struct objc_method_description_list {
1308 int count;
1309 struct objc_method_description list[];
1310 };
1311*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001312llvm::Constant *
1313CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1314 std::vector<llvm::Constant*> Desc(2);
1315 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1316 ObjCTypes.SelectorPtrTy);
1317 Desc[1] = GetMethodVarType(MD);
1318 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1319 Desc);
1320}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001321
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001322llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1323 const char *Section,
1324 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001325 // Return null for empty list.
1326 if (Methods.empty())
1327 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1328
1329 std::vector<llvm::Constant*> Values(2);
1330 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1331 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1332 Methods.size());
1333 Values[1] = llvm::ConstantArray::get(AT, Methods);
1334 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1335
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001336 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001337 return llvm::ConstantExpr::getBitCast(GV,
1338 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001339}
1340
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001341/*
1342 struct _objc_category {
1343 char *category_name;
1344 char *class_name;
1345 struct _objc_method_list *instance_methods;
1346 struct _objc_method_list *class_methods;
1347 struct _objc_protocol_list *protocols;
1348 uint32_t size; // <rdar://4585769>
1349 struct _objc_property_list *instance_properties;
1350 };
1351 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001352void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001353 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001354
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001355 // FIXME: This is poor design, the OCD should have a pointer to the
1356 // category decl. Additionally, note that Category can be null for
1357 // the @implementation w/o an @interface case. Sema should just
1358 // create one for us as it does for @implementation so everyone else
1359 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001360 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001361 const ObjCCategoryDecl *Category =
1362 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001363 std::string ExtName(Interface->getNameAsString() + "_" +
1364 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001365
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001366 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1367 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1368 e = OCD->instmeth_end(); i != e; ++i) {
1369 // Instance methods should always be defined.
1370 InstanceMethods.push_back(GetMethodConstant(*i));
1371 }
1372 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1373 e = OCD->classmeth_end(); i != e; ++i) {
1374 // Class methods should always be defined.
1375 ClassMethods.push_back(GetMethodConstant(*i));
1376 }
1377
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001378 std::vector<llvm::Constant*> Values(7);
1379 Values[0] = GetClassName(OCD->getIdentifier());
1380 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001381 Values[2] =
1382 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1383 ExtName,
1384 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001385 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001386 Values[3] =
1387 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1388 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001389 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001390 if (Category) {
1391 Values[4] =
1392 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1393 Category->protocol_begin(),
1394 Category->protocol_end());
1395 } else {
1396 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1397 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001398 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001399
1400 // If there is no category @interface then there can be no properties.
1401 if (Category) {
1402 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001403 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001404 } else {
1405 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1406 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001407
1408 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1409 Values);
1410
1411 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001412 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1413 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001414 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001415 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001416}
1417
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001418// FIXME: Get from somewhere?
1419enum ClassFlags {
1420 eClassFlags_Factory = 0x00001,
1421 eClassFlags_Meta = 0x00002,
1422 // <rdr://5142207>
1423 eClassFlags_HasCXXStructors = 0x02000,
1424 eClassFlags_Hidden = 0x20000,
1425 eClassFlags_ABI2_Hidden = 0x00010,
1426 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1427};
1428
1429// <rdr://5142207&4705298&4843145>
1430static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1431 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1432 // FIXME: Support -fvisibility
1433 switch (attr->getVisibility()) {
1434 default:
1435 assert(0 && "Unknown visibility");
1436 return false;
1437 case VisibilityAttr::DefaultVisibility:
1438 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1439 return false;
1440 case VisibilityAttr::HiddenVisibility:
1441 return true;
1442 }
1443 } else {
1444 return false; // FIXME: Support -fvisibility
1445 }
1446}
1447
1448/*
1449 struct _objc_class {
1450 Class isa;
1451 Class super_class;
1452 const char *name;
1453 long version;
1454 long info;
1455 long instance_size;
1456 struct _objc_ivar_list *ivars;
1457 struct _objc_method_list *methods;
1458 struct _objc_cache *cache;
1459 struct _objc_protocol_list *protocols;
1460 // Objective-C 1.0 extensions (<rdr://4585769>)
1461 const char *ivar_layout;
1462 struct _objc_class_ext *ext;
1463 };
1464
1465 See EmitClassExtension();
1466 */
1467void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001468 DefinedSymbols.insert(ID->getIdentifier());
1469
Chris Lattner8ec03f52008-11-24 03:54:41 +00001470 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001471 // FIXME: Gross
1472 ObjCInterfaceDecl *Interface =
1473 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001474 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001475 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001476 Interface->protocol_begin(),
1477 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001478 const llvm::Type *InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001479 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001480 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001481 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001482
1483 // FIXME: Set CXX-structors flag.
1484 if (IsClassHidden(ID->getClassInterface()))
1485 Flags |= eClassFlags_Hidden;
1486
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001487 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1488 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1489 e = ID->instmeth_end(); i != e; ++i) {
1490 // Instance methods should always be defined.
1491 InstanceMethods.push_back(GetMethodConstant(*i));
1492 }
1493 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1494 e = ID->classmeth_end(); i != e; ++i) {
1495 // Class methods should always be defined.
1496 ClassMethods.push_back(GetMethodConstant(*i));
1497 }
1498
1499 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1500 e = ID->propimpl_end(); i != e; ++i) {
1501 ObjCPropertyImplDecl *PID = *i;
1502
1503 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1504 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1505
1506 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1507 if (llvm::Constant *C = GetMethodConstant(MD))
1508 InstanceMethods.push_back(C);
1509 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1510 if (llvm::Constant *C = GetMethodConstant(MD))
1511 InstanceMethods.push_back(C);
1512 }
1513 }
1514
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001515 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001516 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001517 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001518 // Record a reference to the super class.
1519 LazySymbols.insert(Super->getIdentifier());
1520
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001521 Values[ 1] =
1522 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1523 ObjCTypes.ClassPtrTy);
1524 } else {
1525 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1526 }
1527 Values[ 2] = GetClassName(ID->getIdentifier());
1528 // Version is always 0.
1529 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1530 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1531 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001532 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001533 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001534 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001535 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001536 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001537 // cache is always NULL.
1538 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1539 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001540 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001541 // Values[10] = BuildIvarLayout(ID, true);
1542 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001543 Values[11] = EmitClassExtension(ID);
1544 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1545 Values);
1546
1547 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001548 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1549 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001550 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001551 DefinedClasses.push_back(GV);
1552}
1553
1554llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1555 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001556 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001557 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001558 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001559 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001560
1561 if (IsClassHidden(ID->getClassInterface()))
1562 Flags |= eClassFlags_Hidden;
1563
1564 std::vector<llvm::Constant*> Values(12);
1565 // The isa for the metaclass is the root of the hierarchy.
1566 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1567 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1568 Root = Super;
1569 Values[ 0] =
1570 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1571 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001572 // The super class for the metaclass is emitted as the name of the
1573 // super class. The runtime fixes this up to point to the
1574 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001575 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1576 Values[ 1] =
1577 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1578 ObjCTypes.ClassPtrTy);
1579 } else {
1580 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1581 }
1582 Values[ 2] = GetClassName(ID->getIdentifier());
1583 // Version is always 0.
1584 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1585 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1586 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001587 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001588 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001589 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001590 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001591 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001592 // cache is always NULL.
1593 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1594 Values[ 9] = Protocols;
1595 // ivar_layout for metaclass is always NULL.
1596 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1597 // The class extension is always unused for metaclasses.
1598 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1599 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1600 Values);
1601
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001602 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001603 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001604
1605 // Check for a forward reference.
1606 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1607 if (GV) {
1608 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1609 "Forward metaclass reference has incorrect type.");
1610 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1611 GV->setInitializer(Init);
1612 } else {
1613 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1614 llvm::GlobalValue::InternalLinkage,
1615 Init, Name,
1616 &CGM.getModule());
1617 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001618 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001619 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001620 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001621
1622 return GV;
1623}
1624
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001625llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001626 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001627
1628 // FIXME: Should we look these up somewhere other than the
1629 // module. Its a bit silly since we only generate these while
1630 // processing an implementation, so exactly one pointer would work
1631 // if know when we entered/exitted an implementation block.
1632
1633 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001634 // Previously, metaclass with internal linkage may have been defined.
1635 // pass 'true' as 2nd argument so it is returned.
1636 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001637 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1638 "Forward metaclass reference has incorrect type.");
1639 return GV;
1640 } else {
1641 // Generate as an external reference to keep a consistent
1642 // module. This will be patched up when we emit the metaclass.
1643 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1644 llvm::GlobalValue::ExternalLinkage,
1645 0,
1646 Name,
1647 &CGM.getModule());
1648 }
1649}
1650
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001651/*
1652 struct objc_class_ext {
1653 uint32_t size;
1654 const char *weak_ivar_layout;
1655 struct _objc_property_list *properties;
1656 };
1657*/
1658llvm::Constant *
1659CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1660 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001661 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001662
1663 std::vector<llvm::Constant*> Values(3);
1664 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001665 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001666 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001667 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001668 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001669 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001670
1671 // Return null if no extension bits are used.
1672 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1673 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1674
1675 llvm::Constant *Init =
1676 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001677 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1678 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001679}
1680
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001681/// countInheritedIvars - count number of ivars in class and its super class(s)
1682///
1683static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1684 int count = 0;
1685 if (!OI)
1686 return 0;
1687 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1688 if (SuperClass)
1689 count += countInheritedIvars(SuperClass);
1690 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1691 E = OI->ivar_end(); I != E; ++I)
1692 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001693 // look into properties.
1694 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1695 E = OI->prop_end(); I != E; ++I) {
1696 if ((*I)->getPropertyIvarDecl())
1697 ++count;
1698 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001699 return count;
1700}
1701
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001702/// getInterfaceDeclForIvar - Get the interface declaration node where
1703/// this ivar is declared in.
1704/// FIXME. Ideally, this info should be in the ivar node. But currently
1705/// it is not and prevailing wisdom is that ASTs should not have more
1706/// info than is absolutely needed, even though this info reflects the
1707/// source language.
1708///
1709static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1710 const ObjCInterfaceDecl *OI,
1711 const ObjCIvarDecl *IVD) {
1712 if (!OI)
1713 return 0;
1714 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1715 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1716 E = OI->ivar_end(); I != E; ++I)
1717 if ((*I)->getIdentifier() == IVD->getIdentifier())
1718 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001719 // look into properties.
1720 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1721 E = OI->prop_end(); I != E; ++I) {
1722 ObjCPropertyDecl *PDecl = (*I);
1723 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1724 if (IV->getIdentifier() == IVD->getIdentifier())
1725 return OI;
1726 }
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001727 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1728}
1729
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001730/*
1731 struct objc_ivar {
1732 char *ivar_name;
1733 char *ivar_type;
1734 int ivar_offset;
1735 };
1736
1737 struct objc_ivar_list {
1738 int ivar_count;
1739 struct objc_ivar list[count];
1740 };
1741 */
1742llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001743 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001744 std::vector<llvm::Constant*> Ivars, Ivar(3);
1745
1746 // When emitting the root class GCC emits ivar entries for the
1747 // actual class structure. It is not clear if we need to follow this
1748 // behavior; for now lets try and get away with not doing it. If so,
1749 // the cleanest solution would be to make up an ObjCInterfaceDecl
1750 // for the class.
1751 if (ForClass)
1752 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001753
1754 ObjCInterfaceDecl *OID =
1755 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001756 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001757
1758 RecordDecl::field_iterator ifield, pfield;
1759 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001760 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1761 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001762 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001763 if (Field->getIdentifier())
1764 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1765 else
1766 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001767 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001768 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001769 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001770 }
1771
1772 // Return null for empty list.
1773 if (Ivars.empty())
1774 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1775
1776 std::vector<llvm::Constant*> Values(2);
1777 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1778 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1779 Ivars.size());
1780 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1781 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1782
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001783 llvm::GlobalVariable *GV;
1784 if (ForClass)
1785 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001786 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1787 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001788 else
1789 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1790 + ID->getNameAsString(),
1791 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1792 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001793 return llvm::ConstantExpr::getBitCast(GV,
1794 ObjCTypes.IvarListPtrTy);
1795}
1796
1797/*
1798 struct objc_method {
1799 SEL method_name;
1800 char *method_types;
1801 void *method;
1802 };
1803
1804 struct objc_method_list {
1805 struct objc_method_list *obsolete;
1806 int count;
1807 struct objc_method methods_list[count];
1808 };
1809*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001810
1811/// GetMethodConstant - Return a struct objc_method constant for the
1812/// given method if it has been defined. The result is null if the
1813/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001814llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001815 // FIXME: Use DenseMap::lookup
1816 llvm::Function *Fn = MethodDefinitions[MD];
1817 if (!Fn)
1818 return 0;
1819
1820 std::vector<llvm::Constant*> Method(3);
1821 Method[0] =
1822 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1823 ObjCTypes.SelectorPtrTy);
1824 Method[1] = GetMethodVarType(MD);
1825 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1826 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1827}
1828
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001829llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1830 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001831 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001832 // Return null for empty list.
1833 if (Methods.empty())
1834 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1835
1836 std::vector<llvm::Constant*> Values(3);
1837 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1838 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1839 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1840 Methods.size());
1841 Values[2] = llvm::ConstantArray::get(AT, Methods);
1842 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1843
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001844 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001845 return llvm::ConstantExpr::getBitCast(GV,
1846 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001847}
1848
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001849llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001850 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001851 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001852 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001853
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001854 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001855 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001856 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001857 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001858 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001859 llvm::GlobalValue::InternalLinkage,
1860 Name,
1861 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001862 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001863
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001864 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001865}
1866
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001867uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001868 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001869 if (!Field->isBitField())
1870 return Layout->getElementOffset(
1871 CGM.getTypes().getLLVMFieldNo(Field));
1872 // FIXME. Must be a better way of getting a bitfield base offset.
1873 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1874 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1875 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1876 offset = (offset*size)/8;
1877 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001878}
1879
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001880/// GetFieldBaseOffset - return's field byt offset.
1881uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1882 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001883 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001884 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001885 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1886 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001887}
1888
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001889llvm::GlobalVariable *
1890CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1891 llvm::Constant *Init,
1892 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001893 unsigned Align,
1894 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001895 const llvm::Type *Ty = Init->getType();
1896 llvm::GlobalVariable *GV =
1897 new llvm::GlobalVariable(Ty, false,
1898 llvm::GlobalValue::InternalLinkage,
1899 Init,
1900 Name,
1901 &CGM.getModule());
1902 if (Section)
1903 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001904 if (Align)
1905 GV->setAlignment(Align);
1906 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001907 UsedGlobals.push_back(GV);
1908 return GV;
1909}
1910
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001911llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001912 // Abuse this interface function as a place to finalize.
1913 FinishModule();
1914
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001915 return NULL;
1916}
1917
Chris Lattner74391b42009-03-22 21:03:39 +00001918llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001919 return ObjCTypes.GetPropertyFn;
1920}
1921
Chris Lattner74391b42009-03-22 21:03:39 +00001922llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001923 return ObjCTypes.SetPropertyFn;
1924}
1925
Chris Lattner74391b42009-03-22 21:03:39 +00001926llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001927 return ObjCTypes.EnumerationMutationFn;
1928}
1929
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001930/*
1931
1932Objective-C setjmp-longjmp (sjlj) Exception Handling
1933--
1934
1935The basic framework for a @try-catch-finally is as follows:
1936{
1937 objc_exception_data d;
1938 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001939 bool _call_try_exit = true;
1940
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001941 objc_exception_try_enter(&d);
1942 if (!setjmp(d.jmp_buf)) {
1943 ... try body ...
1944 } else {
1945 // exception path
1946 id _caught = objc_exception_extract(&d);
1947
1948 // enter new try scope for handlers
1949 if (!setjmp(d.jmp_buf)) {
1950 ... match exception and execute catch blocks ...
1951
1952 // fell off end, rethrow.
1953 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001954 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001955 } else {
1956 // exception in catch block
1957 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001958 _call_try_exit = false;
1959 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001960 }
1961 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001962 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001963
1964finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001965 if (_call_try_exit)
1966 objc_exception_try_exit(&d);
1967
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001968 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001969 ... dispatch to finally destination ...
1970
1971finally_rethrow:
1972 objc_exception_throw(_rethrow);
1973
1974finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001975}
1976
1977This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001978uses _rethrow to determine if objc_exception_try_exit should be called
1979and if the object should be rethrown. This breaks in the face of
1980throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001981
1982We specialize this framework for a few particular circumstances:
1983
1984 - If there are no catch blocks, then we avoid emitting the second
1985 exception handling context.
1986
1987 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1988 e)) we avoid emitting the code to rethrow an uncaught exception.
1989
1990 - FIXME: If there is no @finally block we can do a few more
1991 simplifications.
1992
1993Rethrows and Jumps-Through-Finally
1994--
1995
1996Support for implicit rethrows and jumping through the finally block is
1997handled by storing the current exception-handling context in
1998ObjCEHStack.
1999
Daniel Dunbar898d5082008-09-30 01:06:03 +00002000In order to implement proper @finally semantics, we support one basic
2001mechanism for jumping through the finally block to an arbitrary
2002destination. Constructs which generate exits from a @try or @catch
2003block use this mechanism to implement the proper semantics by chaining
2004jumps, as necessary.
2005
2006This mechanism works like the one used for indirect goto: we
2007arbitrarily assign an ID to each destination and store the ID for the
2008destination in a variable prior to entering the finally block. At the
2009end of the finally block we simply create a switch to the proper
2010destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002011
2012Code gen for @synchronized(expr) stmt;
2013Effectively generating code for:
2014objc_sync_enter(expr);
2015@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002016*/
2017
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002018void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2019 const Stmt &S) {
2020 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002021 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002022 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002023 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002024 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2025 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2026 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002027
2028 // For @synchronized, call objc_sync_enter(sync.expr). The
2029 // evaluation of the expression must occur before we enter the
2030 // @synchronized. We can safely avoid a temp here because jumps into
2031 // @synchronized are illegal & this will dominate uses.
2032 llvm::Value *SyncArg = 0;
2033 if (!isTry) {
2034 SyncArg =
2035 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2036 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002037 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002038 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002039
2040 // Push an EH context entry, used for handling rethrows and jumps
2041 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002042 CGF.PushCleanupBlock(FinallyBlock);
2043
Anders Carlsson273558f2009-02-07 21:37:21 +00002044 CGF.ObjCEHValueStack.push_back(0);
2045
Daniel Dunbar898d5082008-09-30 01:06:03 +00002046 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002047 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2048 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002049 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2050 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002051 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2052 "_call_try_exit");
2053 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2054
Anders Carlsson80f25672008-09-09 17:59:25 +00002055 // Enter a new try block and call setjmp.
2056 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2057 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2058 "jmpbufarray");
2059 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2060 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2061 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002062
Daniel Dunbar55e87422008-11-11 02:29:29 +00002063 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2064 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002065 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002066 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002067
2068 // Emit the @try block.
2069 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002070 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2071 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002072 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002073
2074 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002075 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002076
2077 // Retrieve the exception object. We may emit multiple blocks but
2078 // nothing can cross this so the value is already in SSA form.
2079 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2080 ExceptionData,
2081 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002082 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002083 if (!isTry)
2084 {
2085 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002086 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002087 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002088 }
2089 else if (const ObjCAtCatchStmt* CatchStmt =
2090 cast<ObjCAtTryStmt>(S).getCatchStmts())
2091 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002092 // Enter a new exception try block (in case a @catch block throws
2093 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002094 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002095
Anders Carlsson80f25672008-09-09 17:59:25 +00002096 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2097 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002098 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002099
Daniel Dunbar55e87422008-11-11 02:29:29 +00002100 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2101 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002102 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002103
2104 CGF.EmitBlock(CatchBlock);
2105
Daniel Dunbar55e40722008-09-27 07:03:52 +00002106 // Handle catch list. As a special case we check if everything is
2107 // matched and avoid generating code for falling off the end if
2108 // so.
2109 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002110 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002111 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002112
Steve Naroff7ba138a2009-03-03 19:52:17 +00002113 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002114 const PointerType *PT = 0;
2115
Anders Carlsson80f25672008-09-09 17:59:25 +00002116 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002117 if (!CatchParam) {
2118 AllMatched = true;
2119 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002120 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002121
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002122 // catch(id e) always matches.
2123 // FIXME: For the time being we also match id<X>; this should
2124 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002125 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002126 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002127 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002128 }
2129
Daniel Dunbar55e40722008-09-27 07:03:52 +00002130 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002131 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002132 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002133 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002134 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002135 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002136
Anders Carlssondde0a942008-09-11 09:15:33 +00002137 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002138 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002139 break;
2140 }
2141
Daniel Dunbar129271a2008-09-27 07:36:24 +00002142 assert(PT && "Unexpected non-pointer type in @catch");
2143 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002144 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002145 assert(ObjCType && "Catch parameter must have Objective-C type!");
2146
2147 // Check if the @catch block matches the exception object.
2148 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2149
Anders Carlsson80f25672008-09-09 17:59:25 +00002150 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2151 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002152
Daniel Dunbar55e87422008-11-11 02:29:29 +00002153 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002154
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002155 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002156 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002157
2158 // Emit the @catch block.
2159 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002160 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002161 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002162
2163 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002164 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002165 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002166 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002167
2168 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002169 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002170
2171 CGF.EmitBlock(NextCatchBlock);
2172 }
2173
Daniel Dunbar55e40722008-09-27 07:03:52 +00002174 if (!AllMatched) {
2175 // None of the handlers caught the exception, so store it to be
2176 // rethrown at the end of the @finally block.
2177 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002178 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002179 }
2180
2181 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002182 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002183 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2184 ExceptionData),
2185 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);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002188 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002189 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002190 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002191 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002192 }
2193
Daniel Dunbar898d5082008-09-30 01:06:03 +00002194 // Pop the exception-handling stack entry. It is important to do
2195 // this now, because the code in the @finally block is not in this
2196 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002197 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2198
Anders Carlsson273558f2009-02-07 21:37:21 +00002199 CGF.ObjCEHValueStack.pop_back();
2200
Anders Carlsson80f25672008-09-09 17:59:25 +00002201 // Emit the @finally block.
2202 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002203 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2204
2205 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2206
2207 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002208 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002209
2210 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002211 if (isTry) {
2212 if (const ObjCAtFinallyStmt* FinallyStmt =
2213 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2214 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002215 } else {
2216 // Emit objc_sync_exit(expr); as finally's sole statement for
2217 // @synchronized.
2218 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002219 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002220
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002221 // Emit the switch block
2222 if (Info.SwitchBlock)
2223 CGF.EmitBlock(Info.SwitchBlock);
2224 if (Info.EndBlock)
2225 CGF.EmitBlock(Info.EndBlock);
2226
Daniel Dunbar898d5082008-09-30 01:06:03 +00002227 CGF.EmitBlock(FinallyRethrow);
2228 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2229 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002230 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002231
2232 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002233}
2234
2235void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002236 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002237 llvm::Value *ExceptionAsObject;
2238
2239 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2240 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2241 ExceptionAsObject =
2242 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2243 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002244 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002245 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002246 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002247 }
2248
2249 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002250 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002251
2252 // Clear the insertion point to indicate we are in unreachable code.
2253 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002254}
2255
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002256/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002257/// object: objc_read_weak (id *src)
2258///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002259llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002260 llvm::Value *AddrWeakObj)
2261{
Eli Friedman8339b352009-03-07 03:57:15 +00002262 const llvm::Type* DestTy =
2263 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002264 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002265 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002266 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002267 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002268 return read_weak;
2269}
2270
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002271/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2272/// objc_assign_weak (id src, id *dst)
2273///
2274void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2275 llvm::Value *src, llvm::Value *dst)
2276{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002277 const llvm::Type * SrcTy = src->getType();
2278 if (!isa<llvm::PointerType>(SrcTy)) {
2279 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2280 assert(Size <= 8 && "does not support size > 8");
2281 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2282 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002283 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2284 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002285 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2286 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002287 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2288 src, dst, "weakassign");
2289 return;
2290}
2291
Fariborz Jahanian58626502008-11-19 00:59:10 +00002292/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2293/// objc_assign_global (id src, id *dst)
2294///
2295void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2296 llvm::Value *src, llvm::Value *dst)
2297{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002298 const llvm::Type * SrcTy = src->getType();
2299 if (!isa<llvm::PointerType>(SrcTy)) {
2300 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2301 assert(Size <= 8 && "does not support size > 8");
2302 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2303 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002304 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2305 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002306 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2307 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002308 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2309 src, dst, "globalassign");
2310 return;
2311}
2312
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002313/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2314/// objc_assign_ivar (id src, id *dst)
2315///
2316void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2317 llvm::Value *src, llvm::Value *dst)
2318{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002319 const llvm::Type * SrcTy = src->getType();
2320 if (!isa<llvm::PointerType>(SrcTy)) {
2321 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2322 assert(Size <= 8 && "does not support size > 8");
2323 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2324 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002325 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2326 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002327 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2328 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2329 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2330 src, dst, "assignivar");
2331 return;
2332}
2333
Fariborz Jahanian58626502008-11-19 00:59:10 +00002334/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2335/// objc_assign_strongCast (id src, id *dst)
2336///
2337void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2338 llvm::Value *src, llvm::Value *dst)
2339{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002340 const llvm::Type * SrcTy = src->getType();
2341 if (!isa<llvm::PointerType>(SrcTy)) {
2342 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2343 assert(Size <= 8 && "does not support size > 8");
2344 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2345 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002346 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2347 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002348 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2349 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002350 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2351 src, dst, "weakassign");
2352 return;
2353}
2354
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002355/// EmitObjCValueForIvar - Code Gen for ivar reference.
2356///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002357LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2358 QualType ObjectTy,
2359 llvm::Value *BaseValue,
2360 const ObjCIvarDecl *Ivar,
2361 const FieldDecl *Field,
2362 unsigned CVRQualifiers) {
2363 if (Ivar->isBitField())
2364 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2365 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002366 // TODO: Add a special case for isa (index 0)
2367 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2368 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002369 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002370 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2371 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002372 LValue::SetObjCIvar(LV, true);
2373 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002374}
2375
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002376llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2377 ObjCInterfaceDecl *Interface,
2378 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002379 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002380 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002381 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002382 return llvm::ConstantInt::get(
2383 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2384 Offset);
2385}
2386
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002387/* *** Private Interface *** */
2388
2389/// EmitImageInfo - Emit the image info marker used to encode some module
2390/// level information.
2391///
2392/// See: <rdr://4810609&4810587&4810587>
2393/// struct IMAGE_INFO {
2394/// unsigned version;
2395/// unsigned flags;
2396/// };
2397enum ImageInfoFlags {
2398 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2399 eImageInfo_GarbageCollected = (1 << 1),
2400 eImageInfo_GCOnly = (1 << 2)
2401};
2402
2403void CGObjCMac::EmitImageInfo() {
2404 unsigned version = 0; // Version is unused?
2405 unsigned flags = 0;
2406
2407 // FIXME: Fix and continue?
2408 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2409 flags |= eImageInfo_GarbageCollected;
2410 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2411 flags |= eImageInfo_GCOnly;
2412
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002413 // Emitted as int[2];
2414 llvm::Constant *values[2] = {
2415 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2416 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2417 };
2418 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002419
2420 const char *Section;
2421 if (ObjCABI == 1)
2422 Section = "__OBJC, __image_info,regular";
2423 else
2424 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002425 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002426 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2427 llvm::ConstantArray::get(AT, values, 2),
2428 Section,
2429 0,
2430 true);
2431 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002432}
2433
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002434
2435// struct objc_module {
2436// unsigned long version;
2437// unsigned long size;
2438// const char *name;
2439// Symtab symtab;
2440// };
2441
2442// FIXME: Get from somewhere
2443static const int ModuleVersion = 7;
2444
2445void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002446 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002447
2448 std::vector<llvm::Constant*> Values(4);
2449 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2450 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002451 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002452 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002453 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002454 CreateMetadataVar("\01L_OBJC_MODULES",
2455 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2456 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002457 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002458}
2459
2460llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002461 unsigned NumClasses = DefinedClasses.size();
2462 unsigned NumCategories = DefinedCategories.size();
2463
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002464 // Return null if no symbols were defined.
2465 if (!NumClasses && !NumCategories)
2466 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2467
2468 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002469 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2470 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2471 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2472 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2473
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002474 // The runtime expects exactly the list of defined classes followed
2475 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002476 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002477 for (unsigned i=0; i<NumClasses; i++)
2478 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2479 ObjCTypes.Int8PtrTy);
2480 for (unsigned i=0; i<NumCategories; i++)
2481 Symbols[NumClasses + i] =
2482 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2483 ObjCTypes.Int8PtrTy);
2484
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002485 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002486 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002487 NumClasses + NumCategories),
2488 Symbols);
2489
2490 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2491
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002492 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002493 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2494 "__OBJC,__symbols,regular,no_dead_strip",
2495 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002496 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2497}
2498
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002499llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002500 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002501 LazySymbols.insert(ID->getIdentifier());
2502
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002503 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2504
2505 if (!Entry) {
2506 llvm::Constant *Casted =
2507 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2508 ObjCTypes.ClassPtrTy);
2509 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002510 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2511 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2512 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002513 }
2514
2515 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002516}
2517
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002518llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002519 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2520
2521 if (!Entry) {
2522 llvm::Constant *Casted =
2523 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2524 ObjCTypes.SelectorPtrTy);
2525 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002526 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2527 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2528 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002529 }
2530
2531 return Builder.CreateLoad(Entry, false, "tmp");
2532}
2533
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002534llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002535 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002536
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002537 if (!Entry)
2538 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2539 llvm::ConstantArray::get(Ident->getName()),
2540 "__TEXT,__cstring,cstring_literals",
2541 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002542
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002543 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002544}
2545
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002546/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2547/// interface declaration.
2548const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2549 const ObjCInterfaceDecl *OID) const {
2550 const llvm::Type *InterfaceTy =
2551 CGM.getTypes().ConvertType(
2552 CGM.getContext().getObjCInterfaceType(
2553 const_cast<ObjCInterfaceDecl*>(OID)));
2554 const llvm::StructLayout *Layout =
2555 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2556 return Layout;
2557}
2558
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002559/// GetIvarLayoutName - Returns a unique constant for the given
2560/// ivar layout bitmap.
2561llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2562 const ObjCCommonTypesHelper &ObjCTypes) {
2563 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2564}
2565
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002566void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2567 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002568 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002569 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002570 unsigned int BytePos, bool ForStrongLayout,
2571 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002572 bool IsUnion = (RD && RD->isUnion());
2573 uint64_t MaxUnionIvarSize = 0;
2574 uint64_t MaxSkippedUnionIvarSize = 0;
2575 FieldDecl *MaxField = 0;
2576 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002577 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002578 if (RecFields.empty())
2579 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002580 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002581 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002582 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2583 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2584
2585 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2586
2587 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002588 FieldDecl *Field = RecFields[i];
2589 // Skip over unnamed or bitfields
2590 if (!Field->getIdentifier() || Field->isBitField())
2591 continue;
2592 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002593 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002594 if (FQT->isUnionType())
2595 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002596 else
2597 assert(FQT->isRecordType() &&
2598 "only union/record is supported for ivar layout bitmap");
2599
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002600 const RecordType *RT = FQT->getAsRecordType();
2601 const RecordDecl *RD = RT->getDecl();
2602 // FIXME - Find a more efficiant way of passing records down.
Chris Lattnerf1690852009-03-31 08:48:01 +00002603 TmpRecFields.append(RD->field_begin(), RD->field_end());
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002604 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002605 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002606 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002607 ForStrongLayout, Index, SkIndex,
2608 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002609 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002610 continue;
2611 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002612
2613 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002614 const ConstantArrayType *CArray =
2615 dyn_cast_or_null<ConstantArrayType>(Array);
2616 assert(CArray && "only array with know element size is supported");
2617 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002618 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2619 const ConstantArrayType *CArray =
2620 dyn_cast_or_null<ConstantArrayType>(Array);
2621 FQT = CArray->getElementType();
2622 }
2623
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002624 assert(!FQT->isUnionType() &&
2625 "layout for array of unions not supported");
2626 if (FQT->isRecordType()) {
2627 uint64_t ElCount = CArray->getSize().getZExtValue();
2628 int OldIndex = Index;
2629 int OldSkIndex = SkIndex;
2630
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002631 // FIXME - Use a common routine with the above!
2632 const RecordType *RT = FQT->getAsRecordType();
2633 const RecordDecl *RD = RT->getDecl();
2634 // FIXME - Find a more efficiant way of passing records down.
Chris Lattnerf1690852009-03-31 08:48:01 +00002635 TmpRecFields.append(RD->field_begin(), RD->field_end());
2636
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002637 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002638 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002639 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002640 ForStrongLayout, Index, SkIndex,
2641 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002642 TmpRecFields.clear();
2643
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002644 // Replicate layout information for each array element. Note that
2645 // one element is already done.
2646 uint64_t ElIx = 1;
2647 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2648 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002649 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002650 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2651 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002652 GC_IVAR gcivar;
2653 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2654 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2655 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002656 }
2657
Chris Lattnerf1690852009-03-31 08:48:01 +00002658 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002659 GC_IVAR skivar;
2660 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2661 skivar.ivar_size = SkipIvars[i].ivar_size;
2662 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002663 }
2664 }
2665 continue;
2666 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002667 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002668 // At this point, we are done with Record/Union and array there of.
2669 // For other arrays we are down to its element type.
2670 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2671 do {
2672 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2673 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2674 break;
2675 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002676 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002677 GCAttr = QualType::Strong;
2678 break;
2679 }
2680 else if (const PointerType *PT = FQT->getAsPointerType()) {
2681 FQT = PT->getPointeeType();
2682 }
2683 else {
2684 break;
2685 }
2686 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002687
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002688 if ((ForStrongLayout && GCAttr == QualType::Strong)
2689 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2690 if (IsUnion)
2691 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002692 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2693 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002694 if (UnionIvarSize > MaxUnionIvarSize)
2695 {
2696 MaxUnionIvarSize = UnionIvarSize;
2697 MaxField = Field;
2698 }
2699 }
2700 else
2701 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002702 GC_IVAR gcivar;
2703 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2704 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2705 WordSizeInBits;
2706 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002707 }
2708 }
2709 else if ((ForStrongLayout &&
2710 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2711 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2712 if (IsUnion)
2713 {
2714 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2715 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2716 {
2717 MaxSkippedUnionIvarSize = UnionIvarSize;
2718 MaxSkippedField = Field;
2719 }
2720 }
2721 else
2722 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002723 GC_IVAR skivar;
2724 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2725 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2726 WordSizeInBits;
2727 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002728 }
2729 }
2730 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002731 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002732 GC_IVAR gcivar;
2733 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2734 gcivar.ivar_size = MaxUnionIvarSize;
2735 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002736 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002737
2738 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002739 GC_IVAR skivar;
2740 skivar.ivar_bytepos = BytePos +
2741 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2742 skivar.ivar_size = MaxSkippedUnionIvarSize;
2743 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002744 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002745}
2746
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002747static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002748IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002749{
2750 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2751 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2752
2753 if (sa < sb)
2754 return -1;
2755 if (sa > sb)
2756 return 1;
2757 return 0;
2758}
2759
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002760/// BuildIvarLayout - Builds ivar layout bitmap for the class
2761/// implementation for the __strong or __weak case.
2762/// The layout map displays which words in ivar list must be skipped
2763/// and which must be scanned by GC (see below). String is built of bytes.
2764/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2765/// of words to skip and right nibble is count of words to scan. So, each
2766/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2767/// represented by a 0x00 byte which also ends the string.
2768/// 1. when ForStrongLayout is true, following ivars are scanned:
2769/// - id, Class
2770/// - object *
2771/// - __strong anything
2772///
2773/// 2. When ForStrongLayout is false, following ivars are scanned:
2774/// - __weak anything
2775///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002776llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002777 const ObjCImplementationDecl *OMD,
2778 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002779 int Index = -1;
2780 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002781 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002782 int SkipScan;
2783 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002784 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2785 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2786 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002787
Chris Lattnerf1690852009-03-31 08:48:01 +00002788 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002789 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002790 CGM.getContext().CollectObjCIvars(OI, RecFields);
2791 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002792 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002793
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002794 SkipIvars.clear();
2795 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002796
2797 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002798 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2799 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002800 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002801 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002802
2803 // Sort on byte position in case we encounterred a union nested in
2804 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002805 if (hasUnion && !IvarsInfo.empty())
2806 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2807 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002808 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2809
2810 // Build the string of skip/scan nibbles
2811 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002813 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002814 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002815 if (IvarsInfo[0].ivar_bytepos == 0) {
2816 WordsToSkip = 0;
2817 WordsToScan = IvarsInfo[0].ivar_size;
2818 }
2819 else {
2820 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2821 WordsToScan = IvarsInfo[0].ivar_size;
2822 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002823 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002824 {
2825 unsigned int TailPrevGCObjC =
2826 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2827 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2828 {
2829 // consecutive 'scanned' object pointers.
2830 WordsToScan += IvarsInfo[i].ivar_size;
2831 }
2832 else
2833 {
2834 // Skip over 'gc'able object pointer which lay over each other.
2835 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2836 continue;
2837 // Must skip over 1 or more words. We save current skip/scan values
2838 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002839 SKIP_SCAN SkScan;
2840 SkScan.skip = WordsToSkip;
2841 SkScan.scan = WordsToScan;
2842 SkipScanIvars.push_back(SkScan); ++SkipScan;
2843
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002844 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002845 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2846 SkScan.scan = 0;
2847 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002848 WordsToSkip = 0;
2849 WordsToScan = IvarsInfo[i].ivar_size;
2850 }
2851 }
2852 if (WordsToScan > 0)
2853 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002854 SKIP_SCAN SkScan;
2855 SkScan.skip = WordsToSkip;
2856 SkScan.scan = WordsToScan;
2857 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002858 }
2859
2860 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002861 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002862 {
2863 int LastByteSkipped =
2864 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2865 int LastByteScanned =
2866 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2867 BytesSkipped = (LastByteSkipped > LastByteScanned);
2868 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2869 if (BytesSkipped)
2870 {
2871 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002872 SKIP_SCAN SkScan;
2873 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2874 SkScan.scan = 0;
2875 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002876 }
2877 }
2878 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2879 // as 0xMN.
2880 for (int i = 0; i <= SkipScan; i++)
2881 {
2882 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2883 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2884 // 0xM0 followed by 0x0N detected.
2885 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2886 for (int j = i+1; j < SkipScan; j++)
2887 SkipScanIvars[j] = SkipScanIvars[j+1];
2888 --SkipScan;
2889 }
2890 }
2891
2892 // Generate the string.
2893 std::string BitMap;
2894 for (int i = 0; i <= SkipScan; i++)
2895 {
2896 unsigned char byte;
2897 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2898 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2899 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2900 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2901
2902 if (skip_small > 0 || skip_big > 0)
2903 BytesSkipped = true;
2904 // first skip big.
2905 for (unsigned int ix = 0; ix < skip_big; ix++)
2906 BitMap += (unsigned char)(0xf0);
2907
2908 // next (skip small, scan)
2909 if (skip_small)
2910 {
2911 byte = skip_small << 4;
2912 if (scan_big > 0)
2913 {
2914 byte |= 0xf;
2915 --scan_big;
2916 }
2917 else if (scan_small)
2918 {
2919 byte |= scan_small;
2920 scan_small = 0;
2921 }
2922 BitMap += byte;
2923 }
2924 // next scan big
2925 for (unsigned int ix = 0; ix < scan_big; ix++)
2926 BitMap += (unsigned char)(0x0f);
2927 // last scan small
2928 if (scan_small)
2929 {
2930 byte = scan_small;
2931 BitMap += byte;
2932 }
2933 }
2934 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002935 unsigned char zero = 0;
2936 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002937 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2938 // final layout.
2939 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002940 return llvm::Constant::getNullValue(PtrTy);
2941 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2942 llvm::ConstantArray::get(BitMap.c_str()),
2943 "__TEXT,__cstring,cstring_literals",
2944 0, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002945 // FIXME. Need a commomand-line option for this eventually.
2946 if (ForStrongLayout)
2947 printf("\nstrong ivar layout: ");
2948 else
2949 printf("\nweak ivar layout: ");
2950 const unsigned char *s = (unsigned char*)BitMap.c_str();
2951 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002952 if (!(s[i] & 0xf0))
2953 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2954 else
2955 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002956 printf("\n");
2957
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002958 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002959}
2960
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002961llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002962 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2963
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002964 // FIXME: Avoid std::string copying.
2965 if (!Entry)
2966 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2967 llvm::ConstantArray::get(Sel.getAsString()),
2968 "__TEXT,__cstring,cstring_literals",
2969 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002970
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002971 return getConstantGEP(Entry, 0, 0);
2972}
2973
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002974// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002975llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002976 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2977}
2978
2979// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002980llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002981 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2982}
2983
Devang Patel7794bb82009-03-04 18:21:39 +00002984llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2985 std::string TypeStr;
2986 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2987
2988 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002989
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002990 if (!Entry)
2991 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2992 llvm::ConstantArray::get(TypeStr),
2993 "__TEXT,__cstring,cstring_literals",
2994 0, true);
2995
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002996 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002997}
2998
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002999llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003000 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003001 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3002 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003003
3004 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3005
3006 if (!Entry) {
3007 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
3008 Entry =
3009 new llvm::GlobalVariable(C->getType(), false,
3010 llvm::GlobalValue::InternalLinkage,
3011 C, "\01L_OBJC_METH_VAR_TYPE_",
3012 &CGM.getModule());
3013 Entry->setSection("__TEXT,__cstring,cstring_literals");
3014 UsedGlobals.push_back(Entry);
3015 }
3016
3017 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003018}
3019
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003020// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003021llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003022 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3023
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003024 if (!Entry)
3025 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3026 llvm::ConstantArray::get(Ident->getName()),
3027 "__TEXT,__cstring,cstring_literals",
3028 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003029
3030 return getConstantGEP(Entry, 0, 0);
3031}
3032
3033// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003034// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003035llvm::Constant *
3036 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3037 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003038 std::string TypeStr;
3039 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003040 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3041}
3042
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003043void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3044 const ObjCContainerDecl *CD,
3045 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003046 NameOut = '\01';
3047 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003048 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003049 assert (CD && "Missing container decl in GetNameForMethod");
3050 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00003051 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
3052 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00003053 NameOut += ' ';
3054 NameOut += D->getSelector().getAsString();
3055 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003056}
3057
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003058/// GetFirstIvarInRecord - This routine returns the record for the
3059/// implementation of the fiven class OID. It also returns field
3060/// corresponding to the first ivar in the class in FIV. It also
3061/// returns the one before the first ivar.
3062///
3063const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3064 const ObjCInterfaceDecl *OID,
3065 RecordDecl::field_iterator &FIV,
3066 RecordDecl::field_iterator &PIV) {
3067 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
3068 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
3069 RecordDecl::field_iterator ifield = RD->field_begin();
3070 RecordDecl::field_iterator pfield = RD->field_end();
3071 while (countSuperClassIvars-- > 0) {
3072 pfield = ifield;
3073 ++ifield;
3074 }
3075 FIV = ifield;
3076 PIV = pfield;
3077 return RD;
3078}
3079
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003080void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003081 EmitModuleInfo();
3082
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003083 // Emit the dummy bodies for any protocols which were referenced but
3084 // never defined.
3085 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3086 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3087 if (i->second->hasInitializer())
3088 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003089
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003090 std::vector<llvm::Constant*> Values(5);
3091 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3092 Values[1] = GetClassName(i->first);
3093 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3094 Values[3] = Values[4] =
3095 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3096 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3097 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3098 Values));
3099 }
3100
3101 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003102 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003103 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003104 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003105 }
3106
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003107 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003108 llvm::GlobalValue *GV =
3109 new llvm::GlobalVariable(AT, false,
3110 llvm::GlobalValue::AppendingLinkage,
3111 llvm::ConstantArray::get(AT, Used),
3112 "llvm.used",
3113 &CGM.getModule());
3114
3115 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003116
3117 // Add assembler directives to add lazy undefined symbol references
3118 // for classes which are referenced but not defined. This is
3119 // important for correct linker interaction.
3120
3121 // FIXME: Uh, this isn't particularly portable.
3122 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003123
3124 if (!CGM.getModule().getModuleInlineAsm().empty())
3125 s << "\n";
3126
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003127 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3128 e = LazySymbols.end(); i != e; ++i) {
3129 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3130 }
3131 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3132 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003133 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003134 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3135 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003136
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003137 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003138}
3139
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003140CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003141 : CGObjCCommonMac(cgm),
3142 ObjCTypes(cgm)
3143{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003144 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003145 ObjCABI = 2;
3146}
3147
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003148/* *** */
3149
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003150ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3151: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003152{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003153 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3154 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003155
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003156 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003157 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003158 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003159 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003160 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3161
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003162 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003163 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003164 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003165
3166 // FIXME: It would be nice to unify this with the opaque type, so
3167 // that the IR comes out a bit cleaner.
3168 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3169 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003170
3171 // I'm not sure I like this. The implicit coordination is a bit
3172 // gross. We should solve this in a reasonable fashion because this
3173 // is a pretty common task (match some runtime data structure with
3174 // an LLVM data structure).
3175
3176 // FIXME: This is leaked.
3177 // FIXME: Merge with rewriter code?
3178
3179 // struct _objc_super {
3180 // id self;
3181 // Class cls;
3182 // }
3183 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3184 SourceLocation(),
3185 &Ctx.Idents.get("_objc_super"));
3186 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3187 Ctx.getObjCIdType(), 0, false));
3188 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3189 Ctx.getObjCClassType(), 0, false));
3190 RD->completeDefinition(Ctx);
3191
3192 SuperCTy = Ctx.getTagDeclType(RD);
3193 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3194
3195 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003196 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3197
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003198 // struct _prop_t {
3199 // char *name;
3200 // char *attributes;
3201 // }
3202 PropertyTy = llvm::StructType::get(Int8PtrTy,
3203 Int8PtrTy,
3204 NULL);
3205 CGM.getModule().addTypeName("struct._prop_t",
3206 PropertyTy);
3207
3208 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003209 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003210 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003211 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003212 // }
3213 PropertyListTy = llvm::StructType::get(IntTy,
3214 IntTy,
3215 llvm::ArrayType::get(PropertyTy, 0),
3216 NULL);
3217 CGM.getModule().addTypeName("struct._prop_list_t",
3218 PropertyListTy);
3219 // struct _prop_list_t *
3220 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3221
3222 // struct _objc_method {
3223 // SEL _cmd;
3224 // char *method_type;
3225 // char *_imp;
3226 // }
3227 MethodTy = llvm::StructType::get(SelectorPtrTy,
3228 Int8PtrTy,
3229 Int8PtrTy,
3230 NULL);
3231 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003232
3233 // struct _objc_cache *
3234 CacheTy = llvm::OpaqueType::get();
3235 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3236 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003237
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003238 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003239
3240 QualType IdType = Ctx.getObjCIdType();
3241 QualType SelType = Ctx.getObjCSelType();
3242 llvm::SmallVector<QualType,16> Params;
3243 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003244
3245 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003246 Params.push_back(IdType);
3247 Params.push_back(SelType);
3248 Params.push_back(Ctx.LongTy);
3249 Params.push_back(Ctx.BoolTy);
3250 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3251 false);
3252 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003253
3254 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3255 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003256 Params.push_back(IdType);
3257 Params.push_back(SelType);
3258 Params.push_back(Ctx.LongTy);
3259 Params.push_back(IdType);
3260 Params.push_back(Ctx.BoolTy);
3261 Params.push_back(Ctx.BoolTy);
3262 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3263 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3264
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003265 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003266
3267 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003268 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003269 Params.push_back(IdType);
3270 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3271 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3272 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003273
3274 // gc's API
3275 // id objc_read_weak (id *)
3276 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003277 Params.push_back(Ctx.getPointerType(IdType));
3278 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3279 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3280
3281 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003282 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003283 Params.push_back(IdType);
3284 Params.push_back(Ctx.getPointerType(IdType));
3285
3286 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3287 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3288 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3289 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3290 GcAssignStrongCastFn =
3291 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003292
3293 // void objc_exception_throw(id)
3294 Params.clear();
3295 Params.push_back(IdType);
3296
3297 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003298 ExceptionThrowFn =
3299 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003300
3301 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003302 // void objc_sync_exit (id)
3303 Params.clear();
3304 Params.push_back(IdType);
3305
3306 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003307 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003308}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003309
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003310ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3311 : ObjCCommonTypesHelper(cgm)
3312{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003313 // struct _objc_method_description {
3314 // SEL name;
3315 // char *types;
3316 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003317 MethodDescriptionTy =
3318 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003319 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003320 NULL);
3321 CGM.getModule().addTypeName("struct._objc_method_description",
3322 MethodDescriptionTy);
3323
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003324 // struct _objc_method_description_list {
3325 // int count;
3326 // struct _objc_method_description[1];
3327 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003328 MethodDescriptionListTy =
3329 llvm::StructType::get(IntTy,
3330 llvm::ArrayType::get(MethodDescriptionTy, 0),
3331 NULL);
3332 CGM.getModule().addTypeName("struct._objc_method_description_list",
3333 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003334
3335 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003336 MethodDescriptionListPtrTy =
3337 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3338
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003339 // Protocol description structures
3340
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003341 // struct _objc_protocol_extension {
3342 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3343 // struct _objc_method_description_list *optional_instance_methods;
3344 // struct _objc_method_description_list *optional_class_methods;
3345 // struct _objc_property_list *instance_properties;
3346 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003347 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003348 llvm::StructType::get(IntTy,
3349 MethodDescriptionListPtrTy,
3350 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003351 PropertyListPtrTy,
3352 NULL);
3353 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3354 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003355
3356 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003357 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3358
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003359 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003360
3361 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3362 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3363
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003364 const llvm::Type *T =
3365 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3366 LongTy,
3367 llvm::ArrayType::get(ProtocolTyHolder, 0),
3368 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003369 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3370
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003371 // struct _objc_protocol {
3372 // struct _objc_protocol_extension *isa;
3373 // char *protocol_name;
3374 // struct _objc_protocol **_objc_protocol_list;
3375 // struct _objc_method_description_list *instance_methods;
3376 // struct _objc_method_description_list *class_methods;
3377 // }
3378 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003379 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003380 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3381 MethodDescriptionListPtrTy,
3382 MethodDescriptionListPtrTy,
3383 NULL);
3384 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3385
3386 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3387 CGM.getModule().addTypeName("struct._objc_protocol_list",
3388 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003389 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003390 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3391
3392 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003393 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003394 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003395
3396 // Class description structures
3397
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003398 // struct _objc_ivar {
3399 // char *ivar_name;
3400 // char *ivar_type;
3401 // int ivar_offset;
3402 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003403 IvarTy = llvm::StructType::get(Int8PtrTy,
3404 Int8PtrTy,
3405 IntTy,
3406 NULL);
3407 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3408
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003409 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003410 IvarListTy = llvm::OpaqueType::get();
3411 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3412 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3413
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003414 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003415 MethodListTy = llvm::OpaqueType::get();
3416 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3417 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3418
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003419 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003420 ClassExtensionTy =
3421 llvm::StructType::get(IntTy,
3422 Int8PtrTy,
3423 PropertyListPtrTy,
3424 NULL);
3425 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3426 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3427
3428 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3429
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003430 // struct _objc_class {
3431 // Class isa;
3432 // Class super_class;
3433 // char *name;
3434 // long version;
3435 // long info;
3436 // long instance_size;
3437 // struct _objc_ivar_list *ivars;
3438 // struct _objc_method_list *methods;
3439 // struct _objc_cache *cache;
3440 // struct _objc_protocol_list *protocols;
3441 // char *ivar_layout;
3442 // struct _objc_class_ext *ext;
3443 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003444 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3445 llvm::PointerType::getUnqual(ClassTyHolder),
3446 Int8PtrTy,
3447 LongTy,
3448 LongTy,
3449 LongTy,
3450 IvarListPtrTy,
3451 MethodListPtrTy,
3452 CachePtrTy,
3453 ProtocolListPtrTy,
3454 Int8PtrTy,
3455 ClassExtensionPtrTy,
3456 NULL);
3457 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3458
3459 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3460 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3461 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3462
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003463 // struct _objc_category {
3464 // char *category_name;
3465 // char *class_name;
3466 // struct _objc_method_list *instance_method;
3467 // struct _objc_method_list *class_method;
3468 // uint32_t size; // sizeof(struct _objc_category)
3469 // struct _objc_property_list *instance_properties;// category's @property
3470 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003471 CategoryTy = llvm::StructType::get(Int8PtrTy,
3472 Int8PtrTy,
3473 MethodListPtrTy,
3474 MethodListPtrTy,
3475 ProtocolListPtrTy,
3476 IntTy,
3477 PropertyListPtrTy,
3478 NULL);
3479 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3480
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003481 // Global metadata structures
3482
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003483 // struct _objc_symtab {
3484 // long sel_ref_cnt;
3485 // SEL *refs;
3486 // short cls_def_cnt;
3487 // short cat_def_cnt;
3488 // char *defs[cls_def_cnt + cat_def_cnt];
3489 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003490 SymtabTy = llvm::StructType::get(LongTy,
3491 SelectorPtrTy,
3492 ShortTy,
3493 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003494 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003495 NULL);
3496 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3497 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3498
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003499 // struct _objc_module {
3500 // long version;
3501 // long size; // sizeof(struct _objc_module)
3502 // char *name;
3503 // struct _objc_symtab* symtab;
3504 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003505 ModuleTy =
3506 llvm::StructType::get(LongTy,
3507 LongTy,
3508 Int8PtrTy,
3509 SymtabPtrTy,
3510 NULL);
3511 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003512
Daniel Dunbar49f66022008-09-24 03:38:44 +00003513 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003514
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003515 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003516 std::vector<const llvm::Type*> Params;
3517 Params.push_back(ObjectPtrTy);
3518 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003519 MessageSendFn =
3520 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3521 Params,
3522 true),
3523 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003524
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003525 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003526 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003527 Params.push_back(ObjectPtrTy);
3528 Params.push_back(SelectorPtrTy);
3529 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003530 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3531 Params,
3532 true),
3533 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003534
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003535 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003536 Params.clear();
3537 Params.push_back(ObjectPtrTy);
3538 Params.push_back(SelectorPtrTy);
3539 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003540 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003541 MessageSendFpretFn =
3542 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3543 Params,
3544 true),
3545 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003546
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003547 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003548 Params.clear();
3549 Params.push_back(SuperPtrTy);
3550 Params.push_back(SelectorPtrTy);
3551 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003552 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3553 Params,
3554 true),
3555 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003556
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003557 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3558 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003559 Params.clear();
3560 Params.push_back(Int8PtrTy);
3561 Params.push_back(SuperPtrTy);
3562 Params.push_back(SelectorPtrTy);
3563 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003564 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3565 Params,
3566 true),
3567 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003568
3569 // There is no objc_msgSendSuper_fpret? How can that work?
3570 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003571
Anders Carlsson124526b2008-09-09 10:10:21 +00003572 // FIXME: This is the size of the setjmp buffer and should be
3573 // target specific. 18 is what's used on 32-bit X86.
3574 uint64_t SetJmpBufferSize = 18;
3575
3576 // Exceptions
3577 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003578 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003579
3580 ExceptionDataTy =
3581 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3582 SetJmpBufferSize),
3583 StackPtrTy, NULL);
3584 CGM.getModule().addTypeName("struct._objc_exception_data",
3585 ExceptionDataTy);
3586
3587 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003588 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3589 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003590 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3591 Params,
3592 false),
3593 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003594 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003595 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3596 Params,
3597 false),
3598 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003599 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003600 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3601 Params,
3602 false),
3603 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003604
3605 Params.clear();
3606 Params.push_back(ClassPtrTy);
3607 Params.push_back(ObjectPtrTy);
3608 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003609 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3610 Params,
3611 false),
3612 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003613
Anders Carlsson124526b2008-09-09 10:10:21 +00003614 Params.clear();
3615 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3616 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003617 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3618 Params,
3619 false),
3620 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003621
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003622}
3623
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003624ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003625: ObjCCommonTypesHelper(cgm)
3626{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003627 // struct _method_list_t {
3628 // uint32_t entsize; // sizeof(struct _objc_method)
3629 // uint32_t method_count;
3630 // struct _objc_method method_list[method_count];
3631 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003632 MethodListnfABITy = llvm::StructType::get(IntTy,
3633 IntTy,
3634 llvm::ArrayType::get(MethodTy, 0),
3635 NULL);
3636 CGM.getModule().addTypeName("struct.__method_list_t",
3637 MethodListnfABITy);
3638 // struct method_list_t *
3639 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003640
3641 // struct _protocol_t {
3642 // id isa; // NULL
3643 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003644 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003645 // const struct method_list_t * const instance_methods;
3646 // const struct method_list_t * const class_methods;
3647 // const struct method_list_t *optionalInstanceMethods;
3648 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003649 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003650 // const uint32_t size; // sizeof(struct _protocol_t)
3651 // const uint32_t flags; // = 0
3652 // }
3653
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003654 // Holder for struct _protocol_list_t *
3655 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3656
3657 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3658 Int8PtrTy,
3659 llvm::PointerType::getUnqual(
3660 ProtocolListTyHolder),
3661 MethodListnfABIPtrTy,
3662 MethodListnfABIPtrTy,
3663 MethodListnfABIPtrTy,
3664 MethodListnfABIPtrTy,
3665 PropertyListPtrTy,
3666 IntTy,
3667 IntTy,
3668 NULL);
3669 CGM.getModule().addTypeName("struct._protocol_t",
3670 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003671
3672 // struct _protocol_t*
3673 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003674
Fariborz Jahanianda320092009-01-29 19:24:30 +00003675 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003676 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003677 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003678 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003679 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3680 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003681 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003682 NULL);
3683 CGM.getModule().addTypeName("struct._objc_protocol_list",
3684 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003685 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3686 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003687
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003688 // struct _objc_protocol_list*
3689 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003690
3691 // struct _ivar_t {
3692 // unsigned long int *offset; // pointer to ivar offset location
3693 // char *name;
3694 // char *type;
3695 // uint32_t alignment;
3696 // uint32_t size;
3697 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003698 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3699 Int8PtrTy,
3700 Int8PtrTy,
3701 IntTy,
3702 IntTy,
3703 NULL);
3704 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3705
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003706 // struct _ivar_list_t {
3707 // uint32 entsize; // sizeof(struct _ivar_t)
3708 // uint32 count;
3709 // struct _iver_t list[count];
3710 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003711 IvarListnfABITy = llvm::StructType::get(IntTy,
3712 IntTy,
3713 llvm::ArrayType::get(
3714 IvarnfABITy, 0),
3715 NULL);
3716 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3717
3718 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003719
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003720 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003721 // uint32_t const flags;
3722 // uint32_t const instanceStart;
3723 // uint32_t const instanceSize;
3724 // uint32_t const reserved; // only when building for 64bit targets
3725 // const uint8_t * const ivarLayout;
3726 // const char *const name;
3727 // const struct _method_list_t * const baseMethods;
3728 // const struct _objc_protocol_list *const baseProtocols;
3729 // const struct _ivar_list_t *const ivars;
3730 // const uint8_t * const weakIvarLayout;
3731 // const struct _prop_list_t * const properties;
3732 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003733
3734 // FIXME. Add 'reserved' field in 64bit abi mode!
3735 ClassRonfABITy = llvm::StructType::get(IntTy,
3736 IntTy,
3737 IntTy,
3738 Int8PtrTy,
3739 Int8PtrTy,
3740 MethodListnfABIPtrTy,
3741 ProtocolListnfABIPtrTy,
3742 IvarListnfABIPtrTy,
3743 Int8PtrTy,
3744 PropertyListPtrTy,
3745 NULL);
3746 CGM.getModule().addTypeName("struct._class_ro_t",
3747 ClassRonfABITy);
3748
3749 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3750 std::vector<const llvm::Type*> Params;
3751 Params.push_back(ObjectPtrTy);
3752 Params.push_back(SelectorPtrTy);
3753 ImpnfABITy = llvm::PointerType::getUnqual(
3754 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3755
3756 // struct _class_t {
3757 // struct _class_t *isa;
3758 // struct _class_t * const superclass;
3759 // void *cache;
3760 // IMP *vtable;
3761 // struct class_ro_t *ro;
3762 // }
3763
3764 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3765 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3766 llvm::PointerType::getUnqual(ClassTyHolder),
3767 CachePtrTy,
3768 llvm::PointerType::getUnqual(ImpnfABITy),
3769 llvm::PointerType::getUnqual(
3770 ClassRonfABITy),
3771 NULL);
3772 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3773
3774 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3775 ClassnfABITy);
3776
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003777 // LLVM for struct _class_t *
3778 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3779
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003780 // struct _category_t {
3781 // const char * const name;
3782 // struct _class_t *const cls;
3783 // const struct _method_list_t * const instance_methods;
3784 // const struct _method_list_t * const class_methods;
3785 // const struct _protocol_list_t * const protocols;
3786 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003787 // }
3788 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003789 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003790 MethodListnfABIPtrTy,
3791 MethodListnfABIPtrTy,
3792 ProtocolListnfABIPtrTy,
3793 PropertyListPtrTy,
3794 NULL);
3795 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003796
3797 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003798 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3799 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003800
3801 // MessageRefTy - LLVM for:
3802 // struct _message_ref_t {
3803 // IMP messenger;
3804 // SEL name;
3805 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003806
3807 // First the clang type for struct _message_ref_t
3808 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3809 SourceLocation(),
3810 &Ctx.Idents.get("_message_ref_t"));
3811 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3812 Ctx.VoidPtrTy, 0, false));
3813 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3814 Ctx.getObjCSelType(), 0, false));
3815 RD->completeDefinition(Ctx);
3816
3817 MessageRefCTy = Ctx.getTagDeclType(RD);
3818 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3819 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003820
3821 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3822 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3823
3824 // SuperMessageRefTy - LLVM for:
3825 // struct _super_message_ref_t {
3826 // SUPER_IMP messenger;
3827 // SEL name;
3828 // };
3829 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3830 SelectorPtrTy,
3831 NULL);
3832 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3833
3834 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3835 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3836
3837 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3838 Params.clear();
3839 Params.push_back(ObjectPtrTy);
3840 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003841 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3842 Params,
3843 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003844 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003845 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003846 "objc_msgSend_fixup");
3847
3848 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3849 MessageSendFpretFixupFn =
3850 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3851 Params,
3852 true),
3853 "objc_msgSend_fpret_fixup");
3854
3855 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3856 MessageSendStretFixupFn =
3857 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3858 Params,
3859 true),
3860 "objc_msgSend_stret_fixup");
3861
3862 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3863 MessageSendIdFixupFn =
3864 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3865 Params,
3866 true),
3867 "objc_msgSendId_fixup");
3868
3869
3870 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3871 MessageSendIdStretFixupFn =
3872 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3873 Params,
3874 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003875 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003876
3877 // id objc_msgSendSuper2_fixup (struct objc_super *,
3878 // struct _super_message_ref_t*, ...)
3879 Params.clear();
3880 Params.push_back(SuperPtrTy);
3881 Params.push_back(SuperMessageRefPtrTy);
3882 MessageSendSuper2FixupFn =
3883 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3884 Params,
3885 true),
3886 "objc_msgSendSuper2_fixup");
3887
3888
3889 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3890 // struct _super_message_ref_t*, ...)
3891 MessageSendSuper2StretFixupFn =
3892 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3893 Params,
3894 true),
3895 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003896
3897 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003898 Params.push_back(Int8PtrTy);
3899 UnwindResumeOrRethrowFn =
3900 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3901 Params,
3902 false),
3903 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003904 ObjCBeginCatchFn =
3905 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3906 Params,
3907 false),
3908 "objc_begin_catch");
3909
3910 Params.clear();
3911 ObjCEndCatchFn =
3912 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3913 Params,
3914 false),
3915 "objc_end_catch");
3916
3917 // struct objc_typeinfo {
3918 // const void** vtable; // objc_ehtype_vtable + 2
3919 // const char* name; // c++ typeinfo string
3920 // Class cls;
3921 // };
3922 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3923 Int8PtrTy,
3924 ClassnfABIPtrTy,
3925 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003926 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003927 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003928}
3929
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003930llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3931 FinishNonFragileABIModule();
3932
3933 return NULL;
3934}
3935
3936void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3937 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003938
3939 // Build list of all implemented classe addresses in array
3940 // L_OBJC_LABEL_CLASS_$.
3941 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3942 // list of 'nonlazy' implementations (defined as those with a +load{}
3943 // method!!).
3944 unsigned NumClasses = DefinedClasses.size();
3945 if (NumClasses) {
3946 std::vector<llvm::Constant*> Symbols(NumClasses);
3947 for (unsigned i=0; i<NumClasses; i++)
3948 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3949 ObjCTypes.Int8PtrTy);
3950 llvm::Constant* Init =
3951 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3952 NumClasses),
3953 Symbols);
3954
3955 llvm::GlobalVariable *GV =
3956 new llvm::GlobalVariable(Init->getType(), false,
3957 llvm::GlobalValue::InternalLinkage,
3958 Init,
3959 "\01L_OBJC_LABEL_CLASS_$",
3960 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003961 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003962 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3963 UsedGlobals.push_back(GV);
3964 }
3965
3966 // Build list of all implemented category addresses in array
3967 // L_OBJC_LABEL_CATEGORY_$.
3968 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3969 // list of 'nonlazy' category implementations (defined as those with a +load{}
3970 // method!!).
3971 unsigned NumCategory = DefinedCategories.size();
3972 if (NumCategory) {
3973 std::vector<llvm::Constant*> Symbols(NumCategory);
3974 for (unsigned i=0; i<NumCategory; i++)
3975 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3976 ObjCTypes.Int8PtrTy);
3977 llvm::Constant* Init =
3978 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3979 NumCategory),
3980 Symbols);
3981
3982 llvm::GlobalVariable *GV =
3983 new llvm::GlobalVariable(Init->getType(), false,
3984 llvm::GlobalValue::InternalLinkage,
3985 Init,
3986 "\01L_OBJC_LABEL_CATEGORY_$",
3987 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003988 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003989 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3990 UsedGlobals.push_back(GV);
3991 }
3992
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003993 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3994 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3995 std::vector<llvm::Constant*> Values(2);
3996 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003997 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003998 // FIXME: Fix and continue?
3999 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4000 flags |= eImageInfo_GarbageCollected;
4001 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4002 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004003 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004004 llvm::Constant* Init = llvm::ConstantArray::get(
4005 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4006 Values);
4007 llvm::GlobalVariable *IMGV =
4008 new llvm::GlobalVariable(Init->getType(), false,
4009 llvm::GlobalValue::InternalLinkage,
4010 Init,
4011 "\01L_OBJC_IMAGE_INFO",
4012 &CGM.getModule());
4013 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4014 UsedGlobals.push_back(IMGV);
4015
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004016 std::vector<llvm::Constant*> Used;
4017 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 }
4021
4022 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
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004210 bool classIsHidden = IsClassHidden(ID->getClassInterface());
4211 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004212 flags |= OBJC2_CLS_HIDDEN;
4213 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004214 // class is root
4215 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004216 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004217 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName, false);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004218 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004219 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004220 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4221 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4222 Root = Super;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004223 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString(), false);
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004224 // work on super class metadata symbol.
4225 std::string SuperClassName =
4226 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004227 SuperClassGV = GetClassGlobal(SuperClassName, false);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004228 }
4229 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4230 InstanceStart,
4231 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004232 std::string TClassName = ObjCMetaClassName + ClassName;
4233 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004234 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4235 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004236
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004237 // Metadata for the class
4238 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004239 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004240 flags |= OBJC2_CLS_HIDDEN;
4241 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004242 flags |= CLS_ROOT;
4243 SuperClassGV = 0;
4244 }
4245 else {
4246 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004247 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004248 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004249 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004250 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004251 // FIXME: Gross
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004252 InstanceStart = InstanceSize = 0;
4253 if (ObjCInterfaceDecl *OID =
4254 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4255 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004256 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004257
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004258 RecordDecl::field_iterator firstField, lastField;
4259 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004260
4261 for (RecordDecl::field_iterator e = RD->field_end(),
4262 ifield = firstField; ifield != e; ++ifield)
4263 lastField = ifield;
4264
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004265 if (lastField != RD->field_end()) {
4266 FieldDecl *Field = *lastField;
4267 const llvm::Type *FieldTy =
4268 CGM.getTypes().ConvertTypeForMem(Field->getType());
4269 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004270 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004271 if (firstField == RD->field_end())
4272 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004273 else {
4274 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004275 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004276 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004277 }
4278 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004279 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004280 InstanceStart,
4281 InstanceSize,
4282 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004283
4284 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004285 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004286 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4287 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004288 UsedGlobals.push_back(ClassMD);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004289 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004290}
4291
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004292/// GenerateProtocolRef - This routine is called to generate code for
4293/// a protocol reference expression; as in:
4294/// @code
4295/// @protocol(Proto1);
4296/// @endcode
4297/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4298/// which will hold address of the protocol meta-data.
4299///
4300llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4301 const ObjCProtocolDecl *PD) {
4302
4303 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
4304 ObjCTypes.ExternalProtocolPtrTy);
4305
4306 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4307 ProtocolName += PD->getNameAsCString();
4308
4309 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4310 if (PTGV)
4311 return Builder.CreateLoad(PTGV, false, "tmp");
4312 PTGV = new llvm::GlobalVariable(
4313 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004314 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004315 Init,
4316 ProtocolName,
4317 &CGM.getModule());
4318 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4319 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4320 UsedGlobals.push_back(PTGV);
4321 return Builder.CreateLoad(PTGV, false, "tmp");
4322}
4323
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004324/// GenerateCategory - Build metadata for a category implementation.
4325/// struct _category_t {
4326/// const char * const name;
4327/// struct _class_t *const cls;
4328/// const struct _method_list_t * const instance_methods;
4329/// const struct _method_list_t * const class_methods;
4330/// const struct _protocol_list_t * const protocols;
4331/// const struct _prop_list_t * const properties;
4332/// }
4333///
4334void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4335{
4336 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004337 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4338 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004339 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004340 std::string ExtClassName(getClassSymbolPrefix() +
4341 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004342
4343 std::vector<llvm::Constant*> Values(6);
4344 Values[0] = GetClassName(OCD->getIdentifier());
4345 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004346 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004347 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004348 std::vector<llvm::Constant*> Methods;
4349 std::string MethodListName(Prefix);
4350 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4351 "_$_" + OCD->getNameAsString();
4352
4353 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4354 e = OCD->instmeth_end(); i != e; ++i) {
4355 // Instance methods should always be defined.
4356 Methods.push_back(GetMethodConstant(*i));
4357 }
4358
4359 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004360 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004361 Methods);
4362
4363 MethodListName = Prefix;
4364 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4365 OCD->getNameAsString();
4366 Methods.clear();
4367 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4368 e = OCD->classmeth_end(); i != e; ++i) {
4369 // Class methods should always be defined.
4370 Methods.push_back(GetMethodConstant(*i));
4371 }
4372
4373 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004374 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004375 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004376 const ObjCCategoryDecl *Category =
4377 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004378 if (Category) {
4379 std::string ExtName(Interface->getNameAsString() + "_$_" +
4380 OCD->getNameAsString());
4381 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4382 + Interface->getNameAsString() + "_$_"
4383 + Category->getNameAsString(),
4384 Category->protocol_begin(),
4385 Category->protocol_end());
4386 Values[5] =
4387 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4388 OCD, Category, ObjCTypes);
4389 }
4390 else {
4391 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4392 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4393 }
4394
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004395 llvm::Constant *Init =
4396 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4397 Values);
4398 llvm::GlobalVariable *GCATV
4399 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4400 false,
4401 llvm::GlobalValue::InternalLinkage,
4402 Init,
4403 ExtCatName,
4404 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004405 GCATV->setAlignment(
4406 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004407 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004408 UsedGlobals.push_back(GCATV);
4409 DefinedCategories.push_back(GCATV);
4410}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004411
4412/// GetMethodConstant - Return a struct objc_method constant for the
4413/// given method if it has been defined. The result is null if the
4414/// method has not been defined. The return value has type MethodPtrTy.
4415llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4416 const ObjCMethodDecl *MD) {
4417 // FIXME: Use DenseMap::lookup
4418 llvm::Function *Fn = MethodDefinitions[MD];
4419 if (!Fn)
4420 return 0;
4421
4422 std::vector<llvm::Constant*> Method(3);
4423 Method[0] =
4424 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4425 ObjCTypes.SelectorPtrTy);
4426 Method[1] = GetMethodVarType(MD);
4427 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4428 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4429}
4430
4431/// EmitMethodList - Build meta-data for method declarations
4432/// struct _method_list_t {
4433/// uint32_t entsize; // sizeof(struct _objc_method)
4434/// uint32_t method_count;
4435/// struct _objc_method method_list[method_count];
4436/// }
4437///
4438llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4439 const std::string &Name,
4440 const char *Section,
4441 const ConstantVector &Methods) {
4442 // Return null for empty list.
4443 if (Methods.empty())
4444 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4445
4446 std::vector<llvm::Constant*> Values(3);
4447 // sizeof(struct _objc_method)
4448 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4449 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4450 // method_count
4451 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4452 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4453 Methods.size());
4454 Values[2] = llvm::ConstantArray::get(AT, Methods);
4455 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4456
4457 llvm::GlobalVariable *GV =
4458 new llvm::GlobalVariable(Init->getType(), false,
4459 llvm::GlobalValue::InternalLinkage,
4460 Init,
4461 Name,
4462 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004463 GV->setAlignment(
4464 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004465 GV->setSection(Section);
4466 UsedGlobals.push_back(GV);
4467 return llvm::ConstantExpr::getBitCast(GV,
4468 ObjCTypes.MethodListnfABIPtrTy);
4469}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004470
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004471/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4472/// the given ivar.
4473///
4474llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4475 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004476 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004477 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004478 Name += "\01_OBJC_IVAR_$_" +
4479 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004480 + Ivar->getNameAsString();
4481 llvm::GlobalVariable *IvarOffsetGV =
4482 CGM.getModule().getGlobalVariable(Name);
4483 if (!IvarOffsetGV)
4484 IvarOffsetGV =
4485 new llvm::GlobalVariable(ObjCTypes.LongTy,
4486 false,
4487 llvm::GlobalValue::ExternalLinkage,
4488 0,
4489 Name,
4490 &CGM.getModule());
4491 return IvarOffsetGV;
4492}
4493
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004494llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004495 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004496 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004497 unsigned long int Offset) {
4498
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004499 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004500 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004501 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004502 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004503 llvm::GlobalVariable *IvarOffsetGV =
4504 CGM.getModule().getGlobalVariable(ExternalName);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004505 if (IvarOffsetGV)
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004506 // ivar offset symbol already built due to user code referencing it.
4507 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004508 else
4509 IvarOffsetGV =
4510 new llvm::GlobalVariable(Init->getType(),
4511 false,
4512 llvm::GlobalValue::ExternalLinkage,
4513 Init,
4514 ExternalName,
4515 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004516 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004517 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004518 // @private and @package have hidden visibility.
4519 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004520 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004521 if (!globalVisibility)
4522 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004523 else if (IsClassHidden(ID))
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004524 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004525 else if (CGM.getLangOptions().getVisibilityMode() ==
4526 LangOptions::HiddenVisibility)
4527 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4528 else if (CGM.getLangOptions().getVisibilityMode() ==
4529 LangOptions::DefaultVisibility)
4530 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004531 IvarOffsetGV->setSection("__DATA, __objc_const");
4532 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004533 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004534}
4535
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004536/// EmitIvarList - Emit the ivar list for the given
4537/// implementation. If ForClass is true the list of class ivars
4538/// (i.e. metaclass ivars) is emitted, otherwise the list of
4539/// interface ivars will be emitted. The return value has type
4540/// IvarListnfABIPtrTy.
4541/// struct _ivar_t {
4542/// unsigned long int *offset; // pointer to ivar offset location
4543/// char *name;
4544/// char *type;
4545/// uint32_t alignment;
4546/// uint32_t size;
4547/// }
4548/// struct _ivar_list_t {
4549/// uint32 entsize; // sizeof(struct _ivar_t)
4550/// uint32 count;
4551/// struct _iver_t list[count];
4552/// }
4553///
4554llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4555 const ObjCImplementationDecl *ID) {
4556
4557 std::vector<llvm::Constant*> Ivars, Ivar(5);
4558
4559 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4560 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4561
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004562 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004563 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004564
4565 RecordDecl::field_iterator i,p;
4566 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004567 // collect declared and synthesized ivars in a small vector.
4568 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4569 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4570 E = OID->ivar_end(); I != E; ++I)
4571 OIvars.push_back(*I);
4572 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(),
4573 E = OID->prop_end(); I != E; ++I)
4574 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4575 OIvars.push_back(IV);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004576
Fariborz Jahanian18191882009-03-31 18:11:23 +00004577 unsigned iv = 0;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004578 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004579 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004580 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004581 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004582 if (Field->getIdentifier())
4583 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4584 else
4585 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004586 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004587 const llvm::Type *FieldTy =
4588 CGM.getTypes().ConvertTypeForMem(Field->getType());
4589 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4590 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4591 Field->getType().getTypePtr()) >> 3;
4592 Align = llvm::Log2_32(Align);
4593 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004594 // NOTE. Size of a bitfield does not match gcc's, because of the way
4595 // bitfields are treated special in each. But I am told that 'size'
4596 // for bitfield ivars is ignored by the runtime so it does not matter.
4597 // (even if it matters, some day, there is enough info. to get the bitfield
4598 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004599 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4600 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4601 }
4602 // Return null for empty list.
4603 if (Ivars.empty())
4604 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4605 std::vector<llvm::Constant*> Values(3);
4606 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4607 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4608 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4609 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4610 Ivars.size());
4611 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4612 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4613 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4614 llvm::GlobalVariable *GV =
4615 new llvm::GlobalVariable(Init->getType(), false,
4616 llvm::GlobalValue::InternalLinkage,
4617 Init,
4618 Prefix + OID->getNameAsString(),
4619 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004620 GV->setAlignment(
4621 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004622 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004623
4624 UsedGlobals.push_back(GV);
4625 return llvm::ConstantExpr::getBitCast(GV,
4626 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004627}
4628
4629llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4630 const ObjCProtocolDecl *PD) {
4631 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4632
4633 if (!Entry) {
4634 // We use the initializer as a marker of whether this is a forward
4635 // reference or not. At module finalization we add the empty
4636 // contents for protocols which were referenced but never defined.
4637 Entry =
4638 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4639 llvm::GlobalValue::ExternalLinkage,
4640 0,
4641 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4642 &CGM.getModule());
4643 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4644 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004645 }
4646
4647 return Entry;
4648}
4649
4650/// GetOrEmitProtocol - Generate the protocol meta-data:
4651/// @code
4652/// struct _protocol_t {
4653/// id isa; // NULL
4654/// const char * const protocol_name;
4655/// const struct _protocol_list_t * protocol_list; // super protocols
4656/// const struct method_list_t * const instance_methods;
4657/// const struct method_list_t * const class_methods;
4658/// const struct method_list_t *optionalInstanceMethods;
4659/// const struct method_list_t *optionalClassMethods;
4660/// const struct _prop_list_t * properties;
4661/// const uint32_t size; // sizeof(struct _protocol_t)
4662/// const uint32_t flags; // = 0
4663/// }
4664/// @endcode
4665///
4666
4667llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4668 const ObjCProtocolDecl *PD) {
4669 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4670
4671 // Early exit if a defining object has already been generated.
4672 if (Entry && Entry->hasInitializer())
4673 return Entry;
4674
4675 const char *ProtocolName = PD->getNameAsCString();
4676
4677 // Construct method lists.
4678 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4679 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4680 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4681 e = PD->instmeth_end(); i != e; ++i) {
4682 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004683 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004684 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4685 OptInstanceMethods.push_back(C);
4686 } else {
4687 InstanceMethods.push_back(C);
4688 }
4689 }
4690
4691 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4692 e = PD->classmeth_end(); i != e; ++i) {
4693 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004694 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004695 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4696 OptClassMethods.push_back(C);
4697 } else {
4698 ClassMethods.push_back(C);
4699 }
4700 }
4701
4702 std::vector<llvm::Constant*> Values(10);
4703 // isa is NULL
4704 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4705 Values[1] = GetClassName(PD->getIdentifier());
4706 Values[2] = EmitProtocolList(
4707 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4708 PD->protocol_begin(),
4709 PD->protocol_end());
4710
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004711 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004712 + PD->getNameAsString(),
4713 "__DATA, __objc_const",
4714 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004715 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004716 + PD->getNameAsString(),
4717 "__DATA, __objc_const",
4718 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004719 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004720 + PD->getNameAsString(),
4721 "__DATA, __objc_const",
4722 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004723 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004724 + PD->getNameAsString(),
4725 "__DATA, __objc_const",
4726 OptClassMethods);
4727 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4728 0, PD, ObjCTypes);
4729 uint32_t Size =
4730 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4731 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4732 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4733 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4734 Values);
4735
4736 if (Entry) {
4737 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004738 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004739 Entry->setInitializer(Init);
4740 } else {
4741 Entry =
4742 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004743 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004744 Init,
4745 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4746 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004747 Entry->setAlignment(
4748 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004749 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004750 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004751 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4752
4753 // Use this protocol meta-data to build protocol list table in section
4754 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004755 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004756 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004757 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004758 Entry,
4759 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4760 +ProtocolName,
4761 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004762 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004763 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004764 PTGV->setSection("__DATA, __objc_protolist");
4765 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4766 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004767 return Entry;
4768}
4769
4770/// EmitProtocolList - Generate protocol list meta-data:
4771/// @code
4772/// struct _protocol_list_t {
4773/// long protocol_count; // Note, this is 32/64 bit
4774/// struct _protocol_t[protocol_count];
4775/// }
4776/// @endcode
4777///
4778llvm::Constant *
4779CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4780 ObjCProtocolDecl::protocol_iterator begin,
4781 ObjCProtocolDecl::protocol_iterator end) {
4782 std::vector<llvm::Constant*> ProtocolRefs;
4783
Fariborz Jahanianda320092009-01-29 19:24:30 +00004784 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004785 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004786 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4787
Daniel Dunbar948e2582009-02-15 07:36:20 +00004788 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004789 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4790 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004791 return llvm::ConstantExpr::getBitCast(GV,
4792 ObjCTypes.ProtocolListnfABIPtrTy);
4793
4794 for (; begin != end; ++begin)
4795 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4796
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 // This list is null terminated.
4798 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004799 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004800
4801 std::vector<llvm::Constant*> Values(2);
4802 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4803 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004804 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004805 ProtocolRefs.size()),
4806 ProtocolRefs);
4807
4808 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4809 GV = new llvm::GlobalVariable(Init->getType(), false,
4810 llvm::GlobalValue::InternalLinkage,
4811 Init,
4812 Name,
4813 &CGM.getModule());
4814 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004815 GV->setAlignment(
4816 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004817 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004818 return llvm::ConstantExpr::getBitCast(GV,
4819 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004820}
4821
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004822/// GetMethodDescriptionConstant - This routine build following meta-data:
4823/// struct _objc_method {
4824/// SEL _cmd;
4825/// char *method_type;
4826/// char *_imp;
4827/// }
4828
4829llvm::Constant *
4830CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4831 std::vector<llvm::Constant*> Desc(3);
4832 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4833 ObjCTypes.SelectorPtrTy);
4834 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004835 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004836 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4837 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4838}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004839
4840/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4841/// This code gen. amounts to generating code for:
4842/// @code
4843/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4844/// @encode
4845///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004846LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004847 CodeGen::CodeGenFunction &CGF,
4848 QualType ObjectTy,
4849 llvm::Value *BaseValue,
4850 const ObjCIvarDecl *Ivar,
4851 const FieldDecl *Field,
4852 unsigned CVRQualifiers) {
4853 assert(ObjectTy->isObjCInterfaceType() &&
4854 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004855 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004856 std::string ExternalName;
4857 llvm::GlobalVariable *IvarOffsetGV =
4858 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004859
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004860 // (char *) BaseValue
4861 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4862 ObjCTypes.Int8PtrTy);
4863 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4864 // (char*)BaseValue + Offset_symbol
4865 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4866 // (type *)((char*)BaseValue + Offset_symbol)
4867 const llvm::Type *IvarTy =
4868 CGM.getTypes().ConvertType(Ivar->getType());
4869 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4870 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004871
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004872 if (Ivar->isBitField()) {
4873 CodeGenTypes::BitFieldInfo bitFieldInfo =
4874 CGM.getTypes().getBitFieldInfo(Field);
4875 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4876 Field->getType()->isSignedIntegerType(),
4877 Field->getType().getCVRQualifiers()|CVRQualifiers);
4878 }
4879
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004880 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004881 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4882 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004883 LValue::SetObjCIvar(LV, true);
4884 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004885}
4886
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004887llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4888 CodeGen::CodeGenFunction &CGF,
4889 ObjCInterfaceDecl *Interface,
4890 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004891 std::string ExternalName;
4892 llvm::GlobalVariable *IvarOffsetGV =
4893 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4894
4895 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004896}
4897
Fariborz Jahanian46551122009-02-04 00:22:57 +00004898CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4899 CodeGen::CodeGenFunction &CGF,
4900 QualType ResultType,
4901 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004902 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004903 QualType Arg0Ty,
4904 bool IsSuper,
4905 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004906 // FIXME. Even though IsSuper is passes. This function doese not
4907 // handle calls to 'super' receivers.
4908 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004909 llvm::Value *Arg0 = Receiver;
4910 if (!IsSuper)
4911 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004912
4913 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004914 // FIXME. This is too much work to get the ABI-specific result type
4915 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004916 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4917 llvm::SmallVector<QualType, 16>());
4918 llvm::Constant *Fn;
4919 std::string Name("\01l_");
4920 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004921#if 0
4922 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004923 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4924 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4925 // FIXME. Is there a better way of getting these names.
4926 // They are available in RuntimeFunctions vector pair.
4927 Name += "objc_msgSendId_stret_fixup";
4928 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004929 else
4930#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004931 if (IsSuper) {
4932 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4933 Name += "objc_msgSendSuper2_stret_fixup";
4934 }
4935 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004936 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004937 Fn = ObjCTypes.MessageSendStretFixupFn;
4938 Name += "objc_msgSend_stret_fixup";
4939 }
4940 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004941 else if (ResultType->isFloatingType() &&
4942 // Selection of frret API only happens in 32bit nonfragile ABI.
4943 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004944 Fn = ObjCTypes.MessageSendFpretFixupFn;
4945 Name += "objc_msgSend_fpret_fixup";
4946 }
4947 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004948#if 0
4949// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004950 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4951 Fn = ObjCTypes.MessageSendIdFixupFn;
4952 Name += "objc_msgSendId_fixup";
4953 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004954 else
4955#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004956 if (IsSuper) {
4957 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4958 Name += "objc_msgSendSuper2_fixup";
4959 }
4960 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004961 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004962 Fn = ObjCTypes.MessageSendFixupFn;
4963 Name += "objc_msgSend_fixup";
4964 }
4965 }
4966 Name += '_';
4967 std::string SelName(Sel.getAsString());
4968 // Replace all ':' in selector name with '_' ouch!
4969 for(unsigned i = 0; i < SelName.size(); i++)
4970 if (SelName[i] == ':')
4971 SelName[i] = '_';
4972 Name += SelName;
4973 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4974 if (!GV) {
4975 // Build messafe ref table entry.
4976 std::vector<llvm::Constant*> Values(2);
4977 Values[0] = Fn;
4978 Values[1] = GetMethodVarName(Sel);
4979 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4980 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004981 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004982 Init,
4983 Name,
4984 &CGM.getModule());
4985 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4986 GV->setAlignment(
4987 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4988 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4989 UsedGlobals.push_back(GV);
4990 }
4991 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004992
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004993 CallArgList ActualArgs;
4994 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4995 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4996 ObjCTypes.MessageRefCPtrTy));
4997 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004998 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4999 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5000 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005001 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005002 Callee = CGF.Builder.CreateBitCast(Callee,
5003 llvm::PointerType::getUnqual(FTy));
5004 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005005}
5006
5007/// Generate code for a message send expression in the nonfragile abi.
5008CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5009 CodeGen::CodeGenFunction &CGF,
5010 QualType ResultType,
5011 Selector Sel,
5012 llvm::Value *Receiver,
5013 bool IsClassMessage,
5014 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005015 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005017 false, CallArgs);
5018}
5019
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005020llvm::GlobalVariable *
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005021CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name,
5022 bool AddToUsed) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005023 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5024
Daniel Dunbardfff2302009-03-02 05:18:14 +00005025 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005026 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5027 llvm::GlobalValue::ExternalLinkage,
5028 0, Name, &CGM.getModule());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005029 if (AddToUsed)
5030 UsedGlobals.push_back(GV);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005031 }
5032
5033 return GV;
5034}
5035
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005036llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005037 const ObjCInterfaceDecl *ID,
5038 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005039
5040 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5041
5042 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005043 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005044 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005045 Entry =
5046 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5047 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005048 ClassGV,
5049 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5050 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005051 &CGM.getModule());
5052 Entry->setAlignment(
5053 CGM.getTargetData().getPrefTypeAlignment(
5054 ObjCTypes.ClassnfABIPtrTy));
5055
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005056 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005057 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005058 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005059 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005060 UsedGlobals.push_back(Entry);
5061 }
5062
5063 return Builder.CreateLoad(Entry, false, "tmp");
5064}
5065
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005066/// EmitMetaClassRef - Return a Value * of the address of _class_t
5067/// meta-data
5068///
5069llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5070 const ObjCInterfaceDecl *ID) {
5071 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5072 if (Entry)
5073 return Builder.CreateLoad(Entry, false, "tmp");
5074
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005075 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
5076 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName, false);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005077 Entry =
5078 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5079 llvm::GlobalValue::InternalLinkage,
5080 MetaClassGV,
5081 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5082 &CGM.getModule());
5083 Entry->setAlignment(
5084 CGM.getTargetData().getPrefTypeAlignment(
5085 ObjCTypes.ClassnfABIPtrTy));
5086
5087 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
5088 UsedGlobals.push_back(Entry);
5089
5090 return Builder.CreateLoad(Entry, false, "tmp");
5091}
5092
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005093/// GetClass - Return a reference to the class for the given interface
5094/// decl.
5095llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5096 const ObjCInterfaceDecl *ID) {
5097 return EmitClassRef(Builder, ID);
5098}
5099
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005100/// Generates a message send where the super is the receiver. This is
5101/// a message send to self with special delivery semantics indicating
5102/// which class's method should be called.
5103CodeGen::RValue
5104CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5105 QualType ResultType,
5106 Selector Sel,
5107 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005108 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005109 llvm::Value *Receiver,
5110 bool IsClassMessage,
5111 const CodeGen::CallArgList &CallArgs) {
5112 // ...
5113 // Create and init a super structure; this is a (receiver, class)
5114 // pair we will pass to objc_msgSendSuper.
5115 llvm::Value *ObjCSuper =
5116 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5117
5118 llvm::Value *ReceiverAsObject =
5119 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5120 CGF.Builder.CreateStore(ReceiverAsObject,
5121 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5122
5123 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005124 llvm::Value *Target;
5125 if (IsClassMessage) {
5126 if (isCategoryImpl) {
5127 // Message sent to "super' in a class method defined in
5128 // a category implementation.
5129 Target = EmitClassRef(CGF.Builder, Class, false);
5130 Target = CGF.Builder.CreateStructGEP(Target, 0);
5131 Target = CGF.Builder.CreateLoad(Target);
5132 }
5133 else
5134 Target = EmitMetaClassRef(CGF.Builder, Class);
5135 }
5136 else
5137 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005138
5139 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5140 // and ObjCTypes types.
5141 const llvm::Type *ClassTy =
5142 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5143 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5144 CGF.Builder.CreateStore(Target,
5145 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5146
5147 return EmitMessageSend(CGF, ResultType, Sel,
5148 ObjCSuper, ObjCTypes.SuperPtrCTy,
5149 true, CallArgs);
5150}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005151
5152llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5153 Selector Sel) {
5154 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5155
5156 if (!Entry) {
5157 llvm::Constant *Casted =
5158 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5159 ObjCTypes.SelectorPtrTy);
5160 Entry =
5161 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5162 llvm::GlobalValue::InternalLinkage,
5163 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5164 &CGM.getModule());
5165 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5166 UsedGlobals.push_back(Entry);
5167 }
5168
5169 return Builder.CreateLoad(Entry, false, "tmp");
5170}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005171/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5172/// objc_assign_ivar (id src, id *dst)
5173///
5174void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5175 llvm::Value *src, llvm::Value *dst)
5176{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005177 const llvm::Type * SrcTy = src->getType();
5178 if (!isa<llvm::PointerType>(SrcTy)) {
5179 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5180 assert(Size <= 8 && "does not support size > 8");
5181 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5182 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005183 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5184 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005185 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5186 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5187 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5188 src, dst, "assignivar");
5189 return;
5190}
5191
5192/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5193/// objc_assign_strongCast (id src, id *dst)
5194///
5195void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5196 CodeGen::CodeGenFunction &CGF,
5197 llvm::Value *src, llvm::Value *dst)
5198{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005199 const llvm::Type * SrcTy = src->getType();
5200 if (!isa<llvm::PointerType>(SrcTy)) {
5201 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5202 assert(Size <= 8 && "does not support size > 8");
5203 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5204 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005205 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5206 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005207 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5208 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5209 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5210 src, dst, "weakassign");
5211 return;
5212}
5213
5214/// EmitObjCWeakRead - Code gen for loading value of a __weak
5215/// object: objc_read_weak (id *src)
5216///
5217llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5218 CodeGen::CodeGenFunction &CGF,
5219 llvm::Value *AddrWeakObj)
5220{
Eli Friedman8339b352009-03-07 03:57:15 +00005221 const llvm::Type* DestTy =
5222 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005223 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5224 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5225 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005226 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005227 return read_weak;
5228}
5229
5230/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5231/// objc_assign_weak (id src, id *dst)
5232///
5233void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5234 llvm::Value *src, llvm::Value *dst)
5235{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005236 const llvm::Type * SrcTy = src->getType();
5237 if (!isa<llvm::PointerType>(SrcTy)) {
5238 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5239 assert(Size <= 8 && "does not support size > 8");
5240 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5241 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005242 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5243 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005244 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5245 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5246 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5247 src, dst, "weakassign");
5248 return;
5249}
5250
5251/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5252/// objc_assign_global (id src, id *dst)
5253///
5254void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5255 llvm::Value *src, llvm::Value *dst)
5256{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005257 const llvm::Type * SrcTy = src->getType();
5258 if (!isa<llvm::PointerType>(SrcTy)) {
5259 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5260 assert(Size <= 8 && "does not support size > 8");
5261 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5262 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005263 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5264 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005265 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5266 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5267 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5268 src, dst, "globalassign");
5269 return;
5270}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005271
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005272void
5273CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5274 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005275 bool isTry = isa<ObjCAtTryStmt>(S);
5276 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5277 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005278 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005279 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005280 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005281 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5282
5283 // For @synchronized, call objc_sync_enter(sync.expr). The
5284 // evaluation of the expression must occur before we enter the
5285 // @synchronized. We can safely avoid a temp here because jumps into
5286 // @synchronized are illegal & this will dominate uses.
5287 llvm::Value *SyncArg = 0;
5288 if (!isTry) {
5289 SyncArg =
5290 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5291 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005292 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005293 }
5294
5295 // Push an EH context entry, used for handling rethrows and jumps
5296 // through finally.
5297 CGF.PushCleanupBlock(FinallyBlock);
5298
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005299 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005300
5301 CGF.EmitBlock(TryBlock);
5302 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5303 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5304 CGF.EmitBranchThroughCleanup(FinallyEnd);
5305
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005306 // Emit the exception handler.
5307
5308 CGF.EmitBlock(TryHandler);
5309
5310 llvm::Value *llvm_eh_exception =
5311 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5312 llvm::Value *llvm_eh_selector_i64 =
5313 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5314 llvm::Value *llvm_eh_typeid_for_i64 =
5315 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5316 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5317 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5318
5319 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5320 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005321 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005322
5323 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005324 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005325 bool HasCatchAll = false;
5326 if (isTry) {
5327 if (const ObjCAtCatchStmt* CatchStmt =
5328 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5329 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005330 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005331 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005332
5333 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005334 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005335 // Use i8* null here to signal this is a catch all, not a cleanup.
5336 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5337 SelectorArgs.push_back(Null);
5338 HasCatchAll = true;
5339 break;
5340 }
5341
Daniel Dunbarede8de92009-03-06 00:01:21 +00005342 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5343 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005344 llvm::Value *IDEHType =
5345 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5346 if (!IDEHType)
5347 IDEHType =
5348 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5349 llvm::GlobalValue::ExternalLinkage,
5350 0, "OBJC_EHTYPE_id", &CGM.getModule());
5351 SelectorArgs.push_back(IDEHType);
5352 HasCatchAll = true;
5353 break;
5354 }
5355
5356 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005357 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005358 assert(PT && "Invalid @catch type.");
5359 const ObjCInterfaceType *IT =
5360 PT->getPointeeType()->getAsObjCInterfaceType();
5361 assert(IT && "Invalid @catch type.");
5362 llvm::Value *EHType = GetInterfaceEHType(IT);
5363 SelectorArgs.push_back(EHType);
5364 }
5365 }
5366 }
5367
5368 // We use a cleanup unless there was already a catch all.
5369 if (!HasCatchAll) {
5370 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005371 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005372 }
5373
5374 llvm::Value *Selector =
5375 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5376 SelectorArgs.begin(), SelectorArgs.end(),
5377 "selector");
5378 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005379 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005380 const Stmt *CatchBody = Handlers[i].second;
5381
5382 llvm::BasicBlock *Next = 0;
5383
5384 // The last handler always matches.
5385 if (i + 1 != e) {
5386 assert(CatchParam && "Only last handler can be a catch all.");
5387
5388 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5389 Next = CGF.createBasicBlock("catch.next");
5390 llvm::Value *Id =
5391 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5392 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5393 ObjCTypes.Int8PtrTy));
5394 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5395 Match, Next);
5396
5397 CGF.EmitBlock(Match);
5398 }
5399
5400 if (CatchBody) {
5401 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5402 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5403
5404 // Cleanups must call objc_end_catch.
5405 //
5406 // FIXME: It seems incorrect for objc_begin_catch to be inside
5407 // this context, but this matches gcc.
5408 CGF.PushCleanupBlock(MatchEnd);
5409 CGF.setInvokeDest(MatchHandler);
5410
5411 llvm::Value *ExcObject =
5412 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5413
5414 // Bind the catch parameter if it exists.
5415 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005416 ExcObject =
5417 CGF.Builder.CreateBitCast(ExcObject,
5418 CGF.ConvertType(CatchParam->getType()));
5419 // CatchParam is a ParmVarDecl because of the grammar
5420 // construction used to handle this, but for codegen purposes
5421 // we treat this as a local decl.
5422 CGF.EmitLocalBlockVarDecl(*CatchParam);
5423 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005424 }
5425
5426 CGF.ObjCEHValueStack.push_back(ExcObject);
5427 CGF.EmitStmt(CatchBody);
5428 CGF.ObjCEHValueStack.pop_back();
5429
5430 CGF.EmitBranchThroughCleanup(FinallyEnd);
5431
5432 CGF.EmitBlock(MatchHandler);
5433
5434 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5435 // We are required to emit this call to satisfy LLVM, even
5436 // though we don't use the result.
5437 llvm::SmallVector<llvm::Value*, 8> Args;
5438 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005439 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005440 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5441 0));
5442 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5443 CGF.Builder.CreateStore(Exc, RethrowPtr);
5444 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5445
5446 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5447
5448 CGF.EmitBlock(MatchEnd);
5449
5450 // Unfortunately, we also have to generate another EH frame here
5451 // in case this throws.
5452 llvm::BasicBlock *MatchEndHandler =
5453 CGF.createBasicBlock("match.end.handler");
5454 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5455 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5456 Cont, MatchEndHandler,
5457 Args.begin(), Args.begin());
5458
5459 CGF.EmitBlock(Cont);
5460 if (Info.SwitchBlock)
5461 CGF.EmitBlock(Info.SwitchBlock);
5462 if (Info.EndBlock)
5463 CGF.EmitBlock(Info.EndBlock);
5464
5465 CGF.EmitBlock(MatchEndHandler);
5466 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5467 // We are required to emit this call to satisfy LLVM, even
5468 // though we don't use the result.
5469 Args.clear();
5470 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005471 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005472 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5473 0));
5474 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5475 CGF.Builder.CreateStore(Exc, RethrowPtr);
5476 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5477
5478 if (Next)
5479 CGF.EmitBlock(Next);
5480 } else {
5481 assert(!Next && "catchup should be last handler.");
5482
5483 CGF.Builder.CreateStore(Exc, RethrowPtr);
5484 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5485 }
5486 }
5487
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005488 // Pop the cleanup entry, the @finally is outside this cleanup
5489 // scope.
5490 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5491 CGF.setInvokeDest(PrevLandingPad);
5492
5493 CGF.EmitBlock(FinallyBlock);
5494
5495 if (isTry) {
5496 if (const ObjCAtFinallyStmt* FinallyStmt =
5497 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5498 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5499 } else {
5500 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5501 // @synchronized.
5502 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005503 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005504
5505 if (Info.SwitchBlock)
5506 CGF.EmitBlock(Info.SwitchBlock);
5507 if (Info.EndBlock)
5508 CGF.EmitBlock(Info.EndBlock);
5509
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005510 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005511 CGF.EmitBranch(FinallyEnd);
5512
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005513 CGF.EmitBlock(FinallyRethrow);
5514 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5515 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005516 CGF.Builder.CreateUnreachable();
5517
5518 CGF.EmitBlock(FinallyEnd);
5519}
5520
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005521/// EmitThrowStmt - Generate code for a throw statement.
5522void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5523 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005524 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005525 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005526 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005527 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005528 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5529 "Unexpected rethrow outside @catch block.");
5530 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005531 }
5532
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005533 llvm::Value *ExceptionAsObject =
5534 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5535 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5536 if (InvokeDest) {
5537 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5538 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5539 Cont, InvokeDest,
5540 &ExceptionAsObject, &ExceptionAsObject + 1);
5541 CGF.EmitBlock(Cont);
5542 } else
5543 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5544 CGF.Builder.CreateUnreachable();
5545
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005546 // Clear the insertion point to indicate we are in unreachable code.
5547 CGF.Builder.ClearInsertionPoint();
5548}
Daniel Dunbare588b992009-03-01 04:46:24 +00005549
5550llvm::Value *
5551CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5552 const ObjCInterfaceDecl *ID = IT->getDecl();
5553 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5554 if (Entry)
5555 return Entry;
5556
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005557 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005558 std::string VTableName = "objc_ehtype_vtable";
5559 llvm::GlobalVariable *VTableGV =
5560 CGM.getModule().getGlobalVariable(VTableName);
5561 if (!VTableGV)
5562 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5563 llvm::GlobalValue::ExternalLinkage,
5564 0, VTableName, &CGM.getModule());
5565
5566 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5567
5568 std::vector<llvm::Constant*> Values(3);
5569 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5570 Values[1] = GetClassName(ID->getIdentifier());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005571 Values[2] = GetClassGlobal(ClassName, false);
Daniel Dunbare588b992009-03-01 04:46:24 +00005572 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5573
5574 Entry =
5575 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005576 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005577 Init,
5578 (std::string("OBJC_EHTYPE_$_") +
5579 ID->getIdentifier()->getName()),
5580 &CGM.getModule());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005581 if (CGM.getLangOptions().getVisibilityMode() ==
5582 LangOptions::HiddenVisibility)
5583 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
5584 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Daniel Dunbare588b992009-03-01 04:46:24 +00005585
5586 return Entry;
5587}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005588
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005589/* *** */
5590
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005591CodeGen::CGObjCRuntime *
5592CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005593 return new CGObjCMac(CGM);
5594}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005595
5596CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005597CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005598 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005599}