blob: d1623075d59cfe7f4e4f7b60b7c3bd5d3cfa5d0a [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +000095 llvm::Constant *getGcAssignWeakFn() {
96 // id objc_assign_weak (id, id *)
97 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
98 Args.push_back(ObjectPtrTy->getPointerTo());
99 llvm::FunctionType *FTy =
100 llvm::FunctionType::get(ObjectPtrTy, Args, false);
101 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
102 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000103
104 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +0000105 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000106
107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000108 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000109
110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000111 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000112
113 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000114 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000115
Daniel Dunbar1c566672009-02-24 01:43:46 +0000116 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000117 llvm::Constant *getSyncEnterFn() {
118 // void objc_sync_enter (id)
119 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
120 llvm::FunctionType *FTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
122 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
123 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000124
125 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000126 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000127
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
129 ~ObjCCommonTypesHelper(){}
130};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000131
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000132/// ObjCTypesHelper - Helper class that encapsulates lazy
133/// construction of varies types used during ObjC generation.
134class ObjCTypesHelper : public ObjCCommonTypesHelper {
135private:
136
Chris Lattner74391b42009-03-22 21:03:39 +0000137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000139 *MessageSendSuperFpretFn;
140
141public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000142 /// SymtabTy - LLVM type for struct objc_symtab.
143 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000144 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
145 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000146 /// ModuleTy - LLVM type for struct objc_module.
147 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000148
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000149 /// ProtocolTy - LLVM type for struct objc_protocol.
150 const llvm::StructType *ProtocolTy;
151 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
152 const llvm::Type *ProtocolPtrTy;
153 /// ProtocolExtensionTy - LLVM type for struct
154 /// objc_protocol_extension.
155 const llvm::StructType *ProtocolExtensionTy;
156 /// ProtocolExtensionTy - LLVM type for struct
157 /// objc_protocol_extension *.
158 const llvm::Type *ProtocolExtensionPtrTy;
159 /// MethodDescriptionTy - LLVM type for struct
160 /// objc_method_description.
161 const llvm::StructType *MethodDescriptionTy;
162 /// MethodDescriptionListTy - LLVM type for struct
163 /// objc_method_description_list.
164 const llvm::StructType *MethodDescriptionListTy;
165 /// MethodDescriptionListPtrTy - LLVM type for struct
166 /// objc_method_description_list *.
167 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000168 /// ProtocolListTy - LLVM type for struct objc_property_list.
169 const llvm::Type *ProtocolListTy;
170 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
171 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000172 /// CategoryTy - LLVM type for struct objc_category.
173 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000174 /// ClassTy - LLVM type for struct objc_class.
175 const llvm::StructType *ClassTy;
176 /// ClassPtrTy - LLVM type for struct objc_class *.
177 const llvm::Type *ClassPtrTy;
178 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
179 const llvm::StructType *ClassExtensionTy;
180 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
181 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000182 // IvarTy - LLVM type for struct objc_ivar.
183 const llvm::StructType *IvarTy;
184 /// IvarListTy - LLVM type for struct objc_ivar_list.
185 const llvm::Type *IvarListTy;
186 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
187 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000188 /// MethodListTy - LLVM type for struct objc_method_list.
189 const llvm::Type *MethodListTy;
190 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
191 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000192
193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
194 const llvm::Type *ExceptionDataTy;
195
Anders Carlsson124526b2008-09-09 10:10:21 +0000196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000197 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000198
199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000200 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000201
202 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000203 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000204
205 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000206 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000207
208 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000209 llvm::Constant *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000210
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000211public:
212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000213 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000214
215
Chris Lattner74391b42009-03-22 21:03:39 +0000216 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000217 return IsSuper ? MessageSendSuperFn : MessageSendFn;
218 }
219
Chris Lattner74391b42009-03-22 21:03:39 +0000220 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
222 }
223
Chris Lattner74391b42009-03-22 21:03:39 +0000224 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
226 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000227};
228
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000230/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000232public:
Chris Lattner74391b42009-03-22 21:03:39 +0000233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000234 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
236 *MessageSendSuper2StretFixupFn;
237
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000238 // MethodListnfABITy - LLVM for struct _method_list_t
239 const llvm::StructType *MethodListnfABITy;
240
241 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
242 const llvm::Type *MethodListnfABIPtrTy;
243
244 // ProtocolnfABITy = LLVM for struct _protocol_t
245 const llvm::StructType *ProtocolnfABITy;
246
Daniel Dunbar948e2582009-02-15 07:36:20 +0000247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
248 const llvm::Type *ProtocolnfABIPtrTy;
249
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000250 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
251 const llvm::StructType *ProtocolListnfABITy;
252
253 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
254 const llvm::Type *ProtocolListnfABIPtrTy;
255
256 // ClassnfABITy - LLVM for struct _class_t
257 const llvm::StructType *ClassnfABITy;
258
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000259 // ClassnfABIPtrTy - LLVM for struct _class_t*
260 const llvm::Type *ClassnfABIPtrTy;
261
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000262 // IvarnfABITy - LLVM for struct _ivar_t
263 const llvm::StructType *IvarnfABITy;
264
265 // IvarListnfABITy - LLVM for struct _ivar_list_t
266 const llvm::StructType *IvarListnfABITy;
267
268 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
269 const llvm::Type *IvarListnfABIPtrTy;
270
271 // ClassRonfABITy - LLVM for struct _class_ro_t
272 const llvm::StructType *ClassRonfABITy;
273
274 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
275 const llvm::Type *ImpnfABITy;
276
277 // CategorynfABITy - LLVM for struct _category_t
278 const llvm::StructType *CategorynfABITy;
279
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000280 // New types for nonfragile abi messaging.
281
282 // MessageRefTy - LLVM for:
283 // struct _message_ref_t {
284 // IMP messenger;
285 // SEL name;
286 // };
287 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000288 // MessageRefCTy - clang type for struct _message_ref_t
289 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000290
291 // MessageRefPtrTy - LLVM for struct _message_ref_t*
292 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000293 // MessageRefCPtrTy - clang type for struct _message_ref_t*
294 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000295
Fariborz Jahanianef163782009-02-05 01:13:09 +0000296 // MessengerTy - Type of the messenger (shown as IMP above)
297 const llvm::FunctionType *MessengerTy;
298
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000299 // SuperMessageRefTy - LLVM for:
300 // struct _super_message_ref_t {
301 // SUPER_IMP messenger;
302 // SEL name;
303 // };
304 const llvm::StructType *SuperMessageRefTy;
305
306 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
307 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000308
309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
310 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000311 llvm::Value *getEHPersonalityPtr() {
312 llvm::Constant *Personality =
313 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
314 std::vector<const llvm::Type*>(),
315 true),
316 "__objc_personality_v0");
317 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
318 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000319
Chris Lattner74391b42009-03-22 21:03:39 +0000320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000321
322 const llvm::StructType *EHTypeTy;
323 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000324
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
326 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327};
328
329class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000330public:
331 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000332 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000333 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000334 unsigned int ivar_bytepos;
335 unsigned int ivar_size;
336 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
337 };
338
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000339 class SKIP_SCAN {
340 public:
341 unsigned int skip;
342 unsigned int scan;
343 SKIP_SCAN() : skip(0), scan(0) {}
344 };
345
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000346protected:
347 CodeGen::CodeGenModule &CGM;
348 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000349 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000350
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000351 // gc ivar layout bitmap calculation helper caches.
352 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
353 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
354 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000355
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000356 /// LazySymbols - Symbols to generate a lazy reference for. See
357 /// DefinedSymbols and FinishModule().
358 std::set<IdentifierInfo*> LazySymbols;
359
360 /// DefinedSymbols - External symbols which are defined by this
361 /// module. The symbols in this list and LazySymbols are used to add
362 /// special linker symbols which ensure that Objective-C modules are
363 /// linked properly.
364 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000366 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000369 /// MethodVarNames - uniqued method variable names.
370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000371
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000372 /// MethodVarTypes - uniqued method type signatures. We have to use
373 /// a StringMap here because have no other unique reference.
374 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000375
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000376 /// MethodDefinitions - map of methods which have been defined in
377 /// this translation unit.
378 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000379
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000380 /// PropertyNames - uniqued method variable names.
381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000383 /// ClassReferences - uniqued class references.
384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000385
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 /// SelectorReferences - uniqued selector references.
387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000388
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000389 /// Protocols - Protocols for which an objc_protocol structure has
390 /// been emitted. Forward declarations are handled by creating an
391 /// empty structure whose initializer is filled in when/if defined.
392 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000393
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000394 /// DefinedProtocols - Protocols which have actually been
395 /// defined. We should not need this, see FIXME in GenerateProtocol.
396 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// DefinedClasses - List of defined classes.
399 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000400
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000401 /// DefinedCategories - List of defined categories.
402 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000403
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000404 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000405 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000406 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000407
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 const ObjCContainerDecl *CD,
412 std::string &NameOut);
413
414 /// GetMethodVarName - Return a unique constant for the given
415 /// selector's name. The return value has type char *.
416 llvm::Constant *GetMethodVarName(Selector Sel);
417 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
418 llvm::Constant *GetMethodVarName(const std::string &Name);
419
420 /// GetMethodVarType - Return a unique constant for the given
421 /// selector's name. The return value has type char *.
422
423 // FIXME: This is a horrible name.
424 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000425 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000426
427 /// GetPropertyName - Return a unique constant for the given
428 /// name. The return value has type char *.
429 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
430
431 // FIXME: This can be dropped once string functions are unified.
432 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
433 const Decl *Container);
434
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000435 /// GetClassName - Return a unique constant for the given selector's
436 /// name. The return value has type char *.
437 llvm::Constant *GetClassName(IdentifierInfo *Ident);
438
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000439 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
440 /// interface declaration.
441 const llvm::StructLayout *GetInterfaceDeclStructLayout(
442 const ObjCInterfaceDecl *ID) const;
443
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000444 /// BuildIvarLayout - Builds ivar layout bitmap for the class
445 /// implementation for the __strong or __weak case.
446 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
448 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000449
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
451 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000452 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000454 unsigned int BytePos, bool ForStrongLayout,
455 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000456
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000457 /// GetIvarLayoutName - Returns a unique constant for the given
458 /// ivar layout bitmap.
459 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
460 const ObjCCommonTypesHelper &ObjCTypes);
461
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000462 /// EmitPropertyList - Emit the given property list. The return
463 /// value has type PropertyListPtrTy.
464 llvm::Constant *EmitPropertyList(const std::string &Name,
465 const Decl *Container,
466 const ObjCContainerDecl *OCD,
467 const ObjCCommonTypesHelper &ObjCTypes);
468
Fariborz Jahanianda320092009-01-29 19:24:30 +0000469 /// GetProtocolRef - Return a reference to the internal protocol
470 /// description, creating an empty one if it has not been
471 /// defined. The return value has type ProtocolPtrTy.
472 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000473
474 /// GetIvarBaseOffset - returns ivars byte offset.
475 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000476 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000477
Chris Lattnercd0ee142009-03-31 08:33:16 +0000478 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000479 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
480 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000481 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000482
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000483 /// CreateMetadataVar - Create a global variable with internal
484 /// linkage for use by the Objective-C runtime.
485 ///
486 /// This is a convenience wrapper which not only creates the
487 /// variable, but also sets the section and alignment and adds the
488 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000489 ///
490 /// \param Name - The variable name.
491 /// \param Init - The variable initializer; this is also used to
492 /// define the type of the variable.
493 /// \param Section - The section the variable should go into, or 0.
494 /// \param Align - The alignment for the variable, or 0.
495 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000496 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000497 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
498 llvm::Constant *Init,
499 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000500 unsigned Align,
501 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000502
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000503 /// GetNamedIvarList - Return the list of ivars in the interface
504 /// itself (not including super classes and not including unnamed
505 /// bitfields).
506 ///
507 /// For the non-fragile ABI, this also includes synthesized property
508 /// ivars.
509 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
510 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
511
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000512public:
513 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
514 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000515
Steve Naroff33fdb732009-03-31 16:53:37 +0000516 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000517
518 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
519 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000520
521 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
522
523 /// GetOrEmitProtocol - Get the protocol object for the given
524 /// declaration, emitting it if necessary. The return value has type
525 /// ProtocolPtrTy.
526 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
527
528 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
529 /// object for the given declaration, emitting it if needed. These
530 /// forward references will be filled in with empty bodies if no
531 /// definition is seen. The return value has type ProtocolPtrTy.
532 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000533};
534
535class CGObjCMac : public CGObjCCommonMac {
536private:
537 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000538 /// EmitImageInfo - Emit the image info marker used to encode some module
539 /// level information.
540 void EmitImageInfo();
541
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000542 /// EmitModuleInfo - Another marker encoding module level
543 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000544 void EmitModuleInfo();
545
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000546 /// EmitModuleSymols - Emit module symbols, the list of defined
547 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000548 llvm::Constant *EmitModuleSymbols();
549
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000550 /// FinishModule - Write out global data structures at the end of
551 /// processing a translation unit.
552 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000553
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000554 /// EmitClassExtension - Generate the class extension structure used
555 /// to store the weak ivar layout and properties. The return value
556 /// has type ClassExtensionPtrTy.
557 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
558
559 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
560 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000561 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000562 const ObjCInterfaceDecl *ID);
563
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000564 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000565 QualType ResultType,
566 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000567 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000568 QualType Arg0Ty,
569 bool IsSuper,
570 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000571
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000572 /// EmitIvarList - Emit the ivar list for the given
573 /// implementation. If ForClass is true the list of class ivars
574 /// (i.e. metaclass ivars) is emitted, otherwise the list of
575 /// interface ivars will be emitted. The return value has type
576 /// IvarListPtrTy.
577 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000578 bool ForClass);
579
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 /// EmitMetaClass - Emit a forward reference to the class structure
581 /// for the metaclass of the given interface. The return value has
582 /// type ClassPtrTy.
583 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
584
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000585 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000586 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000587 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
588 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000589 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000590 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000591
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000592 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000593
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000594 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000595
596 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000597 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000598 llvm::Constant *EmitMethodList(const std::string &Name,
599 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000600 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000601
602 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000603 /// method declarations.
604 /// - TypeName: The name for the type containing the methods.
605 /// - IsProtocol: True iff these methods are for a protocol.
606 /// - ClassMethds: True iff these are class methods.
607 /// - Required: When true, only "required" methods are
608 /// listed. Similarly, when false only "optional" methods are
609 /// listed. For classes this should always be true.
610 /// - begin, end: The method list to output.
611 ///
612 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000613 llvm::Constant *EmitMethodDescList(const std::string &Name,
614 const char *Section,
615 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000616
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000617 /// GetOrEmitProtocol - Get the protocol object for the given
618 /// declaration, emitting it if necessary. The return value has type
619 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000620 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000621
622 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
623 /// object for the given declaration, emitting it if needed. These
624 /// forward references will be filled in with empty bodies if no
625 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000626 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000627
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000628 /// EmitProtocolExtension - Generate the protocol extension
629 /// structure used to store optional instance and class methods, and
630 /// protocol properties. The return value has type
631 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000632 llvm::Constant *
633 EmitProtocolExtension(const ObjCProtocolDecl *PD,
634 const ConstantVector &OptInstanceMethods,
635 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000636
637 /// EmitProtocolList - Generate the list of referenced
638 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000639 llvm::Constant *EmitProtocolList(const std::string &Name,
640 ObjCProtocolDecl::protocol_iterator begin,
641 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000642
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000643 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
644 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000645 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000646
Fariborz Jahanianda320092009-01-29 19:24:30 +0000647 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000648 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000649
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000650 virtual llvm::Function *ModuleInitFunction();
651
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000652 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000653 QualType ResultType,
654 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000655 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000656 bool IsClassMessage,
657 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000658
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000659 virtual CodeGen::RValue
660 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000661 QualType ResultType,
662 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000663 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000664 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000665 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000666 bool IsClassMessage,
667 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000668
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000669 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000670 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000671
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000672 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000673
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000674 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000675
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000676 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000677
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000678 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000679 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000680
Chris Lattner74391b42009-03-22 21:03:39 +0000681 virtual llvm::Constant *GetPropertyGetFunction();
682 virtual llvm::Constant *GetPropertySetFunction();
683 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000684
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000685 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
686 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000687 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
688 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000689 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000690 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000691 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
692 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000693 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
694 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000695 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
696 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000697 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
698 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000699
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000700 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
701 QualType ObjectTy,
702 llvm::Value *BaseValue,
703 const ObjCIvarDecl *Ivar,
704 const FieldDecl *Field,
705 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000706 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
707 ObjCInterfaceDecl *Interface,
708 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000709};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000710
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000711class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000712private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000713 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000714 llvm::GlobalVariable* ObjCEmptyCacheVar;
715 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000716
Daniel Dunbar11394522009-04-18 08:51:00 +0000717 /// SuperClassReferences - uniqued super class references.
718 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
719
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000720 /// MetaClassReferences - uniqued meta class references.
721 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000722
723 /// EHTypeReferences - uniqued class ehtype references.
724 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000725
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000726 /// FinishNonFragileABIModule - Write out global data structures at the end of
727 /// processing a translation unit.
728 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000729
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000730 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
731 unsigned InstanceStart,
732 unsigned InstanceSize,
733 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000734 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
735 llvm::Constant *IsAGV,
736 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000737 llvm::Constant *ClassRoGV,
738 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000739
740 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
741
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000742 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
743
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000744 /// EmitMethodList - Emit the method list for the given
745 /// implementation. The return value has type MethodListnfABITy.
746 llvm::Constant *EmitMethodList(const std::string &Name,
747 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000748 const ConstantVector &Methods);
749 /// EmitIvarList - Emit the ivar list for the given
750 /// implementation. If ForClass is true the list of class ivars
751 /// (i.e. metaclass ivars) is emitted, otherwise the list of
752 /// interface ivars will be emitted. The return value has type
753 /// IvarListnfABIPtrTy.
754 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000755
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000756 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000757 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000758 unsigned long int offset);
759
Fariborz Jahanianda320092009-01-29 19:24:30 +0000760 /// GetOrEmitProtocol - Get the protocol object for the given
761 /// declaration, emitting it if necessary. The return value has type
762 /// ProtocolPtrTy.
763 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
764
765 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
766 /// object for the given declaration, emitting it if needed. These
767 /// forward references will be filled in with empty bodies if no
768 /// definition is seen. The return value has type ProtocolPtrTy.
769 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
770
771 /// EmitProtocolList - Generate the list of referenced
772 /// protocols. The return value has type ProtocolListPtrTy.
773 llvm::Constant *EmitProtocolList(const std::string &Name,
774 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000775 ObjCProtocolDecl::protocol_iterator end);
776
777 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
778 QualType ResultType,
779 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000780 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000781 QualType Arg0Ty,
782 bool IsSuper,
783 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000784
785 /// GetClassGlobal - Return the global variable for the Objective-C
786 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000787 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
788
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000789 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000790 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000791 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000792 const ObjCInterfaceDecl *ID);
793
794 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
795 /// for the given super class reference.
796 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
797 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000798
799 /// EmitMetaClassRef - Return a Value * of the address of _class_t
800 /// meta-data
801 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
802 const ObjCInterfaceDecl *ID);
803
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000804 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
805 /// the given ivar.
806 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000807 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000808 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000809 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000810
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000811 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
812 /// for the given selector.
813 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000814
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000815 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000816 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000817 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
818 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000819
820 const char *getMetaclassSymbolPrefix() const {
821 return "OBJC_METACLASS_$_";
822 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000823
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000824 const char *getClassSymbolPrefix() const {
825 return "OBJC_CLASS_$_";
826 }
827
Daniel Dunbarb02532a2009-04-19 23:41:48 +0000828 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
829 uint32_t &InstanceStart,
830 uint32_t &InstanceSize);
831
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000832public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000833 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000834 // FIXME. All stubs for now!
835 virtual llvm::Function *ModuleInitFunction();
836
837 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
838 QualType ResultType,
839 Selector Sel,
840 llvm::Value *Receiver,
841 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000842 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000843
844 virtual CodeGen::RValue
845 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
846 QualType ResultType,
847 Selector Sel,
848 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000849 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000850 llvm::Value *Receiver,
851 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000852 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000853
854 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000855 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000856
857 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000858 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000859
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000860 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000861
862 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000863 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000864 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000865
Chris Lattner74391b42009-03-22 21:03:39 +0000866 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000867 return ObjCTypes.GetPropertyFn;
868 }
Chris Lattner74391b42009-03-22 21:03:39 +0000869 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000870 return ObjCTypes.SetPropertyFn;
871 }
Chris Lattner74391b42009-03-22 21:03:39 +0000872 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000873 return ObjCTypes.EnumerationMutationFn;
874 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000875
876 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000877 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000878 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000879 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000880 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000881 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000882 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000883 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000884 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000885 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000886 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000887 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000888 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000889 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000890 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
891 QualType ObjectTy,
892 llvm::Value *BaseValue,
893 const ObjCIvarDecl *Ivar,
894 const FieldDecl *Field,
895 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000896 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
897 ObjCInterfaceDecl *Interface,
898 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000899};
900
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000901} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000902
903/* *** Helper Functions *** */
904
905/// getConstantGEP() - Help routine to construct simple GEPs.
906static llvm::Constant *getConstantGEP(llvm::Constant *C,
907 unsigned idx0,
908 unsigned idx1) {
909 llvm::Value *Idxs[] = {
910 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
911 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
912 };
913 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
914}
915
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000916/// hasObjCExceptionAttribute - Return true if this class or any super
917/// class has the __objc_exception__ attribute.
918static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000919 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000920 return true;
921 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
922 return hasObjCExceptionAttribute(Super);
923 return false;
924}
925
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000926/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000927
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000928CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
929 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000930{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000931 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000932 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000933}
934
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000935/// GetClass - Return a reference to the class for the given interface
936/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000937llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000938 const ObjCInterfaceDecl *ID) {
939 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000940}
941
942/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000943llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000944 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000945}
946
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000947/// Generate a constant CFString object.
948/*
949 struct __builtin_CFString {
950 const int *isa; // point to __CFConstantStringClassReference
951 int flags;
952 const char *str;
953 long length;
954 };
955*/
956
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000957llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000958 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +0000959 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000960}
961
962/// Generates a message send where the super is the receiver. This is
963/// a message send to self with special delivery semantics indicating
964/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000965CodeGen::RValue
966CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000967 QualType ResultType,
968 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000969 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000970 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000971 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000972 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000973 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000974 // Create and init a super structure; this is a (receiver, class)
975 // pair we will pass to objc_msgSendSuper.
976 llvm::Value *ObjCSuper =
977 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
978 llvm::Value *ReceiverAsObject =
979 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
980 CGF.Builder.CreateStore(ReceiverAsObject,
981 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000982
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000983 // If this is a class message the metaclass is passed as the target.
984 llvm::Value *Target;
985 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000986 if (isCategoryImpl) {
987 // Message sent to 'super' in a class method defined in a category
988 // implementation requires an odd treatment.
989 // If we are in a class method, we must retrieve the
990 // _metaclass_ for the current class, pointed at by
991 // the class's "isa" pointer. The following assumes that
992 // isa" is the first ivar in a class (which it must be).
993 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
994 Target = CGF.Builder.CreateStructGEP(Target, 0);
995 Target = CGF.Builder.CreateLoad(Target);
996 }
997 else {
998 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
999 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1000 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1001 Target = Super;
1002 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001003 } else {
1004 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1005 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001006 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1007 // and ObjCTypes types.
1008 const llvm::Type *ClassTy =
1009 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001010 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001011 CGF.Builder.CreateStore(Target,
1012 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1013
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001014 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001015 ObjCSuper, ObjCTypes.SuperPtrCTy,
1016 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001017}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001018
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001019/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001020CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001021 QualType ResultType,
1022 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001023 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001024 bool IsClassMessage,
1025 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001026 llvm::Value *Arg0 =
1027 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001028 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001029 Arg0, CGF.getContext().getObjCIdType(),
1030 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001031}
1032
1033CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001034 QualType ResultType,
1035 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001036 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001037 QualType Arg0Ty,
1038 bool IsSuper,
1039 const CallArgList &CallArgs) {
1040 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001041 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1042 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1043 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001044 CGF.getContext().getObjCSelType()));
1045 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001046
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001047 CodeGenTypes &Types = CGM.getTypes();
1048 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1049 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001050
1051 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001052 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001053 Fn = ObjCTypes.getSendStretFn(IsSuper);
1054 } else if (ResultType->isFloatingType()) {
1055 // FIXME: Sadly, this is wrong. This actually depends on the
1056 // architecture. This happens to be right for x86-32 though.
1057 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1058 } else {
1059 Fn = ObjCTypes.getSendFn(IsSuper);
1060 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001061 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001062 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001063}
1064
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001065llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001066 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001067 // FIXME: I don't understand why gcc generates this, or where it is
1068 // resolved. Investigate. Its also wasteful to look this up over and
1069 // over.
1070 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1071
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001072 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1073 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001074}
1075
Fariborz Jahanianda320092009-01-29 19:24:30 +00001076void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001077 // FIXME: We shouldn't need this, the protocol decl should contain
1078 // enough information to tell us whether this was a declaration or a
1079 // definition.
1080 DefinedProtocols.insert(PD->getIdentifier());
1081
1082 // If we have generated a forward reference to this protocol, emit
1083 // it now. Otherwise do nothing, the protocol objects are lazily
1084 // emitted.
1085 if (Protocols.count(PD->getIdentifier()))
1086 GetOrEmitProtocol(PD);
1087}
1088
Fariborz Jahanianda320092009-01-29 19:24:30 +00001089llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001090 if (DefinedProtocols.count(PD->getIdentifier()))
1091 return GetOrEmitProtocol(PD);
1092 return GetOrEmitProtocolRef(PD);
1093}
1094
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001095/*
1096 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1097 struct _objc_protocol {
1098 struct _objc_protocol_extension *isa;
1099 char *protocol_name;
1100 struct _objc_protocol_list *protocol_list;
1101 struct _objc__method_prototype_list *instance_methods;
1102 struct _objc__method_prototype_list *class_methods
1103 };
1104
1105 See EmitProtocolExtension().
1106*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001107llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1108 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1109
1110 // Early exit if a defining object has already been generated.
1111 if (Entry && Entry->hasInitializer())
1112 return Entry;
1113
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001114 // FIXME: I don't understand why gcc generates this, or where it is
1115 // resolved. Investigate. Its also wasteful to look this up over and
1116 // over.
1117 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1118
Chris Lattner8ec03f52008-11-24 03:54:41 +00001119 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001120
1121 // Construct method lists.
1122 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1123 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001124 for (ObjCProtocolDecl::instmeth_iterator
1125 i = PD->instmeth_begin(CGM.getContext()),
1126 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001127 ObjCMethodDecl *MD = *i;
1128 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1129 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1130 OptInstanceMethods.push_back(C);
1131 } else {
1132 InstanceMethods.push_back(C);
1133 }
1134 }
1135
Douglas Gregor6ab35242009-04-09 21:40:53 +00001136 for (ObjCProtocolDecl::classmeth_iterator
1137 i = PD->classmeth_begin(CGM.getContext()),
1138 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001139 ObjCMethodDecl *MD = *i;
1140 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1141 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1142 OptClassMethods.push_back(C);
1143 } else {
1144 ClassMethods.push_back(C);
1145 }
1146 }
1147
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001148 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001149 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001150 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001151 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001152 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001153 PD->protocol_begin(),
1154 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001155 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001156 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1157 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001158 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1159 InstanceMethods);
1160 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001161 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1162 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001163 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1164 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001165 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1166 Values);
1167
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001168 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001169 // Already created, fix the linkage and update the initializer.
1170 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001171 Entry->setInitializer(Init);
1172 } else {
1173 Entry =
1174 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1175 llvm::GlobalValue::InternalLinkage,
1176 Init,
1177 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1178 &CGM.getModule());
1179 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001180 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001181 UsedGlobals.push_back(Entry);
1182 // FIXME: Is this necessary? Why only for protocol?
1183 Entry->setAlignment(4);
1184 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001185
1186 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001187}
1188
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001189llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001190 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1191
1192 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001193 // We use the initializer as a marker of whether this is a forward
1194 // reference or not. At module finalization we add the empty
1195 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001196 Entry =
1197 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001198 llvm::GlobalValue::ExternalLinkage,
1199 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001200 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001201 &CGM.getModule());
1202 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001203 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001204 UsedGlobals.push_back(Entry);
1205 // FIXME: Is this necessary? Why only for protocol?
1206 Entry->setAlignment(4);
1207 }
1208
1209 return Entry;
1210}
1211
1212/*
1213 struct _objc_protocol_extension {
1214 uint32_t size;
1215 struct objc_method_description_list *optional_instance_methods;
1216 struct objc_method_description_list *optional_class_methods;
1217 struct objc_property_list *instance_properties;
1218 };
1219*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001220llvm::Constant *
1221CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1222 const ConstantVector &OptInstanceMethods,
1223 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001224 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001225 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001226 std::vector<llvm::Constant*> Values(4);
1227 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001228 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001229 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1230 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001231 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1232 OptInstanceMethods);
1233 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001234 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1235 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001236 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1237 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001238 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1239 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001240 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001241
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001242 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001243 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1244 Values[3]->isNullValue())
1245 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1246
1247 llvm::Constant *Init =
1248 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001249
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001250 // No special section, but goes in llvm.used
1251 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1252 Init,
1253 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001254}
1255
1256/*
1257 struct objc_protocol_list {
1258 struct objc_protocol_list *next;
1259 long count;
1260 Protocol *list[];
1261 };
1262*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001263llvm::Constant *
1264CGObjCMac::EmitProtocolList(const std::string &Name,
1265 ObjCProtocolDecl::protocol_iterator begin,
1266 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001267 std::vector<llvm::Constant*> ProtocolRefs;
1268
Daniel Dunbardbc933702008-08-21 21:57:41 +00001269 for (; begin != end; ++begin)
1270 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001271
1272 // Just return null for empty protocol lists
1273 if (ProtocolRefs.empty())
1274 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1275
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001276 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001277 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1278
1279 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001280 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001281 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1282 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1283 Values[2] =
1284 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1285 ProtocolRefs.size()),
1286 ProtocolRefs);
1287
1288 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1289 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001290 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001291 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001292 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1293}
1294
1295/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001296 struct _objc_property {
1297 const char * const name;
1298 const char * const attributes;
1299 };
1300
1301 struct _objc_property_list {
1302 uint32_t entsize; // sizeof (struct _objc_property)
1303 uint32_t prop_count;
1304 struct _objc_property[prop_count];
1305 };
1306*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001307llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1308 const Decl *Container,
1309 const ObjCContainerDecl *OCD,
1310 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001311 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001312 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1313 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001314 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001315 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001316 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001317 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1318 Prop));
1319 }
1320
1321 // Return null for empty list.
1322 if (Properties.empty())
1323 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1324
1325 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001326 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001327 std::vector<llvm::Constant*> Values(3);
1328 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1329 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1330 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1331 Properties.size());
1332 Values[2] = llvm::ConstantArray::get(AT, Properties);
1333 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1334
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001335 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001336 CreateMetadataVar(Name, Init,
1337 (ObjCABI == 2) ? "__DATA, __objc_const" :
1338 "__OBJC,__property,regular,no_dead_strip",
1339 (ObjCABI == 2) ? 8 : 4,
1340 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001341 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001342}
1343
1344/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001345 struct objc_method_description_list {
1346 int count;
1347 struct objc_method_description list[];
1348 };
1349*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001350llvm::Constant *
1351CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1352 std::vector<llvm::Constant*> Desc(2);
1353 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1354 ObjCTypes.SelectorPtrTy);
1355 Desc[1] = GetMethodVarType(MD);
1356 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1357 Desc);
1358}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001359
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001360llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1361 const char *Section,
1362 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001363 // Return null for empty list.
1364 if (Methods.empty())
1365 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1366
1367 std::vector<llvm::Constant*> Values(2);
1368 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1369 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1370 Methods.size());
1371 Values[1] = llvm::ConstantArray::get(AT, Methods);
1372 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1373
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001374 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001375 return llvm::ConstantExpr::getBitCast(GV,
1376 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001377}
1378
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001379/*
1380 struct _objc_category {
1381 char *category_name;
1382 char *class_name;
1383 struct _objc_method_list *instance_methods;
1384 struct _objc_method_list *class_methods;
1385 struct _objc_protocol_list *protocols;
1386 uint32_t size; // <rdar://4585769>
1387 struct _objc_property_list *instance_properties;
1388 };
1389 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001390void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001391 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001392
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001393 // FIXME: This is poor design, the OCD should have a pointer to the
1394 // category decl. Additionally, note that Category can be null for
1395 // the @implementation w/o an @interface case. Sema should just
1396 // create one for us as it does for @implementation so everyone else
1397 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001398 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001399 const ObjCCategoryDecl *Category =
1400 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001401 std::string ExtName(Interface->getNameAsString() + "_" +
1402 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001403
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001404 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1405 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1406 e = OCD->instmeth_end(); i != e; ++i) {
1407 // Instance methods should always be defined.
1408 InstanceMethods.push_back(GetMethodConstant(*i));
1409 }
1410 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1411 e = OCD->classmeth_end(); i != e; ++i) {
1412 // Class methods should always be defined.
1413 ClassMethods.push_back(GetMethodConstant(*i));
1414 }
1415
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001416 std::vector<llvm::Constant*> Values(7);
1417 Values[0] = GetClassName(OCD->getIdentifier());
1418 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001419 Values[2] =
1420 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1421 ExtName,
1422 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001423 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001424 Values[3] =
1425 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001426 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001427 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001428 if (Category) {
1429 Values[4] =
1430 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1431 Category->protocol_begin(),
1432 Category->protocol_end());
1433 } else {
1434 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1435 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001436 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001437
1438 // If there is no category @interface then there can be no properties.
1439 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001440 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001441 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001442 } else {
1443 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1444 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001445
1446 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1447 Values);
1448
1449 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001450 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1451 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001452 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001453 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001454}
1455
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001456// FIXME: Get from somewhere?
1457enum ClassFlags {
1458 eClassFlags_Factory = 0x00001,
1459 eClassFlags_Meta = 0x00002,
1460 // <rdr://5142207>
1461 eClassFlags_HasCXXStructors = 0x02000,
1462 eClassFlags_Hidden = 0x20000,
1463 eClassFlags_ABI2_Hidden = 0x00010,
1464 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1465};
1466
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001467/*
1468 struct _objc_class {
1469 Class isa;
1470 Class super_class;
1471 const char *name;
1472 long version;
1473 long info;
1474 long instance_size;
1475 struct _objc_ivar_list *ivars;
1476 struct _objc_method_list *methods;
1477 struct _objc_cache *cache;
1478 struct _objc_protocol_list *protocols;
1479 // Objective-C 1.0 extensions (<rdr://4585769>)
1480 const char *ivar_layout;
1481 struct _objc_class_ext *ext;
1482 };
1483
1484 See EmitClassExtension();
1485 */
1486void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001487 DefinedSymbols.insert(ID->getIdentifier());
1488
Chris Lattner8ec03f52008-11-24 03:54:41 +00001489 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001490 // FIXME: Gross
1491 ObjCInterfaceDecl *Interface =
1492 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001493 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001494 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001495 Interface->protocol_begin(),
1496 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001497 const llvm::Type *InterfaceTy;
1498 if (Interface->isForwardDecl())
1499 InterfaceTy = llvm::StructType::get(NULL, NULL);
1500 else
1501 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001502 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001503 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001504 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001505
1506 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001507 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508 Flags |= eClassFlags_Hidden;
1509
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001510 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1511 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1512 e = ID->instmeth_end(); i != e; ++i) {
1513 // Instance methods should always be defined.
1514 InstanceMethods.push_back(GetMethodConstant(*i));
1515 }
1516 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1517 e = ID->classmeth_end(); i != e; ++i) {
1518 // Class methods should always be defined.
1519 ClassMethods.push_back(GetMethodConstant(*i));
1520 }
1521
1522 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1523 e = ID->propimpl_end(); i != e; ++i) {
1524 ObjCPropertyImplDecl *PID = *i;
1525
1526 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1527 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1528
1529 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1530 if (llvm::Constant *C = GetMethodConstant(MD))
1531 InstanceMethods.push_back(C);
1532 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1533 if (llvm::Constant *C = GetMethodConstant(MD))
1534 InstanceMethods.push_back(C);
1535 }
1536 }
1537
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001538 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001539 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001540 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001541 // Record a reference to the super class.
1542 LazySymbols.insert(Super->getIdentifier());
1543
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001544 Values[ 1] =
1545 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1546 ObjCTypes.ClassPtrTy);
1547 } else {
1548 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1549 }
1550 Values[ 2] = GetClassName(ID->getIdentifier());
1551 // Version is always 0.
1552 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1553 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1554 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001555 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001556 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001557 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001558 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001559 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001560 // cache is always NULL.
1561 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1562 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001563 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001564 // Values[10] = BuildIvarLayout(ID, true);
1565 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001566 Values[11] = EmitClassExtension(ID);
1567 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1568 Values);
1569
1570 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001571 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1572 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001573 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001574 DefinedClasses.push_back(GV);
1575}
1576
1577llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1578 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001579 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001580 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001581 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001582 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001583
Daniel Dunbar04d40782009-04-14 06:00:08 +00001584 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001585 Flags |= eClassFlags_Hidden;
1586
1587 std::vector<llvm::Constant*> Values(12);
1588 // The isa for the metaclass is the root of the hierarchy.
1589 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1590 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1591 Root = Super;
1592 Values[ 0] =
1593 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1594 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001595 // The super class for the metaclass is emitted as the name of the
1596 // super class. The runtime fixes this up to point to the
1597 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001598 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1599 Values[ 1] =
1600 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1601 ObjCTypes.ClassPtrTy);
1602 } else {
1603 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1604 }
1605 Values[ 2] = GetClassName(ID->getIdentifier());
1606 // Version is always 0.
1607 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1608 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1609 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001610 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001611 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001612 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001613 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001614 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001615 // cache is always NULL.
1616 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1617 Values[ 9] = Protocols;
1618 // ivar_layout for metaclass is always NULL.
1619 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1620 // The class extension is always unused for metaclasses.
1621 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1622 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1623 Values);
1624
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001625 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001626 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001627
1628 // Check for a forward reference.
1629 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1630 if (GV) {
1631 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1632 "Forward metaclass reference has incorrect type.");
1633 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1634 GV->setInitializer(Init);
1635 } else {
1636 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1637 llvm::GlobalValue::InternalLinkage,
1638 Init, Name,
1639 &CGM.getModule());
1640 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001641 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001642 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001643 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001644
1645 return GV;
1646}
1647
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001648llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001649 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001650
1651 // FIXME: Should we look these up somewhere other than the
1652 // module. Its a bit silly since we only generate these while
1653 // processing an implementation, so exactly one pointer would work
1654 // if know when we entered/exitted an implementation block.
1655
1656 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001657 // Previously, metaclass with internal linkage may have been defined.
1658 // pass 'true' as 2nd argument so it is returned.
1659 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001660 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1661 "Forward metaclass reference has incorrect type.");
1662 return GV;
1663 } else {
1664 // Generate as an external reference to keep a consistent
1665 // module. This will be patched up when we emit the metaclass.
1666 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1667 llvm::GlobalValue::ExternalLinkage,
1668 0,
1669 Name,
1670 &CGM.getModule());
1671 }
1672}
1673
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001674/*
1675 struct objc_class_ext {
1676 uint32_t size;
1677 const char *weak_ivar_layout;
1678 struct _objc_property_list *properties;
1679 };
1680*/
1681llvm::Constant *
1682CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1683 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001684 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001685
1686 std::vector<llvm::Constant*> Values(3);
1687 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001688 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001689 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001690 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001691 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001692 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001693
1694 // Return null if no extension bits are used.
1695 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1696 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1697
1698 llvm::Constant *Init =
1699 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001700 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001701 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1702 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001703}
1704
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001705/// getInterfaceDeclForIvar - Get the interface declaration node where
1706/// this ivar is declared in.
1707/// FIXME. Ideally, this info should be in the ivar node. But currently
1708/// it is not and prevailing wisdom is that ASTs should not have more
1709/// info than is absolutely needed, even though this info reflects the
1710/// source language.
1711///
1712static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1713 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001714 const ObjCIvarDecl *IVD,
1715 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001716 if (!OI)
1717 return 0;
1718 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1719 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1720 E = OI->ivar_end(); I != E; ++I)
1721 if ((*I)->getIdentifier() == IVD->getIdentifier())
1722 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001723 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001724 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1725 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001726 ObjCPropertyDecl *PDecl = (*I);
1727 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1728 if (IV->getIdentifier() == IVD->getIdentifier())
1729 return OI;
1730 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001731 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001732}
1733
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001734/*
1735 struct objc_ivar {
1736 char *ivar_name;
1737 char *ivar_type;
1738 int ivar_offset;
1739 };
1740
1741 struct objc_ivar_list {
1742 int ivar_count;
1743 struct objc_ivar list[count];
1744 };
1745 */
1746llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001747 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001748 std::vector<llvm::Constant*> Ivars, Ivar(3);
1749
1750 // When emitting the root class GCC emits ivar entries for the
1751 // actual class structure. It is not clear if we need to follow this
1752 // behavior; for now lets try and get away with not doing it. If so,
1753 // the cleanest solution would be to make up an ObjCInterfaceDecl
1754 // for the class.
1755 if (ForClass)
1756 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001757
1758 ObjCInterfaceDecl *OID =
1759 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001760 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001761
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001762 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1763 GetNamedIvarList(OID, OIvars);
1764
1765 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1766 ObjCIvarDecl *IVD = OIvars[i];
1767 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001768 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00001769 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00001770 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
1771 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001772 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001773 }
1774
1775 // Return null for empty list.
1776 if (Ivars.empty())
1777 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1778
1779 std::vector<llvm::Constant*> Values(2);
1780 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1781 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1782 Ivars.size());
1783 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1784 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1785
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001786 llvm::GlobalVariable *GV;
1787 if (ForClass)
1788 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001789 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1790 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001791 else
1792 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1793 + ID->getNameAsString(),
1794 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001795 4, true);
1796 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001797}
1798
1799/*
1800 struct objc_method {
1801 SEL method_name;
1802 char *method_types;
1803 void *method;
1804 };
1805
1806 struct objc_method_list {
1807 struct objc_method_list *obsolete;
1808 int count;
1809 struct objc_method methods_list[count];
1810 };
1811*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001812
1813/// GetMethodConstant - Return a struct objc_method constant for the
1814/// given method if it has been defined. The result is null if the
1815/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001816llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001817 // FIXME: Use DenseMap::lookup
1818 llvm::Function *Fn = MethodDefinitions[MD];
1819 if (!Fn)
1820 return 0;
1821
1822 std::vector<llvm::Constant*> Method(3);
1823 Method[0] =
1824 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1825 ObjCTypes.SelectorPtrTy);
1826 Method[1] = GetMethodVarType(MD);
1827 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1828 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1829}
1830
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001831llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1832 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001833 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001834 // Return null for empty list.
1835 if (Methods.empty())
1836 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1837
1838 std::vector<llvm::Constant*> Values(3);
1839 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1840 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1841 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1842 Methods.size());
1843 Values[2] = llvm::ConstantArray::get(AT, Methods);
1844 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1845
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001846 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001847 return llvm::ConstantExpr::getBitCast(GV,
1848 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001849}
1850
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001851llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001852 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001853 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001854 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001855
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001856 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001857 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001858 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001859 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001860 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001861 llvm::GlobalValue::InternalLinkage,
1862 Name,
1863 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001864 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001865
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001866 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001867}
1868
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001869uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001870 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001871 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001872 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1873
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001874 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001875 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1876 // FIXME: The "field no" for bitfields is something completely
1877 // different; it is the offset in multiples of the base type size!
1878 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1879 const llvm::Type *Ty =
1880 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1881 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1882 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001883}
1884
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001885/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001886uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1887 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001888 const FieldDecl *Field) {
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00001889 // Is this a c struct?
1890 if (!OI)
1891 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001892 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001893 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1894 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001895}
1896
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001897llvm::GlobalVariable *
1898CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1899 llvm::Constant *Init,
1900 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001901 unsigned Align,
1902 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001903 const llvm::Type *Ty = Init->getType();
1904 llvm::GlobalVariable *GV =
1905 new llvm::GlobalVariable(Ty, false,
1906 llvm::GlobalValue::InternalLinkage,
1907 Init,
1908 Name,
1909 &CGM.getModule());
1910 if (Section)
1911 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001912 if (Align)
1913 GV->setAlignment(Align);
1914 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001915 UsedGlobals.push_back(GV);
1916 return GV;
1917}
1918
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001919llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001920 // Abuse this interface function as a place to finalize.
1921 FinishModule();
1922
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001923 return NULL;
1924}
1925
Chris Lattner74391b42009-03-22 21:03:39 +00001926llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001927 return ObjCTypes.GetPropertyFn;
1928}
1929
Chris Lattner74391b42009-03-22 21:03:39 +00001930llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001931 return ObjCTypes.SetPropertyFn;
1932}
1933
Chris Lattner74391b42009-03-22 21:03:39 +00001934llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001935 return ObjCTypes.EnumerationMutationFn;
1936}
1937
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001938/*
1939
1940Objective-C setjmp-longjmp (sjlj) Exception Handling
1941--
1942
1943The basic framework for a @try-catch-finally is as follows:
1944{
1945 objc_exception_data d;
1946 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001947 bool _call_try_exit = true;
1948
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001949 objc_exception_try_enter(&d);
1950 if (!setjmp(d.jmp_buf)) {
1951 ... try body ...
1952 } else {
1953 // exception path
1954 id _caught = objc_exception_extract(&d);
1955
1956 // enter new try scope for handlers
1957 if (!setjmp(d.jmp_buf)) {
1958 ... match exception and execute catch blocks ...
1959
1960 // fell off end, rethrow.
1961 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001962 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001963 } else {
1964 // exception in catch block
1965 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001966 _call_try_exit = false;
1967 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001968 }
1969 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001970 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001971
1972finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001973 if (_call_try_exit)
1974 objc_exception_try_exit(&d);
1975
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001976 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001977 ... dispatch to finally destination ...
1978
1979finally_rethrow:
1980 objc_exception_throw(_rethrow);
1981
1982finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001983}
1984
1985This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001986uses _rethrow to determine if objc_exception_try_exit should be called
1987and if the object should be rethrown. This breaks in the face of
1988throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001989
1990We specialize this framework for a few particular circumstances:
1991
1992 - If there are no catch blocks, then we avoid emitting the second
1993 exception handling context.
1994
1995 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1996 e)) we avoid emitting the code to rethrow an uncaught exception.
1997
1998 - FIXME: If there is no @finally block we can do a few more
1999 simplifications.
2000
2001Rethrows and Jumps-Through-Finally
2002--
2003
2004Support for implicit rethrows and jumping through the finally block is
2005handled by storing the current exception-handling context in
2006ObjCEHStack.
2007
Daniel Dunbar898d5082008-09-30 01:06:03 +00002008In order to implement proper @finally semantics, we support one basic
2009mechanism for jumping through the finally block to an arbitrary
2010destination. Constructs which generate exits from a @try or @catch
2011block use this mechanism to implement the proper semantics by chaining
2012jumps, as necessary.
2013
2014This mechanism works like the one used for indirect goto: we
2015arbitrarily assign an ID to each destination and store the ID for the
2016destination in a variable prior to entering the finally block. At the
2017end of the finally block we simply create a switch to the proper
2018destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002019
2020Code gen for @synchronized(expr) stmt;
2021Effectively generating code for:
2022objc_sync_enter(expr);
2023@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002024*/
2025
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002026void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2027 const Stmt &S) {
2028 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002029 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002030 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002031 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002032 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2033 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2034 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002035
2036 // For @synchronized, call objc_sync_enter(sync.expr). The
2037 // evaluation of the expression must occur before we enter the
2038 // @synchronized. We can safely avoid a temp here because jumps into
2039 // @synchronized are illegal & this will dominate uses.
2040 llvm::Value *SyncArg = 0;
2041 if (!isTry) {
2042 SyncArg =
2043 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2044 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002045 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002046 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002047
2048 // Push an EH context entry, used for handling rethrows and jumps
2049 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002050 CGF.PushCleanupBlock(FinallyBlock);
2051
Anders Carlsson273558f2009-02-07 21:37:21 +00002052 CGF.ObjCEHValueStack.push_back(0);
2053
Daniel Dunbar898d5082008-09-30 01:06:03 +00002054 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002055 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2056 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002057 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2058 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002059 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2060 "_call_try_exit");
2061 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2062
Anders Carlsson80f25672008-09-09 17:59:25 +00002063 // Enter a new try block and call setjmp.
2064 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2065 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2066 "jmpbufarray");
2067 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2068 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2069 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002070
Daniel Dunbar55e87422008-11-11 02:29:29 +00002071 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2072 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002073 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002074 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002075
2076 // Emit the @try block.
2077 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002078 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2079 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002080 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002081
2082 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002083 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002084
2085 // Retrieve the exception object. We may emit multiple blocks but
2086 // nothing can cross this so the value is already in SSA form.
2087 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2088 ExceptionData,
2089 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002090 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002091 if (!isTry)
2092 {
2093 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002094 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002095 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002096 }
2097 else if (const ObjCAtCatchStmt* CatchStmt =
2098 cast<ObjCAtTryStmt>(S).getCatchStmts())
2099 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002100 // Enter a new exception try block (in case a @catch block throws
2101 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002102 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002103
Anders Carlsson80f25672008-09-09 17:59:25 +00002104 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2105 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002106 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002107
Daniel Dunbar55e87422008-11-11 02:29:29 +00002108 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2109 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002110 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002111
2112 CGF.EmitBlock(CatchBlock);
2113
Daniel Dunbar55e40722008-09-27 07:03:52 +00002114 // Handle catch list. As a special case we check if everything is
2115 // matched and avoid generating code for falling off the end if
2116 // so.
2117 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002118 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002119 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002120
Steve Naroff7ba138a2009-03-03 19:52:17 +00002121 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002122 const PointerType *PT = 0;
2123
Anders Carlsson80f25672008-09-09 17:59:25 +00002124 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002125 if (!CatchParam) {
2126 AllMatched = true;
2127 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002128 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002129
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002130 // catch(id e) always matches.
2131 // FIXME: For the time being we also match id<X>; this should
2132 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002133 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002134 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002135 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002136 }
2137
Daniel Dunbar55e40722008-09-27 07:03:52 +00002138 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002139 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002140 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002141 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002142 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002143 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002144
Anders Carlssondde0a942008-09-11 09:15:33 +00002145 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002146 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002147 break;
2148 }
2149
Daniel Dunbar129271a2008-09-27 07:36:24 +00002150 assert(PT && "Unexpected non-pointer type in @catch");
2151 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002152 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002153 assert(ObjCType && "Catch parameter must have Objective-C type!");
2154
2155 // Check if the @catch block matches the exception object.
2156 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2157
Anders Carlsson80f25672008-09-09 17:59:25 +00002158 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2159 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002160
Daniel Dunbar55e87422008-11-11 02:29:29 +00002161 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002162
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002163 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002164 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002165
2166 // Emit the @catch block.
2167 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002168 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002169 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002170
2171 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002172 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002173 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002174 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002175
2176 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002177 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002178
2179 CGF.EmitBlock(NextCatchBlock);
2180 }
2181
Daniel Dunbar55e40722008-09-27 07:03:52 +00002182 if (!AllMatched) {
2183 // None of the handlers caught the exception, so store it to be
2184 // rethrown at the end of the @finally block.
2185 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002186 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002187 }
2188
2189 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002190 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002191 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2192 ExceptionData),
2193 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002194 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002195 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002196 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002197 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002198 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002199 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002200 }
2201
Daniel Dunbar898d5082008-09-30 01:06:03 +00002202 // Pop the exception-handling stack entry. It is important to do
2203 // this now, because the code in the @finally block is not in this
2204 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002205 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2206
Anders Carlsson273558f2009-02-07 21:37:21 +00002207 CGF.ObjCEHValueStack.pop_back();
2208
Anders Carlsson80f25672008-09-09 17:59:25 +00002209 // Emit the @finally block.
2210 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002211 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2212
2213 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2214
2215 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002216 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002217
2218 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002219 if (isTry) {
2220 if (const ObjCAtFinallyStmt* FinallyStmt =
2221 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2222 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002223 } else {
2224 // Emit objc_sync_exit(expr); as finally's sole statement for
2225 // @synchronized.
2226 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002227 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002228
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002229 // Emit the switch block
2230 if (Info.SwitchBlock)
2231 CGF.EmitBlock(Info.SwitchBlock);
2232 if (Info.EndBlock)
2233 CGF.EmitBlock(Info.EndBlock);
2234
Daniel Dunbar898d5082008-09-30 01:06:03 +00002235 CGF.EmitBlock(FinallyRethrow);
2236 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2237 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002238 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002239
2240 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002241}
2242
2243void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002244 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002245 llvm::Value *ExceptionAsObject;
2246
2247 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2248 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2249 ExceptionAsObject =
2250 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2251 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002252 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002253 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002254 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002255 }
2256
2257 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002258 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002259
2260 // Clear the insertion point to indicate we are in unreachable code.
2261 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002262}
2263
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002264/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002265/// object: objc_read_weak (id *src)
2266///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002267llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002268 llvm::Value *AddrWeakObj)
2269{
Eli Friedman8339b352009-03-07 03:57:15 +00002270 const llvm::Type* DestTy =
2271 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002272 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002273 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002274 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002275 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002276 return read_weak;
2277}
2278
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002279/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2280/// objc_assign_weak (id src, id *dst)
2281///
2282void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2283 llvm::Value *src, llvm::Value *dst)
2284{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002285 const llvm::Type * SrcTy = src->getType();
2286 if (!isa<llvm::PointerType>(SrcTy)) {
2287 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2288 assert(Size <= 8 && "does not support size > 8");
2289 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2290 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002291 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2292 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002293 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2294 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002295 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002296 src, dst, "weakassign");
2297 return;
2298}
2299
Fariborz Jahanian58626502008-11-19 00:59:10 +00002300/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2301/// objc_assign_global (id src, id *dst)
2302///
2303void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2304 llvm::Value *src, llvm::Value *dst)
2305{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002306 const llvm::Type * SrcTy = src->getType();
2307 if (!isa<llvm::PointerType>(SrcTy)) {
2308 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2309 assert(Size <= 8 && "does not support size > 8");
2310 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2311 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002312 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2313 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002314 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2315 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002316 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2317 src, dst, "globalassign");
2318 return;
2319}
2320
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002321/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2322/// objc_assign_ivar (id src, id *dst)
2323///
2324void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2325 llvm::Value *src, llvm::Value *dst)
2326{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002327 const llvm::Type * SrcTy = src->getType();
2328 if (!isa<llvm::PointerType>(SrcTy)) {
2329 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2330 assert(Size <= 8 && "does not support size > 8");
2331 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2332 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002333 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2334 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002335 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2336 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2337 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2338 src, dst, "assignivar");
2339 return;
2340}
2341
Fariborz Jahanian58626502008-11-19 00:59:10 +00002342/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2343/// objc_assign_strongCast (id src, id *dst)
2344///
2345void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2346 llvm::Value *src, llvm::Value *dst)
2347{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002348 const llvm::Type * SrcTy = src->getType();
2349 if (!isa<llvm::PointerType>(SrcTy)) {
2350 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2351 assert(Size <= 8 && "does not support size > 8");
2352 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2353 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002354 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2355 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002356 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2357 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002358 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2359 src, dst, "weakassign");
2360 return;
2361}
2362
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002363/// EmitObjCValueForIvar - Code Gen for ivar reference.
2364///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002365LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2366 QualType ObjectTy,
2367 llvm::Value *BaseValue,
2368 const ObjCIvarDecl *Ivar,
2369 const FieldDecl *Field,
2370 unsigned CVRQualifiers) {
2371 if (Ivar->isBitField())
2372 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2373 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002374 // TODO: Add a special case for isa (index 0)
2375 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2376 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002377 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002378 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2379 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002380 LValue::SetObjCIvar(LV, true);
2381 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002382}
2383
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002384llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2385 ObjCInterfaceDecl *Interface,
2386 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002387 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002388 const FieldDecl *Field =
2389 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002390 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002391 return llvm::ConstantInt::get(
2392 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2393 Offset);
2394}
2395
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002396/* *** Private Interface *** */
2397
2398/// EmitImageInfo - Emit the image info marker used to encode some module
2399/// level information.
2400///
2401/// See: <rdr://4810609&4810587&4810587>
2402/// struct IMAGE_INFO {
2403/// unsigned version;
2404/// unsigned flags;
2405/// };
2406enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002407 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2408 // this implies.
2409 eImageInfo_GarbageCollected = (1 << 1),
2410 eImageInfo_GCOnly = (1 << 2),
2411 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2412
2413 // A flag indicating that the module has no instances of an
2414 // @synthesize of a superclass variable. <rdar://problem/6803242>
2415 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002416};
2417
2418void CGObjCMac::EmitImageInfo() {
2419 unsigned version = 0; // Version is unused?
2420 unsigned flags = 0;
2421
2422 // FIXME: Fix and continue?
2423 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2424 flags |= eImageInfo_GarbageCollected;
2425 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2426 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002427
2428 // We never allow @synthesize of a superclass property.
2429 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002430
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002431 // Emitted as int[2];
2432 llvm::Constant *values[2] = {
2433 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2434 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2435 };
2436 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002437
2438 const char *Section;
2439 if (ObjCABI == 1)
2440 Section = "__OBJC, __image_info,regular";
2441 else
2442 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002443 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002444 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2445 llvm::ConstantArray::get(AT, values, 2),
2446 Section,
2447 0,
2448 true);
2449 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002450}
2451
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002452
2453// struct objc_module {
2454// unsigned long version;
2455// unsigned long size;
2456// const char *name;
2457// Symtab symtab;
2458// };
2459
2460// FIXME: Get from somewhere
2461static const int ModuleVersion = 7;
2462
2463void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002464 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002465
2466 std::vector<llvm::Constant*> Values(4);
2467 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2468 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002469 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002470 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002471 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002472 CreateMetadataVar("\01L_OBJC_MODULES",
2473 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2474 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002475 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002476}
2477
2478llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002479 unsigned NumClasses = DefinedClasses.size();
2480 unsigned NumCategories = DefinedCategories.size();
2481
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002482 // Return null if no symbols were defined.
2483 if (!NumClasses && !NumCategories)
2484 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2485
2486 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002487 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2488 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2489 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2490 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2491
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002492 // The runtime expects exactly the list of defined classes followed
2493 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002494 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002495 for (unsigned i=0; i<NumClasses; i++)
2496 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2497 ObjCTypes.Int8PtrTy);
2498 for (unsigned i=0; i<NumCategories; i++)
2499 Symbols[NumClasses + i] =
2500 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2501 ObjCTypes.Int8PtrTy);
2502
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002503 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002504 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002505 NumClasses + NumCategories),
2506 Symbols);
2507
2508 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2509
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002510 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002511 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2512 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002513 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002514 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2515}
2516
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002517llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002518 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002519 LazySymbols.insert(ID->getIdentifier());
2520
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002521 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2522
2523 if (!Entry) {
2524 llvm::Constant *Casted =
2525 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2526 ObjCTypes.ClassPtrTy);
2527 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002528 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2529 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002530 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002531 }
2532
2533 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002534}
2535
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002536llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002537 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2538
2539 if (!Entry) {
2540 llvm::Constant *Casted =
2541 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2542 ObjCTypes.SelectorPtrTy);
2543 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002544 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2545 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002546 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002547 }
2548
2549 return Builder.CreateLoad(Entry, false, "tmp");
2550}
2551
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002552llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002553 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002554
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002555 if (!Entry)
2556 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2557 llvm::ConstantArray::get(Ident->getName()),
2558 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002559 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002560
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002561 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002562}
2563
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002564/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2565/// interface declaration.
2566const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2567 const ObjCInterfaceDecl *OID) const {
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002568 // FIXME: When does this happen? It seems pretty bad to do this...
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002569 if (OID->isForwardDecl())
2570 return CGM.getTargetData().getStructLayout(llvm::StructType::get(NULL,
2571 NULL));
2572
2573 QualType T =
2574 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2575 const llvm::StructType *InterfaceTy =
2576 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2577 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002578}
2579
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002580/// GetIvarLayoutName - Returns a unique constant for the given
2581/// ivar layout bitmap.
2582llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2583 const ObjCCommonTypesHelper &ObjCTypes) {
2584 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2585}
2586
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002587void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2588 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002589 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002590 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002591 unsigned int BytePos, bool ForStrongLayout,
2592 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002593 bool IsUnion = (RD && RD->isUnion());
2594 uint64_t MaxUnionIvarSize = 0;
2595 uint64_t MaxSkippedUnionIvarSize = 0;
2596 FieldDecl *MaxField = 0;
2597 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002598 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002599 if (RecFields.empty())
2600 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002601 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002602 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002603 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2604 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2605
2606 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2607
2608 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002609 FieldDecl *Field = RecFields[i];
2610 // Skip over unnamed or bitfields
2611 if (!Field->getIdentifier() || Field->isBitField())
2612 continue;
2613 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002614 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002615 if (FQT->isUnionType())
2616 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002617 else
2618 assert(FQT->isRecordType() &&
2619 "only union/record is supported for ivar layout bitmap");
2620
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002621 const RecordType *RT = FQT->getAsRecordType();
2622 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002623 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002624 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2625 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002626 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2627 const llvm::StructLayout *RecLayout =
2628 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2629
2630 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002631 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002632 ForStrongLayout, Index, SkIndex,
2633 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002634 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002635 continue;
2636 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002637
2638 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002639 const ConstantArrayType *CArray =
2640 dyn_cast_or_null<ConstantArrayType>(Array);
2641 assert(CArray && "only array with know element size is supported");
2642 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002643 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2644 const ConstantArrayType *CArray =
2645 dyn_cast_or_null<ConstantArrayType>(Array);
2646 FQT = CArray->getElementType();
2647 }
2648
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002649 assert(!FQT->isUnionType() &&
2650 "layout for array of unions not supported");
2651 if (FQT->isRecordType()) {
2652 uint64_t ElCount = CArray->getSize().getZExtValue();
2653 int OldIndex = Index;
2654 int OldSkIndex = SkIndex;
2655
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002656 // FIXME - Use a common routine with the above!
2657 const RecordType *RT = FQT->getAsRecordType();
2658 const RecordDecl *RD = RT->getDecl();
2659 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002660 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2661 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002662 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2663 const llvm::StructLayout *RecLayout =
2664 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002665
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002666 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002667 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002668 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002669 ForStrongLayout, Index, SkIndex,
2670 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002671 TmpRecFields.clear();
2672
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002673 // Replicate layout information for each array element. Note that
2674 // one element is already done.
2675 uint64_t ElIx = 1;
2676 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2677 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002678 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002679 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2680 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002681 GC_IVAR gcivar;
2682 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2683 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2684 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002685 }
2686
Chris Lattnerf1690852009-03-31 08:48:01 +00002687 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002688 GC_IVAR skivar;
2689 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2690 skivar.ivar_size = SkipIvars[i].ivar_size;
2691 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002692 }
2693 }
2694 continue;
2695 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002696 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002697 // At this point, we are done with Record/Union and array there of.
2698 // For other arrays we are down to its element type.
2699 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2700 do {
2701 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2702 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2703 break;
2704 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002705 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002706 GCAttr = QualType::Strong;
2707 break;
2708 }
2709 else if (const PointerType *PT = FQT->getAsPointerType()) {
2710 FQT = PT->getPointeeType();
2711 }
2712 else {
2713 break;
2714 }
2715 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002716
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002717 if ((ForStrongLayout && GCAttr == QualType::Strong)
2718 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2719 if (IsUnion)
2720 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002721 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2722 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002723 if (UnionIvarSize > MaxUnionIvarSize)
2724 {
2725 MaxUnionIvarSize = UnionIvarSize;
2726 MaxField = Field;
2727 }
2728 }
2729 else
2730 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002731 GC_IVAR gcivar;
2732 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2733 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2734 WordSizeInBits;
2735 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002736 }
2737 }
2738 else if ((ForStrongLayout &&
2739 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2740 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2741 if (IsUnion)
2742 {
2743 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2744 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2745 {
2746 MaxSkippedUnionIvarSize = UnionIvarSize;
2747 MaxSkippedField = Field;
2748 }
2749 }
2750 else
2751 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002752 GC_IVAR skivar;
2753 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2754 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2755 WordSizeInBits;
2756 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002757 }
2758 }
2759 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002760 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002761 GC_IVAR gcivar;
2762 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2763 gcivar.ivar_size = MaxUnionIvarSize;
2764 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002765 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002766
2767 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002768 GC_IVAR skivar;
2769 skivar.ivar_bytepos = BytePos +
2770 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2771 skivar.ivar_size = MaxSkippedUnionIvarSize;
2772 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002773 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002774}
2775
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002776static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002777IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002778{
2779 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2780 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2781
2782 if (sa < sb)
2783 return -1;
2784 if (sa > sb)
2785 return 1;
2786 return 0;
2787}
2788
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002789/// BuildIvarLayout - Builds ivar layout bitmap for the class
2790/// implementation for the __strong or __weak case.
2791/// The layout map displays which words in ivar list must be skipped
2792/// and which must be scanned by GC (see below). String is built of bytes.
2793/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2794/// of words to skip and right nibble is count of words to scan. So, each
2795/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2796/// represented by a 0x00 byte which also ends the string.
2797/// 1. when ForStrongLayout is true, following ivars are scanned:
2798/// - id, Class
2799/// - object *
2800/// - __strong anything
2801///
2802/// 2. When ForStrongLayout is false, following ivars are scanned:
2803/// - __weak anything
2804///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002805llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002806 const ObjCImplementationDecl *OMD,
2807 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002808 int Index = -1;
2809 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002810 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002811 int SkipScan;
2812 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002813 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2814 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2815 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002816
Chris Lattnerf1690852009-03-31 08:48:01 +00002817 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002818 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002819 CGM.getContext().CollectObjCIvars(OI, RecFields);
2820 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002821 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002822
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002823 SkipIvars.clear();
2824 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002825
2826 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002827 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2828 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002829 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002830 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002831
2832 // Sort on byte position in case we encounterred a union nested in
2833 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002834 if (hasUnion && !IvarsInfo.empty())
2835 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2836 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002837 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2838
2839 // Build the string of skip/scan nibbles
2840 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002841 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002842 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002843 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002844 if (IvarsInfo[0].ivar_bytepos == 0) {
2845 WordsToSkip = 0;
2846 WordsToScan = IvarsInfo[0].ivar_size;
2847 }
2848 else {
2849 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2850 WordsToScan = IvarsInfo[0].ivar_size;
2851 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002852 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002853 {
2854 unsigned int TailPrevGCObjC =
2855 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2856 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2857 {
2858 // consecutive 'scanned' object pointers.
2859 WordsToScan += IvarsInfo[i].ivar_size;
2860 }
2861 else
2862 {
2863 // Skip over 'gc'able object pointer which lay over each other.
2864 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2865 continue;
2866 // Must skip over 1 or more words. We save current skip/scan values
2867 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002868 SKIP_SCAN SkScan;
2869 SkScan.skip = WordsToSkip;
2870 SkScan.scan = WordsToScan;
2871 SkipScanIvars.push_back(SkScan); ++SkipScan;
2872
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002873 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002874 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2875 SkScan.scan = 0;
2876 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002877 WordsToSkip = 0;
2878 WordsToScan = IvarsInfo[i].ivar_size;
2879 }
2880 }
2881 if (WordsToScan > 0)
2882 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002883 SKIP_SCAN SkScan;
2884 SkScan.skip = WordsToSkip;
2885 SkScan.scan = WordsToScan;
2886 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002887 }
2888
2889 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002890 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002891 {
2892 int LastByteSkipped =
2893 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2894 int LastByteScanned =
2895 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2896 BytesSkipped = (LastByteSkipped > LastByteScanned);
2897 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2898 if (BytesSkipped)
2899 {
2900 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002901 SKIP_SCAN SkScan;
2902 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2903 SkScan.scan = 0;
2904 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002905 }
2906 }
2907 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2908 // as 0xMN.
2909 for (int i = 0; i <= SkipScan; i++)
2910 {
2911 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2912 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2913 // 0xM0 followed by 0x0N detected.
2914 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2915 for (int j = i+1; j < SkipScan; j++)
2916 SkipScanIvars[j] = SkipScanIvars[j+1];
2917 --SkipScan;
2918 }
2919 }
2920
2921 // Generate the string.
2922 std::string BitMap;
2923 for (int i = 0; i <= SkipScan; i++)
2924 {
2925 unsigned char byte;
2926 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2927 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2928 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2929 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2930
2931 if (skip_small > 0 || skip_big > 0)
2932 BytesSkipped = true;
2933 // first skip big.
2934 for (unsigned int ix = 0; ix < skip_big; ix++)
2935 BitMap += (unsigned char)(0xf0);
2936
2937 // next (skip small, scan)
2938 if (skip_small)
2939 {
2940 byte = skip_small << 4;
2941 if (scan_big > 0)
2942 {
2943 byte |= 0xf;
2944 --scan_big;
2945 }
2946 else if (scan_small)
2947 {
2948 byte |= scan_small;
2949 scan_small = 0;
2950 }
2951 BitMap += byte;
2952 }
2953 // next scan big
2954 for (unsigned int ix = 0; ix < scan_big; ix++)
2955 BitMap += (unsigned char)(0x0f);
2956 // last scan small
2957 if (scan_small)
2958 {
2959 byte = scan_small;
2960 BitMap += byte;
2961 }
2962 }
2963 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002964 unsigned char zero = 0;
2965 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002966
2967 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
2968 printf("\n%s ivar layout for class '%s': ",
2969 ForStrongLayout ? "strong" : "weak",
2970 OMD->getClassInterface()->getNameAsCString());
2971 const unsigned char *s = (unsigned char*)BitMap.c_str();
2972 for (unsigned i = 0; i < BitMap.size(); i++)
2973 if (!(s[i] & 0xf0))
2974 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2975 else
2976 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2977 printf("\n");
2978 }
2979
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002980 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2981 // final layout.
2982 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002983 return llvm::Constant::getNullValue(PtrTy);
2984 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2985 llvm::ConstantArray::get(BitMap.c_str()),
2986 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002987 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002988 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002989}
2990
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002991llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002992 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2993
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002994 // FIXME: Avoid std::string copying.
2995 if (!Entry)
2996 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2997 llvm::ConstantArray::get(Sel.getAsString()),
2998 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002999 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003000
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003001 return getConstantGEP(Entry, 0, 0);
3002}
3003
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003004// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003005llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003006 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3007}
3008
3009// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003010llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003011 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3012}
3013
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003014llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003015 std::string TypeStr;
3016 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3017
3018 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003019
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003020 if (!Entry)
3021 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3022 llvm::ConstantArray::get(TypeStr),
3023 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003024 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003025
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003026 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003027}
3028
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003029llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003030 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003031 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3032 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003033
3034 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3035
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003036 if (!Entry)
3037 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3038 llvm::ConstantArray::get(TypeStr),
3039 "__TEXT,__cstring,cstring_literals",
3040 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003041
3042 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003043}
3044
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003045// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003046llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003047 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3048
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003049 if (!Entry)
3050 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3051 llvm::ConstantArray::get(Ident->getName()),
3052 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003053 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003054
3055 return getConstantGEP(Entry, 0, 0);
3056}
3057
3058// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003059// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003060llvm::Constant *
3061 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3062 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003063 std::string TypeStr;
3064 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003065 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3066}
3067
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003068void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3069 const ObjCContainerDecl *CD,
3070 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003071 NameOut = '\01';
3072 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003073 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003074 assert (CD && "Missing container decl in GetNameForMethod");
3075 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003076 if (const ObjCCategoryImplDecl *CID =
3077 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3078 NameOut += '(';
3079 NameOut += CID->getNameAsString();
3080 NameOut+= ')';
3081 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003082 NameOut += ' ';
3083 NameOut += D->getSelector().getAsString();
3084 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003085}
3086
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003087void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003088 EmitModuleInfo();
3089
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003090 // Emit the dummy bodies for any protocols which were referenced but
3091 // never defined.
3092 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3093 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3094 if (i->second->hasInitializer())
3095 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003096
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003097 std::vector<llvm::Constant*> Values(5);
3098 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3099 Values[1] = GetClassName(i->first);
3100 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3101 Values[3] = Values[4] =
3102 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3103 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3104 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3105 Values));
3106 }
3107
3108 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003109 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003110 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003111 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003112 }
3113
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003114 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003115 llvm::GlobalValue *GV =
3116 new llvm::GlobalVariable(AT, false,
3117 llvm::GlobalValue::AppendingLinkage,
3118 llvm::ConstantArray::get(AT, Used),
3119 "llvm.used",
3120 &CGM.getModule());
3121
3122 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003123
3124 // Add assembler directives to add lazy undefined symbol references
3125 // for classes which are referenced but not defined. This is
3126 // important for correct linker interaction.
3127
3128 // FIXME: Uh, this isn't particularly portable.
3129 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003130
3131 if (!CGM.getModule().getModuleInlineAsm().empty())
3132 s << "\n";
3133
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003134 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3135 e = LazySymbols.end(); i != e; ++i) {
3136 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3137 }
3138 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3139 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003140 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003141 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3142 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003143
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003144 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003145}
3146
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003147CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003148 : CGObjCCommonMac(cgm),
3149 ObjCTypes(cgm)
3150{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003151 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003152 ObjCABI = 2;
3153}
3154
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003155/* *** */
3156
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003157ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3158: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003159{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003160 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3161 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003162
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003163 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003164 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003165 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003166 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003167 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3168
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003169 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003170 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003171 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003172
3173 // FIXME: It would be nice to unify this with the opaque type, so
3174 // that the IR comes out a bit cleaner.
3175 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3176 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003177
3178 // I'm not sure I like this. The implicit coordination is a bit
3179 // gross. We should solve this in a reasonable fashion because this
3180 // is a pretty common task (match some runtime data structure with
3181 // an LLVM data structure).
3182
3183 // FIXME: This is leaked.
3184 // FIXME: Merge with rewriter code?
3185
3186 // struct _objc_super {
3187 // id self;
3188 // Class cls;
3189 // }
3190 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3191 SourceLocation(),
3192 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003193 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3194 Ctx.getObjCIdType(), 0, false));
3195 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3196 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003197 RD->completeDefinition(Ctx);
3198
3199 SuperCTy = Ctx.getTagDeclType(RD);
3200 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3201
3202 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003203 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3204
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003205 // struct _prop_t {
3206 // char *name;
3207 // char *attributes;
3208 // }
3209 PropertyTy = llvm::StructType::get(Int8PtrTy,
3210 Int8PtrTy,
3211 NULL);
3212 CGM.getModule().addTypeName("struct._prop_t",
3213 PropertyTy);
3214
3215 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003216 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003217 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003218 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003219 // }
3220 PropertyListTy = llvm::StructType::get(IntTy,
3221 IntTy,
3222 llvm::ArrayType::get(PropertyTy, 0),
3223 NULL);
3224 CGM.getModule().addTypeName("struct._prop_list_t",
3225 PropertyListTy);
3226 // struct _prop_list_t *
3227 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3228
3229 // struct _objc_method {
3230 // SEL _cmd;
3231 // char *method_type;
3232 // char *_imp;
3233 // }
3234 MethodTy = llvm::StructType::get(SelectorPtrTy,
3235 Int8PtrTy,
3236 Int8PtrTy,
3237 NULL);
3238 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003239
3240 // struct _objc_cache *
3241 CacheTy = llvm::OpaqueType::get();
3242 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3243 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003244
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003245 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003246
3247 QualType IdType = Ctx.getObjCIdType();
3248 QualType SelType = Ctx.getObjCSelType();
3249 llvm::SmallVector<QualType,16> Params;
3250 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003251
3252 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003253 Params.push_back(IdType);
3254 Params.push_back(SelType);
3255 Params.push_back(Ctx.LongTy);
3256 Params.push_back(Ctx.BoolTy);
3257 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3258 false);
3259 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003260
3261 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3262 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003263 Params.push_back(IdType);
3264 Params.push_back(SelType);
3265 Params.push_back(Ctx.LongTy);
3266 Params.push_back(IdType);
3267 Params.push_back(Ctx.BoolTy);
3268 Params.push_back(Ctx.BoolTy);
3269 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3270 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3271
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003272 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003273
3274 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003275 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003276 Params.push_back(IdType);
3277 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3278 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3279 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003280
3281 // gc's API
3282 // id objc_read_weak (id *)
3283 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003284 Params.push_back(Ctx.getPointerType(IdType));
3285 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3286 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3287
Chris Lattner96508e12009-04-17 22:12:36 +00003288 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003289 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003290 Params.push_back(IdType);
3291 Params.push_back(Ctx.getPointerType(IdType));
3292
3293 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003294 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3295 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3296 GcAssignStrongCastFn =
3297 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003298
3299 // void objc_exception_throw(id)
3300 Params.clear();
3301 Params.push_back(IdType);
3302
3303 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003304 ExceptionThrowFn =
3305 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003306
3307 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003308 // void objc_sync_exit (id)
3309 Params.clear();
3310 Params.push_back(IdType);
3311
3312 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003313 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003314}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003315
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003316ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3317 : ObjCCommonTypesHelper(cgm)
3318{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003319 // struct _objc_method_description {
3320 // SEL name;
3321 // char *types;
3322 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003323 MethodDescriptionTy =
3324 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003325 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003326 NULL);
3327 CGM.getModule().addTypeName("struct._objc_method_description",
3328 MethodDescriptionTy);
3329
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003330 // struct _objc_method_description_list {
3331 // int count;
3332 // struct _objc_method_description[1];
3333 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003334 MethodDescriptionListTy =
3335 llvm::StructType::get(IntTy,
3336 llvm::ArrayType::get(MethodDescriptionTy, 0),
3337 NULL);
3338 CGM.getModule().addTypeName("struct._objc_method_description_list",
3339 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003340
3341 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003342 MethodDescriptionListPtrTy =
3343 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3344
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003345 // Protocol description structures
3346
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003347 // struct _objc_protocol_extension {
3348 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3349 // struct _objc_method_description_list *optional_instance_methods;
3350 // struct _objc_method_description_list *optional_class_methods;
3351 // struct _objc_property_list *instance_properties;
3352 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003353 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003354 llvm::StructType::get(IntTy,
3355 MethodDescriptionListPtrTy,
3356 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003357 PropertyListPtrTy,
3358 NULL);
3359 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3360 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003361
3362 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003363 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3364
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003365 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003366
3367 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3368 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3369
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003370 const llvm::Type *T =
3371 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3372 LongTy,
3373 llvm::ArrayType::get(ProtocolTyHolder, 0),
3374 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003375 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3376
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003377 // struct _objc_protocol {
3378 // struct _objc_protocol_extension *isa;
3379 // char *protocol_name;
3380 // struct _objc_protocol **_objc_protocol_list;
3381 // struct _objc_method_description_list *instance_methods;
3382 // struct _objc_method_description_list *class_methods;
3383 // }
3384 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003385 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003386 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3387 MethodDescriptionListPtrTy,
3388 MethodDescriptionListPtrTy,
3389 NULL);
3390 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3391
3392 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3393 CGM.getModule().addTypeName("struct._objc_protocol_list",
3394 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003395 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003396 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3397
3398 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003399 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003400 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003401
3402 // Class description structures
3403
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003404 // struct _objc_ivar {
3405 // char *ivar_name;
3406 // char *ivar_type;
3407 // int ivar_offset;
3408 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003409 IvarTy = llvm::StructType::get(Int8PtrTy,
3410 Int8PtrTy,
3411 IntTy,
3412 NULL);
3413 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3414
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003415 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003416 IvarListTy = llvm::OpaqueType::get();
3417 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3418 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3419
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003420 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003421 MethodListTy = llvm::OpaqueType::get();
3422 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3423 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3424
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003425 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003426 ClassExtensionTy =
3427 llvm::StructType::get(IntTy,
3428 Int8PtrTy,
3429 PropertyListPtrTy,
3430 NULL);
3431 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3432 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3433
3434 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3435
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003436 // struct _objc_class {
3437 // Class isa;
3438 // Class super_class;
3439 // char *name;
3440 // long version;
3441 // long info;
3442 // long instance_size;
3443 // struct _objc_ivar_list *ivars;
3444 // struct _objc_method_list *methods;
3445 // struct _objc_cache *cache;
3446 // struct _objc_protocol_list *protocols;
3447 // char *ivar_layout;
3448 // struct _objc_class_ext *ext;
3449 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003450 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3451 llvm::PointerType::getUnqual(ClassTyHolder),
3452 Int8PtrTy,
3453 LongTy,
3454 LongTy,
3455 LongTy,
3456 IvarListPtrTy,
3457 MethodListPtrTy,
3458 CachePtrTy,
3459 ProtocolListPtrTy,
3460 Int8PtrTy,
3461 ClassExtensionPtrTy,
3462 NULL);
3463 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3464
3465 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3466 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3467 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3468
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003469 // struct _objc_category {
3470 // char *category_name;
3471 // char *class_name;
3472 // struct _objc_method_list *instance_method;
3473 // struct _objc_method_list *class_method;
3474 // uint32_t size; // sizeof(struct _objc_category)
3475 // struct _objc_property_list *instance_properties;// category's @property
3476 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003477 CategoryTy = llvm::StructType::get(Int8PtrTy,
3478 Int8PtrTy,
3479 MethodListPtrTy,
3480 MethodListPtrTy,
3481 ProtocolListPtrTy,
3482 IntTy,
3483 PropertyListPtrTy,
3484 NULL);
3485 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3486
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003487 // Global metadata structures
3488
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003489 // struct _objc_symtab {
3490 // long sel_ref_cnt;
3491 // SEL *refs;
3492 // short cls_def_cnt;
3493 // short cat_def_cnt;
3494 // char *defs[cls_def_cnt + cat_def_cnt];
3495 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003496 SymtabTy = llvm::StructType::get(LongTy,
3497 SelectorPtrTy,
3498 ShortTy,
3499 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003500 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003501 NULL);
3502 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3503 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3504
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003505 // struct _objc_module {
3506 // long version;
3507 // long size; // sizeof(struct _objc_module)
3508 // char *name;
3509 // struct _objc_symtab* symtab;
3510 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003511 ModuleTy =
3512 llvm::StructType::get(LongTy,
3513 LongTy,
3514 Int8PtrTy,
3515 SymtabPtrTy,
3516 NULL);
3517 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003518
Daniel Dunbar49f66022008-09-24 03:38:44 +00003519 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003520
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003521 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003522 std::vector<const llvm::Type*> Params;
3523 Params.push_back(ObjectPtrTy);
3524 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003525 MessageSendFn =
3526 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3527 Params,
3528 true),
3529 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003530
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003531 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003532 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003533 Params.push_back(ObjectPtrTy);
3534 Params.push_back(SelectorPtrTy);
3535 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003536 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3537 Params,
3538 true),
3539 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003540
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003541 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003542 Params.clear();
3543 Params.push_back(ObjectPtrTy);
3544 Params.push_back(SelectorPtrTy);
3545 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003546 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003547 MessageSendFpretFn =
3548 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3549 Params,
3550 true),
3551 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003552
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003553 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003554 Params.clear();
3555 Params.push_back(SuperPtrTy);
3556 Params.push_back(SelectorPtrTy);
3557 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003558 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3559 Params,
3560 true),
3561 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003562
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003563 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3564 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003565 Params.clear();
3566 Params.push_back(Int8PtrTy);
3567 Params.push_back(SuperPtrTy);
3568 Params.push_back(SelectorPtrTy);
3569 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003570 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3571 Params,
3572 true),
3573 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003574
3575 // There is no objc_msgSendSuper_fpret? How can that work?
3576 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003577
Anders Carlsson124526b2008-09-09 10:10:21 +00003578 // FIXME: This is the size of the setjmp buffer and should be
3579 // target specific. 18 is what's used on 32-bit X86.
3580 uint64_t SetJmpBufferSize = 18;
3581
3582 // Exceptions
3583 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003584 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003585
3586 ExceptionDataTy =
3587 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3588 SetJmpBufferSize),
3589 StackPtrTy, NULL);
3590 CGM.getModule().addTypeName("struct._objc_exception_data",
3591 ExceptionDataTy);
3592
3593 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003594 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3595 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003596 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3597 Params,
3598 false),
3599 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003600 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003601 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3602 Params,
3603 false),
3604 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003605 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003606 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3607 Params,
3608 false),
3609 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003610
3611 Params.clear();
3612 Params.push_back(ClassPtrTy);
3613 Params.push_back(ObjectPtrTy);
3614 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003615 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3616 Params,
3617 false),
3618 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003619
Anders Carlsson124526b2008-09-09 10:10:21 +00003620 Params.clear();
3621 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3622 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003623 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3624 Params,
3625 false),
3626 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003627
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003628}
3629
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003630ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003631: ObjCCommonTypesHelper(cgm)
3632{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003633 // struct _method_list_t {
3634 // uint32_t entsize; // sizeof(struct _objc_method)
3635 // uint32_t method_count;
3636 // struct _objc_method method_list[method_count];
3637 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003638 MethodListnfABITy = llvm::StructType::get(IntTy,
3639 IntTy,
3640 llvm::ArrayType::get(MethodTy, 0),
3641 NULL);
3642 CGM.getModule().addTypeName("struct.__method_list_t",
3643 MethodListnfABITy);
3644 // struct method_list_t *
3645 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003646
3647 // struct _protocol_t {
3648 // id isa; // NULL
3649 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003650 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003651 // const struct method_list_t * const instance_methods;
3652 // const struct method_list_t * const class_methods;
3653 // const struct method_list_t *optionalInstanceMethods;
3654 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003655 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003656 // const uint32_t size; // sizeof(struct _protocol_t)
3657 // const uint32_t flags; // = 0
3658 // }
3659
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003660 // Holder for struct _protocol_list_t *
3661 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3662
3663 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3664 Int8PtrTy,
3665 llvm::PointerType::getUnqual(
3666 ProtocolListTyHolder),
3667 MethodListnfABIPtrTy,
3668 MethodListnfABIPtrTy,
3669 MethodListnfABIPtrTy,
3670 MethodListnfABIPtrTy,
3671 PropertyListPtrTy,
3672 IntTy,
3673 IntTy,
3674 NULL);
3675 CGM.getModule().addTypeName("struct._protocol_t",
3676 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003677
3678 // struct _protocol_t*
3679 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003680
Fariborz Jahanianda320092009-01-29 19:24:30 +00003681 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003682 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003683 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003684 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003685 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3686 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003687 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003688 NULL);
3689 CGM.getModule().addTypeName("struct._objc_protocol_list",
3690 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003691 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3692 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003693
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003694 // struct _objc_protocol_list*
3695 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003696
3697 // struct _ivar_t {
3698 // unsigned long int *offset; // pointer to ivar offset location
3699 // char *name;
3700 // char *type;
3701 // uint32_t alignment;
3702 // uint32_t size;
3703 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003704 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3705 Int8PtrTy,
3706 Int8PtrTy,
3707 IntTy,
3708 IntTy,
3709 NULL);
3710 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3711
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003712 // struct _ivar_list_t {
3713 // uint32 entsize; // sizeof(struct _ivar_t)
3714 // uint32 count;
3715 // struct _iver_t list[count];
3716 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003717 IvarListnfABITy = llvm::StructType::get(IntTy,
3718 IntTy,
3719 llvm::ArrayType::get(
3720 IvarnfABITy, 0),
3721 NULL);
3722 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3723
3724 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003725
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003726 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003727 // uint32_t const flags;
3728 // uint32_t const instanceStart;
3729 // uint32_t const instanceSize;
3730 // uint32_t const reserved; // only when building for 64bit targets
3731 // const uint8_t * const ivarLayout;
3732 // const char *const name;
3733 // const struct _method_list_t * const baseMethods;
3734 // const struct _objc_protocol_list *const baseProtocols;
3735 // const struct _ivar_list_t *const ivars;
3736 // const uint8_t * const weakIvarLayout;
3737 // const struct _prop_list_t * const properties;
3738 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003739
3740 // FIXME. Add 'reserved' field in 64bit abi mode!
3741 ClassRonfABITy = llvm::StructType::get(IntTy,
3742 IntTy,
3743 IntTy,
3744 Int8PtrTy,
3745 Int8PtrTy,
3746 MethodListnfABIPtrTy,
3747 ProtocolListnfABIPtrTy,
3748 IvarListnfABIPtrTy,
3749 Int8PtrTy,
3750 PropertyListPtrTy,
3751 NULL);
3752 CGM.getModule().addTypeName("struct._class_ro_t",
3753 ClassRonfABITy);
3754
3755 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3756 std::vector<const llvm::Type*> Params;
3757 Params.push_back(ObjectPtrTy);
3758 Params.push_back(SelectorPtrTy);
3759 ImpnfABITy = llvm::PointerType::getUnqual(
3760 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3761
3762 // struct _class_t {
3763 // struct _class_t *isa;
3764 // struct _class_t * const superclass;
3765 // void *cache;
3766 // IMP *vtable;
3767 // struct class_ro_t *ro;
3768 // }
3769
3770 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3771 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3772 llvm::PointerType::getUnqual(ClassTyHolder),
3773 CachePtrTy,
3774 llvm::PointerType::getUnqual(ImpnfABITy),
3775 llvm::PointerType::getUnqual(
3776 ClassRonfABITy),
3777 NULL);
3778 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3779
3780 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3781 ClassnfABITy);
3782
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003783 // LLVM for struct _class_t *
3784 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3785
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003786 // struct _category_t {
3787 // const char * const name;
3788 // struct _class_t *const cls;
3789 // const struct _method_list_t * const instance_methods;
3790 // const struct _method_list_t * const class_methods;
3791 // const struct _protocol_list_t * const protocols;
3792 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003793 // }
3794 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003795 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003796 MethodListnfABIPtrTy,
3797 MethodListnfABIPtrTy,
3798 ProtocolListnfABIPtrTy,
3799 PropertyListPtrTy,
3800 NULL);
3801 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003802
3803 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003804 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3805 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003806
3807 // MessageRefTy - LLVM for:
3808 // struct _message_ref_t {
3809 // IMP messenger;
3810 // SEL name;
3811 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003812
3813 // First the clang type for struct _message_ref_t
3814 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3815 SourceLocation(),
3816 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003817 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3818 Ctx.VoidPtrTy, 0, false));
3819 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3820 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003821 RD->completeDefinition(Ctx);
3822
3823 MessageRefCTy = Ctx.getTagDeclType(RD);
3824 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3825 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003826
3827 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3828 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3829
3830 // SuperMessageRefTy - LLVM for:
3831 // struct _super_message_ref_t {
3832 // SUPER_IMP messenger;
3833 // SEL name;
3834 // };
3835 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3836 SelectorPtrTy,
3837 NULL);
3838 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3839
3840 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3841 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3842
3843 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3844 Params.clear();
3845 Params.push_back(ObjectPtrTy);
3846 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003847 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3848 Params,
3849 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003850 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003851 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003852 "objc_msgSend_fixup");
3853
3854 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3855 MessageSendFpretFixupFn =
3856 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3857 Params,
3858 true),
3859 "objc_msgSend_fpret_fixup");
3860
3861 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3862 MessageSendStretFixupFn =
3863 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3864 Params,
3865 true),
3866 "objc_msgSend_stret_fixup");
3867
3868 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3869 MessageSendIdFixupFn =
3870 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3871 Params,
3872 true),
3873 "objc_msgSendId_fixup");
3874
3875
3876 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3877 MessageSendIdStretFixupFn =
3878 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3879 Params,
3880 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003881 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003882
3883 // id objc_msgSendSuper2_fixup (struct objc_super *,
3884 // struct _super_message_ref_t*, ...)
3885 Params.clear();
3886 Params.push_back(SuperPtrTy);
3887 Params.push_back(SuperMessageRefPtrTy);
3888 MessageSendSuper2FixupFn =
3889 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3890 Params,
3891 true),
3892 "objc_msgSendSuper2_fixup");
3893
3894
3895 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3896 // struct _super_message_ref_t*, ...)
3897 MessageSendSuper2StretFixupFn =
3898 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3899 Params,
3900 true),
3901 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003902
3903 Params.clear();
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003904 Params.push_back(Int8PtrTy);
3905 UnwindResumeOrRethrowFn =
3906 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3907 Params,
3908 false),
3909 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003910 ObjCBeginCatchFn =
3911 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3912 Params,
3913 false),
3914 "objc_begin_catch");
3915
3916 Params.clear();
3917 ObjCEndCatchFn =
3918 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3919 Params,
3920 false),
3921 "objc_end_catch");
3922
3923 // struct objc_typeinfo {
3924 // const void** vtable; // objc_ehtype_vtable + 2
3925 // const char* name; // c++ typeinfo string
3926 // Class cls;
3927 // };
3928 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3929 Int8PtrTy,
3930 ClassnfABIPtrTy,
3931 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003932 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003933 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003934}
3935
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003936llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3937 FinishNonFragileABIModule();
3938
3939 return NULL;
3940}
3941
3942void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3943 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003944
3945 // Build list of all implemented classe addresses in array
3946 // L_OBJC_LABEL_CLASS_$.
3947 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3948 // list of 'nonlazy' implementations (defined as those with a +load{}
3949 // method!!).
3950 unsigned NumClasses = DefinedClasses.size();
3951 if (NumClasses) {
3952 std::vector<llvm::Constant*> Symbols(NumClasses);
3953 for (unsigned i=0; i<NumClasses; i++)
3954 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3955 ObjCTypes.Int8PtrTy);
3956 llvm::Constant* Init =
3957 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3958 NumClasses),
3959 Symbols);
3960
3961 llvm::GlobalVariable *GV =
3962 new llvm::GlobalVariable(Init->getType(), false,
3963 llvm::GlobalValue::InternalLinkage,
3964 Init,
3965 "\01L_OBJC_LABEL_CLASS_$",
3966 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003967 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003968 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3969 UsedGlobals.push_back(GV);
3970 }
3971
3972 // Build list of all implemented category addresses in array
3973 // L_OBJC_LABEL_CATEGORY_$.
3974 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3975 // list of 'nonlazy' category implementations (defined as those with a +load{}
3976 // method!!).
3977 unsigned NumCategory = DefinedCategories.size();
3978 if (NumCategory) {
3979 std::vector<llvm::Constant*> Symbols(NumCategory);
3980 for (unsigned i=0; i<NumCategory; i++)
3981 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3982 ObjCTypes.Int8PtrTy);
3983 llvm::Constant* Init =
3984 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3985 NumCategory),
3986 Symbols);
3987
3988 llvm::GlobalVariable *GV =
3989 new llvm::GlobalVariable(Init->getType(), false,
3990 llvm::GlobalValue::InternalLinkage,
3991 Init,
3992 "\01L_OBJC_LABEL_CATEGORY_$",
3993 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003994 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003995 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3996 UsedGlobals.push_back(GV);
3997 }
3998
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003999 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4000 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4001 std::vector<llvm::Constant*> Values(2);
4002 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004003 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004004 // FIXME: Fix and continue?
4005 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4006 flags |= eImageInfo_GarbageCollected;
4007 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4008 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004009 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004010 llvm::Constant* Init = llvm::ConstantArray::get(
4011 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4012 Values);
4013 llvm::GlobalVariable *IMGV =
4014 new llvm::GlobalVariable(Init->getType(), false,
4015 llvm::GlobalValue::InternalLinkage,
4016 Init,
4017 "\01L_OBJC_IMAGE_INFO",
4018 &CGM.getModule());
4019 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4020 UsedGlobals.push_back(IMGV);
4021
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004022 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004023
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004024 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4025 e = UsedGlobals.end(); i != e; ++i) {
4026 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4027 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004028
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004029 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4030 llvm::GlobalValue *GV =
4031 new llvm::GlobalVariable(AT, false,
4032 llvm::GlobalValue::AppendingLinkage,
4033 llvm::ConstantArray::get(AT, Used),
4034 "llvm.used",
4035 &CGM.getModule());
4036
4037 GV->setSection("llvm.metadata");
4038
4039}
4040
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004041// Metadata flags
4042enum MetaDataDlags {
4043 CLS = 0x0,
4044 CLS_META = 0x1,
4045 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004046 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004047 CLS_EXCEPTION = 0x20
4048};
4049/// BuildClassRoTInitializer - generate meta-data for:
4050/// struct _class_ro_t {
4051/// uint32_t const flags;
4052/// uint32_t const instanceStart;
4053/// uint32_t const instanceSize;
4054/// uint32_t const reserved; // only when building for 64bit targets
4055/// const uint8_t * const ivarLayout;
4056/// const char *const name;
4057/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004058/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004059/// const struct _ivar_list_t *const ivars;
4060/// const uint8_t * const weakIvarLayout;
4061/// const struct _prop_list_t * const properties;
4062/// }
4063///
4064llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4065 unsigned flags,
4066 unsigned InstanceStart,
4067 unsigned InstanceSize,
4068 const ObjCImplementationDecl *ID) {
4069 std::string ClassName = ID->getNameAsString();
4070 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4071 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4072 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4073 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4074 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004075 // FIXME. ivarLayout is currently null!
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00004076 // Values[ 3] = BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004077 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004078 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004079 // const struct _method_list_t * const baseMethods;
4080 std::vector<llvm::Constant*> Methods;
4081 std::string MethodListName("\01l_OBJC_$_");
4082 if (flags & CLS_META) {
4083 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4084 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4085 e = ID->classmeth_end(); i != e; ++i) {
4086 // Class methods should always be defined.
4087 Methods.push_back(GetMethodConstant(*i));
4088 }
4089 } else {
4090 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4091 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4092 e = ID->instmeth_end(); i != e; ++i) {
4093 // Instance methods should always be defined.
4094 Methods.push_back(GetMethodConstant(*i));
4095 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004096 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4097 e = ID->propimpl_end(); i != e; ++i) {
4098 ObjCPropertyImplDecl *PID = *i;
4099
4100 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4101 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4102
4103 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4104 if (llvm::Constant *C = GetMethodConstant(MD))
4105 Methods.push_back(C);
4106 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4107 if (llvm::Constant *C = GetMethodConstant(MD))
4108 Methods.push_back(C);
4109 }
4110 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004111 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004112 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004113 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004114
4115 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4116 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4117 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4118 + OID->getNameAsString(),
4119 OID->protocol_begin(),
4120 OID->protocol_end());
4121
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004122 if (flags & CLS_META)
4123 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4124 else
4125 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004126 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00004127 // Values[ 8] = BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004128 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004129 if (flags & CLS_META)
4130 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4131 else
4132 Values[ 9] =
4133 EmitPropertyList(
4134 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4135 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004136 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4137 Values);
4138 llvm::GlobalVariable *CLASS_RO_GV =
4139 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4140 llvm::GlobalValue::InternalLinkage,
4141 Init,
4142 (flags & CLS_META) ?
4143 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4144 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4145 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004146 CLASS_RO_GV->setAlignment(
4147 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004148 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004149 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004150
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004151}
4152
4153/// BuildClassMetaData - This routine defines that to-level meta-data
4154/// for the given ClassName for:
4155/// struct _class_t {
4156/// struct _class_t *isa;
4157/// struct _class_t * const superclass;
4158/// void *cache;
4159/// IMP *vtable;
4160/// struct class_ro_t *ro;
4161/// }
4162///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004163llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4164 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004165 llvm::Constant *IsAGV,
4166 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004167 llvm::Constant *ClassRoGV,
4168 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004169 std::vector<llvm::Constant*> Values(5);
4170 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004171 Values[1] = SuperClassGV
4172 ? SuperClassGV
4173 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004174 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4175 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4176 Values[4] = ClassRoGV; // &CLASS_RO_GV
4177 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4178 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004179 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4180 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004181 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004182 GV->setAlignment(
4183 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004184 if (HiddenVisibility)
4185 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004186 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004187}
4188
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004189/// countInheritedIvars - count number of ivars in class and its super class(s)
4190///
4191static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4192 ASTContext &Context) {
4193 int count = 0;
4194 if (!OI)
4195 return 0;
4196 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4197 if (SuperClass)
4198 count += countInheritedIvars(SuperClass, Context);
4199 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4200 E = OI->ivar_end(); I != E; ++I)
4201 ++count;
4202 // look into properties.
4203 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4204 E = OI->prop_end(Context); I != E; ++I) {
4205 if ((*I)->getPropertyIvarDecl())
4206 ++count;
4207 }
4208 return count;
4209}
4210
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004211void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4212 uint32_t &InstanceStart,
4213 uint32_t &InstanceSize) {
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004214 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4215
Daniel Dunbar6ec07162009-04-20 07:18:49 +00004216 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4217 CGM.getContext());
4218 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4219 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4220 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4221 while (countSuperClassIvars-- > 0) {
4222 lastField = firstField;
4223 ++firstField;
4224 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004225
4226 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4227 ifield = firstField; ifield != e; ++ifield)
4228 lastField = ifield;
4229
4230 InstanceStart = InstanceSize = 0;
4231 if (lastField != RD->field_end(CGM.getContext())) {
4232 FieldDecl *Field = *lastField;
4233 const llvm::Type *FieldTy =
4234 CGM.getTypes().ConvertTypeForMem(Field->getType());
4235 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4236 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4237 if (firstField == RD->field_end(CGM.getContext()))
4238 InstanceStart = InstanceSize;
4239 else {
4240 Field = *firstField;
4241 InstanceStart = GetIvarBaseOffset(Layout, Field);
4242 }
4243 }
4244}
4245
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004246void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4247 std::string ClassName = ID->getNameAsString();
4248 if (!ObjCEmptyCacheVar) {
4249 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004250 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004251 false,
4252 llvm::GlobalValue::ExternalLinkage,
4253 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004254 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004255 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004256
4257 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004258 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004259 false,
4260 llvm::GlobalValue::ExternalLinkage,
4261 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004262 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004263 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004264 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004265 assert(ID->getClassInterface() &&
4266 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004267 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004268 uint32_t InstanceStart =
4269 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4270 uint32_t InstanceSize = InstanceStart;
4271 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004272 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4273 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004274
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004275 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004276
Daniel Dunbar04d40782009-04-14 06:00:08 +00004277 bool classIsHidden =
4278 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004279 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004280 flags |= OBJC2_CLS_HIDDEN;
4281 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004282 // class is root
4283 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004284 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004285 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004286 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004287 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004288 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4289 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4290 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004291 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004292 // work on super class metadata symbol.
4293 std::string SuperClassName =
4294 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004295 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004296 }
4297 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4298 InstanceStart,
4299 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004300 std::string TClassName = ObjCMetaClassName + ClassName;
4301 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004302 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4303 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004304
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004305 // Metadata for the class
4306 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004307 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004308 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004309
4310 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4311 flags |= CLS_EXCEPTION;
4312
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004313 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004314 flags |= CLS_ROOT;
4315 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004316 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004317 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004318 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004319 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004320 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004321 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004322 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004323 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004324 InstanceStart,
4325 InstanceSize,
4326 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004327
4328 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004329 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004330 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4331 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004332 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004333
4334 // Force the definition of the EHType if necessary.
4335 if (flags & CLS_EXCEPTION)
4336 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004337}
4338
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004339/// GenerateProtocolRef - This routine is called to generate code for
4340/// a protocol reference expression; as in:
4341/// @code
4342/// @protocol(Proto1);
4343/// @endcode
4344/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4345/// which will hold address of the protocol meta-data.
4346///
4347llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4348 const ObjCProtocolDecl *PD) {
4349
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004350 // This routine is called for @protocol only. So, we must build definition
4351 // of protocol's meta-data (not a reference to it!)
4352 //
4353 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004354 ObjCTypes.ExternalProtocolPtrTy);
4355
4356 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4357 ProtocolName += PD->getNameAsCString();
4358
4359 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4360 if (PTGV)
4361 return Builder.CreateLoad(PTGV, false, "tmp");
4362 PTGV = new llvm::GlobalVariable(
4363 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004364 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004365 Init,
4366 ProtocolName,
4367 &CGM.getModule());
4368 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4369 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4370 UsedGlobals.push_back(PTGV);
4371 return Builder.CreateLoad(PTGV, false, "tmp");
4372}
4373
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004374/// GenerateCategory - Build metadata for a category implementation.
4375/// struct _category_t {
4376/// const char * const name;
4377/// struct _class_t *const cls;
4378/// const struct _method_list_t * const instance_methods;
4379/// const struct _method_list_t * const class_methods;
4380/// const struct _protocol_list_t * const protocols;
4381/// const struct _prop_list_t * const properties;
4382/// }
4383///
4384void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4385{
4386 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004387 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4388 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004389 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004390 std::string ExtClassName(getClassSymbolPrefix() +
4391 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004392
4393 std::vector<llvm::Constant*> Values(6);
4394 Values[0] = GetClassName(OCD->getIdentifier());
4395 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004396 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004397 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004398 std::vector<llvm::Constant*> Methods;
4399 std::string MethodListName(Prefix);
4400 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4401 "_$_" + OCD->getNameAsString();
4402
4403 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4404 e = OCD->instmeth_end(); i != e; ++i) {
4405 // Instance methods should always be defined.
4406 Methods.push_back(GetMethodConstant(*i));
4407 }
4408
4409 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004410 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004411 Methods);
4412
4413 MethodListName = Prefix;
4414 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4415 OCD->getNameAsString();
4416 Methods.clear();
4417 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4418 e = OCD->classmeth_end(); i != e; ++i) {
4419 // Class methods should always be defined.
4420 Methods.push_back(GetMethodConstant(*i));
4421 }
4422
4423 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004424 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004425 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004426 const ObjCCategoryDecl *Category =
4427 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004428 if (Category) {
4429 std::string ExtName(Interface->getNameAsString() + "_$_" +
4430 OCD->getNameAsString());
4431 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4432 + Interface->getNameAsString() + "_$_"
4433 + Category->getNameAsString(),
4434 Category->protocol_begin(),
4435 Category->protocol_end());
4436 Values[5] =
4437 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4438 OCD, Category, ObjCTypes);
4439 }
4440 else {
4441 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4442 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4443 }
4444
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004445 llvm::Constant *Init =
4446 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4447 Values);
4448 llvm::GlobalVariable *GCATV
4449 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4450 false,
4451 llvm::GlobalValue::InternalLinkage,
4452 Init,
4453 ExtCatName,
4454 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004455 GCATV->setAlignment(
4456 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004457 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004458 UsedGlobals.push_back(GCATV);
4459 DefinedCategories.push_back(GCATV);
4460}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004461
4462/// GetMethodConstant - Return a struct objc_method constant for the
4463/// given method if it has been defined. The result is null if the
4464/// method has not been defined. The return value has type MethodPtrTy.
4465llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4466 const ObjCMethodDecl *MD) {
4467 // FIXME: Use DenseMap::lookup
4468 llvm::Function *Fn = MethodDefinitions[MD];
4469 if (!Fn)
4470 return 0;
4471
4472 std::vector<llvm::Constant*> Method(3);
4473 Method[0] =
4474 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4475 ObjCTypes.SelectorPtrTy);
4476 Method[1] = GetMethodVarType(MD);
4477 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4478 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4479}
4480
4481/// EmitMethodList - Build meta-data for method declarations
4482/// struct _method_list_t {
4483/// uint32_t entsize; // sizeof(struct _objc_method)
4484/// uint32_t method_count;
4485/// struct _objc_method method_list[method_count];
4486/// }
4487///
4488llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4489 const std::string &Name,
4490 const char *Section,
4491 const ConstantVector &Methods) {
4492 // Return null for empty list.
4493 if (Methods.empty())
4494 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4495
4496 std::vector<llvm::Constant*> Values(3);
4497 // sizeof(struct _objc_method)
4498 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4499 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4500 // method_count
4501 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4502 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4503 Methods.size());
4504 Values[2] = llvm::ConstantArray::get(AT, Methods);
4505 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4506
4507 llvm::GlobalVariable *GV =
4508 new llvm::GlobalVariable(Init->getType(), false,
4509 llvm::GlobalValue::InternalLinkage,
4510 Init,
4511 Name,
4512 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004513 GV->setAlignment(
4514 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004515 GV->setSection(Section);
4516 UsedGlobals.push_back(GV);
4517 return llvm::ConstantExpr::getBitCast(GV,
4518 ObjCTypes.MethodListnfABIPtrTy);
4519}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004520
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004521/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4522/// the given ivar.
4523///
4524llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004525 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004526 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004527 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004528 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4529 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004530 llvm::GlobalVariable *IvarOffsetGV =
4531 CGM.getModule().getGlobalVariable(Name);
4532 if (!IvarOffsetGV)
4533 IvarOffsetGV =
4534 new llvm::GlobalVariable(ObjCTypes.LongTy,
4535 false,
4536 llvm::GlobalValue::ExternalLinkage,
4537 0,
4538 Name,
4539 &CGM.getModule());
4540 return IvarOffsetGV;
4541}
4542
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004543llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004544 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004545 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004546 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004547 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4548 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4549 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004550 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004551 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004552
4553 // FIXME: This matches gcc, but shouldn't the visibility be set on
4554 // the use as well (i.e., in ObjCIvarOffsetVariable).
4555 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4556 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4557 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004558 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004559 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004560 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004561 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004562 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004563}
4564
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004565/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004566/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004567/// IvarListnfABIPtrTy.
4568/// struct _ivar_t {
4569/// unsigned long int *offset; // pointer to ivar offset location
4570/// char *name;
4571/// char *type;
4572/// uint32_t alignment;
4573/// uint32_t size;
4574/// }
4575/// struct _ivar_list_t {
4576/// uint32 entsize; // sizeof(struct _ivar_t)
4577/// uint32 count;
4578/// struct _iver_t list[count];
4579/// }
4580///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004581
4582void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4583 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4584 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4585 E = OID->ivar_end(); I != E; ++I) {
4586 // Ignore unnamed bit-fields.
4587 if (!(*I)->getDeclName())
4588 continue;
4589
4590 Res.push_back(*I);
4591 }
4592
4593 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4594 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4595 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4596 Res.push_back(IV);
4597}
4598
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004599llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4600 const ObjCImplementationDecl *ID) {
4601
4602 std::vector<llvm::Constant*> Ivars, Ivar(5);
4603
4604 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4605 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4606
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004607 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004608 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004609
Daniel Dunbar91636d62009-04-20 00:33:43 +00004610 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004611 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004612 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004613
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004614 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4615 ObjCIvarDecl *IVD = OIvars[i];
4616 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004617 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004618 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004619 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004620 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004621 const llvm::Type *FieldTy =
4622 CGM.getTypes().ConvertTypeForMem(Field->getType());
4623 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4624 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4625 Field->getType().getTypePtr()) >> 3;
4626 Align = llvm::Log2_32(Align);
4627 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004628 // NOTE. Size of a bitfield does not match gcc's, because of the
4629 // way bitfields are treated special in each. But I am told that
4630 // 'size' for bitfield ivars is ignored by the runtime so it does
4631 // not matter. If it matters, there is enough info to get the
4632 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004633 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4634 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4635 }
4636 // Return null for empty list.
4637 if (Ivars.empty())
4638 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4639 std::vector<llvm::Constant*> Values(3);
4640 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4641 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4642 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4643 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4644 Ivars.size());
4645 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4646 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4647 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4648 llvm::GlobalVariable *GV =
4649 new llvm::GlobalVariable(Init->getType(), false,
4650 llvm::GlobalValue::InternalLinkage,
4651 Init,
4652 Prefix + OID->getNameAsString(),
4653 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004654 GV->setAlignment(
4655 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004656 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004657
4658 UsedGlobals.push_back(GV);
4659 return llvm::ConstantExpr::getBitCast(GV,
4660 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004661}
4662
4663llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4664 const ObjCProtocolDecl *PD) {
4665 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4666
4667 if (!Entry) {
4668 // We use the initializer as a marker of whether this is a forward
4669 // reference or not. At module finalization we add the empty
4670 // contents for protocols which were referenced but never defined.
4671 Entry =
4672 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4673 llvm::GlobalValue::ExternalLinkage,
4674 0,
4675 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4676 &CGM.getModule());
4677 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4678 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004679 }
4680
4681 return Entry;
4682}
4683
4684/// GetOrEmitProtocol - Generate the protocol meta-data:
4685/// @code
4686/// struct _protocol_t {
4687/// id isa; // NULL
4688/// const char * const protocol_name;
4689/// const struct _protocol_list_t * protocol_list; // super protocols
4690/// const struct method_list_t * const instance_methods;
4691/// const struct method_list_t * const class_methods;
4692/// const struct method_list_t *optionalInstanceMethods;
4693/// const struct method_list_t *optionalClassMethods;
4694/// const struct _prop_list_t * properties;
4695/// const uint32_t size; // sizeof(struct _protocol_t)
4696/// const uint32_t flags; // = 0
4697/// }
4698/// @endcode
4699///
4700
4701llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4702 const ObjCProtocolDecl *PD) {
4703 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4704
4705 // Early exit if a defining object has already been generated.
4706 if (Entry && Entry->hasInitializer())
4707 return Entry;
4708
4709 const char *ProtocolName = PD->getNameAsCString();
4710
4711 // Construct method lists.
4712 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4713 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004714 for (ObjCProtocolDecl::instmeth_iterator
4715 i = PD->instmeth_begin(CGM.getContext()),
4716 e = PD->instmeth_end(CGM.getContext());
4717 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004718 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004719 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004720 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4721 OptInstanceMethods.push_back(C);
4722 } else {
4723 InstanceMethods.push_back(C);
4724 }
4725 }
4726
Douglas Gregor6ab35242009-04-09 21:40:53 +00004727 for (ObjCProtocolDecl::classmeth_iterator
4728 i = PD->classmeth_begin(CGM.getContext()),
4729 e = PD->classmeth_end(CGM.getContext());
4730 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004731 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004732 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004733 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4734 OptClassMethods.push_back(C);
4735 } else {
4736 ClassMethods.push_back(C);
4737 }
4738 }
4739
4740 std::vector<llvm::Constant*> Values(10);
4741 // isa is NULL
4742 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4743 Values[1] = GetClassName(PD->getIdentifier());
4744 Values[2] = EmitProtocolList(
4745 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4746 PD->protocol_begin(),
4747 PD->protocol_end());
4748
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004749 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004750 + PD->getNameAsString(),
4751 "__DATA, __objc_const",
4752 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004753 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004754 + PD->getNameAsString(),
4755 "__DATA, __objc_const",
4756 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004757 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004758 + PD->getNameAsString(),
4759 "__DATA, __objc_const",
4760 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004761 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004762 + PD->getNameAsString(),
4763 "__DATA, __objc_const",
4764 OptClassMethods);
4765 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4766 0, PD, ObjCTypes);
4767 uint32_t Size =
4768 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4769 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4770 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4771 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4772 Values);
4773
4774 if (Entry) {
4775 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004776 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004777 Entry->setInitializer(Init);
4778 } else {
4779 Entry =
4780 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004781 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004782 Init,
4783 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4784 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004785 Entry->setAlignment(
4786 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004787 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004788 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004789 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4790
4791 // Use this protocol meta-data to build protocol list table in section
4792 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004793 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004794 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004795 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004796 Entry,
4797 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4798 +ProtocolName,
4799 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004800 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004801 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004802 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004803 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4804 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004805 return Entry;
4806}
4807
4808/// EmitProtocolList - Generate protocol list meta-data:
4809/// @code
4810/// struct _protocol_list_t {
4811/// long protocol_count; // Note, this is 32/64 bit
4812/// struct _protocol_t[protocol_count];
4813/// }
4814/// @endcode
4815///
4816llvm::Constant *
4817CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4818 ObjCProtocolDecl::protocol_iterator begin,
4819 ObjCProtocolDecl::protocol_iterator end) {
4820 std::vector<llvm::Constant*> ProtocolRefs;
4821
Fariborz Jahanianda320092009-01-29 19:24:30 +00004822 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004823 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004824 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4825
Daniel Dunbar948e2582009-02-15 07:36:20 +00004826 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004827 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4828 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004829 return llvm::ConstantExpr::getBitCast(GV,
4830 ObjCTypes.ProtocolListnfABIPtrTy);
4831
4832 for (; begin != end; ++begin)
4833 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4834
Fariborz Jahanianda320092009-01-29 19:24:30 +00004835 // This list is null terminated.
4836 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004837 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004838
4839 std::vector<llvm::Constant*> Values(2);
4840 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4841 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004842 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004843 ProtocolRefs.size()),
4844 ProtocolRefs);
4845
4846 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4847 GV = new llvm::GlobalVariable(Init->getType(), false,
4848 llvm::GlobalValue::InternalLinkage,
4849 Init,
4850 Name,
4851 &CGM.getModule());
4852 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004853 GV->setAlignment(
4854 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004855 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004856 return llvm::ConstantExpr::getBitCast(GV,
4857 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004858}
4859
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004860/// GetMethodDescriptionConstant - This routine build following meta-data:
4861/// struct _objc_method {
4862/// SEL _cmd;
4863/// char *method_type;
4864/// char *_imp;
4865/// }
4866
4867llvm::Constant *
4868CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4869 std::vector<llvm::Constant*> Desc(3);
4870 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4871 ObjCTypes.SelectorPtrTy);
4872 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004873 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004874 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4875 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4876}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004877
4878/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4879/// This code gen. amounts to generating code for:
4880/// @code
4881/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4882/// @encode
4883///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004884LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004885 CodeGen::CodeGenFunction &CGF,
4886 QualType ObjectTy,
4887 llvm::Value *BaseValue,
4888 const ObjCIvarDecl *Ivar,
4889 const FieldDecl *Field,
4890 unsigned CVRQualifiers) {
4891 assert(ObjectTy->isObjCInterfaceType() &&
4892 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004893 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004894 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004895
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004896 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004897 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004898 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4899 // (char*)BaseValue + Offset_symbol
4900 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4901 // (type *)((char*)BaseValue + Offset_symbol)
4902 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004903 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004904 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4905 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004906
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004907 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004908 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004909 CodeGenTypes::BitFieldInfo bitFieldInfo =
4910 CGM.getTypes().getBitFieldInfo(Field);
4911 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004912 FieldTy->isSignedIntegerType(),
4913 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004914 }
4915
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004916 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004917 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4918 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004919 LValue::SetObjCIvar(LV, true);
4920 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004921}
4922
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004923llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4924 CodeGen::CodeGenFunction &CGF,
4925 ObjCInterfaceDecl *Interface,
4926 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004927 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4928 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004929}
4930
Fariborz Jahanian46551122009-02-04 00:22:57 +00004931CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4932 CodeGen::CodeGenFunction &CGF,
4933 QualType ResultType,
4934 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004935 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004936 QualType Arg0Ty,
4937 bool IsSuper,
4938 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004939 // FIXME. Even though IsSuper is passes. This function doese not
4940 // handle calls to 'super' receivers.
4941 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004942 llvm::Value *Arg0 = Receiver;
4943 if (!IsSuper)
4944 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004945
4946 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004947 // FIXME. This is too much work to get the ABI-specific result type
4948 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004949 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4950 llvm::SmallVector<QualType, 16>());
4951 llvm::Constant *Fn;
4952 std::string Name("\01l_");
4953 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004954#if 0
4955 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004956 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4957 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4958 // FIXME. Is there a better way of getting these names.
4959 // They are available in RuntimeFunctions vector pair.
4960 Name += "objc_msgSendId_stret_fixup";
4961 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004962 else
4963#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004964 if (IsSuper) {
4965 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4966 Name += "objc_msgSendSuper2_stret_fixup";
4967 }
4968 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004969 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004970 Fn = ObjCTypes.MessageSendStretFixupFn;
4971 Name += "objc_msgSend_stret_fixup";
4972 }
4973 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004974 else if (ResultType->isFloatingType() &&
4975 // Selection of frret API only happens in 32bit nonfragile ABI.
4976 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004977 Fn = ObjCTypes.MessageSendFpretFixupFn;
4978 Name += "objc_msgSend_fpret_fixup";
4979 }
4980 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004981#if 0
4982// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004983 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4984 Fn = ObjCTypes.MessageSendIdFixupFn;
4985 Name += "objc_msgSendId_fixup";
4986 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004987 else
4988#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004989 if (IsSuper) {
4990 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4991 Name += "objc_msgSendSuper2_fixup";
4992 }
4993 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004994 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004995 Fn = ObjCTypes.MessageSendFixupFn;
4996 Name += "objc_msgSend_fixup";
4997 }
4998 }
4999 Name += '_';
5000 std::string SelName(Sel.getAsString());
5001 // Replace all ':' in selector name with '_' ouch!
5002 for(unsigned i = 0; i < SelName.size(); i++)
5003 if (SelName[i] == ':')
5004 SelName[i] = '_';
5005 Name += SelName;
5006 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5007 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005008 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005009 std::vector<llvm::Constant*> Values(2);
5010 Values[0] = Fn;
5011 Values[1] = GetMethodVarName(Sel);
5012 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5013 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005014 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005015 Init,
5016 Name,
5017 &CGM.getModule());
5018 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005019 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005020 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005021 }
5022 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005023
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005024 CallArgList ActualArgs;
5025 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5026 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5027 ObjCTypes.MessageRefCPtrTy));
5028 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005029 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5030 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5031 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005032 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005033 Callee = CGF.Builder.CreateBitCast(Callee,
5034 llvm::PointerType::getUnqual(FTy));
5035 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005036}
5037
5038/// Generate code for a message send expression in the nonfragile abi.
5039CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5040 CodeGen::CodeGenFunction &CGF,
5041 QualType ResultType,
5042 Selector Sel,
5043 llvm::Value *Receiver,
5044 bool IsClassMessage,
5045 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005046 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005047 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005048 false, CallArgs);
5049}
5050
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005051llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005052CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005053 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5054
Daniel Dunbardfff2302009-03-02 05:18:14 +00005055 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005056 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5057 llvm::GlobalValue::ExternalLinkage,
5058 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005059 }
5060
5061 return GV;
5062}
5063
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005064llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005065 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005066 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5067
5068 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005069 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005070 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005071 Entry =
5072 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5073 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005074 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005075 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005076 &CGM.getModule());
5077 Entry->setAlignment(
5078 CGM.getTargetData().getPrefTypeAlignment(
5079 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005080 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5081 UsedGlobals.push_back(Entry);
5082 }
5083
5084 return Builder.CreateLoad(Entry, false, "tmp");
5085}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005086
Daniel Dunbar11394522009-04-18 08:51:00 +00005087llvm::Value *
5088CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5089 const ObjCInterfaceDecl *ID) {
5090 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5091
5092 if (!Entry) {
5093 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5094 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5095 Entry =
5096 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5097 llvm::GlobalValue::InternalLinkage,
5098 ClassGV,
5099 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5100 &CGM.getModule());
5101 Entry->setAlignment(
5102 CGM.getTargetData().getPrefTypeAlignment(
5103 ObjCTypes.ClassnfABIPtrTy));
5104 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005105 UsedGlobals.push_back(Entry);
5106 }
5107
5108 return Builder.CreateLoad(Entry, false, "tmp");
5109}
5110
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005111/// EmitMetaClassRef - Return a Value * of the address of _class_t
5112/// meta-data
5113///
5114llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5115 const ObjCInterfaceDecl *ID) {
5116 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5117 if (Entry)
5118 return Builder.CreateLoad(Entry, false, "tmp");
5119
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005120 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005121 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005122 Entry =
5123 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5124 llvm::GlobalValue::InternalLinkage,
5125 MetaClassGV,
5126 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5127 &CGM.getModule());
5128 Entry->setAlignment(
5129 CGM.getTargetData().getPrefTypeAlignment(
5130 ObjCTypes.ClassnfABIPtrTy));
5131
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005132 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005133 UsedGlobals.push_back(Entry);
5134
5135 return Builder.CreateLoad(Entry, false, "tmp");
5136}
5137
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005138/// GetClass - Return a reference to the class for the given interface
5139/// decl.
5140llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5141 const ObjCInterfaceDecl *ID) {
5142 return EmitClassRef(Builder, ID);
5143}
5144
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005145/// Generates a message send where the super is the receiver. This is
5146/// a message send to self with special delivery semantics indicating
5147/// which class's method should be called.
5148CodeGen::RValue
5149CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5150 QualType ResultType,
5151 Selector Sel,
5152 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005153 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005154 llvm::Value *Receiver,
5155 bool IsClassMessage,
5156 const CodeGen::CallArgList &CallArgs) {
5157 // ...
5158 // Create and init a super structure; this is a (receiver, class)
5159 // pair we will pass to objc_msgSendSuper.
5160 llvm::Value *ObjCSuper =
5161 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5162
5163 llvm::Value *ReceiverAsObject =
5164 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5165 CGF.Builder.CreateStore(ReceiverAsObject,
5166 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5167
5168 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005169 llvm::Value *Target;
5170 if (IsClassMessage) {
5171 if (isCategoryImpl) {
5172 // Message sent to "super' in a class method defined in
5173 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005174 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005175 Target = CGF.Builder.CreateStructGEP(Target, 0);
5176 Target = CGF.Builder.CreateLoad(Target);
5177 }
5178 else
5179 Target = EmitMetaClassRef(CGF.Builder, Class);
5180 }
5181 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005182 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005183
5184 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5185 // and ObjCTypes types.
5186 const llvm::Type *ClassTy =
5187 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5188 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5189 CGF.Builder.CreateStore(Target,
5190 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5191
5192 return EmitMessageSend(CGF, ResultType, Sel,
5193 ObjCSuper, ObjCTypes.SuperPtrCTy,
5194 true, CallArgs);
5195}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005196
5197llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5198 Selector Sel) {
5199 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5200
5201 if (!Entry) {
5202 llvm::Constant *Casted =
5203 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5204 ObjCTypes.SelectorPtrTy);
5205 Entry =
5206 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5207 llvm::GlobalValue::InternalLinkage,
5208 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5209 &CGM.getModule());
5210 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5211 UsedGlobals.push_back(Entry);
5212 }
5213
5214 return Builder.CreateLoad(Entry, false, "tmp");
5215}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005216/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5217/// objc_assign_ivar (id src, id *dst)
5218///
5219void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5220 llvm::Value *src, llvm::Value *dst)
5221{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005222 const llvm::Type * SrcTy = src->getType();
5223 if (!isa<llvm::PointerType>(SrcTy)) {
5224 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5225 assert(Size <= 8 && "does not support size > 8");
5226 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5227 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005228 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5229 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005230 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5231 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5232 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5233 src, dst, "assignivar");
5234 return;
5235}
5236
5237/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5238/// objc_assign_strongCast (id src, id *dst)
5239///
5240void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5241 CodeGen::CodeGenFunction &CGF,
5242 llvm::Value *src, llvm::Value *dst)
5243{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005244 const llvm::Type * SrcTy = src->getType();
5245 if (!isa<llvm::PointerType>(SrcTy)) {
5246 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5247 assert(Size <= 8 && "does not support size > 8");
5248 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5249 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005250 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5251 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005252 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5253 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5254 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5255 src, dst, "weakassign");
5256 return;
5257}
5258
5259/// EmitObjCWeakRead - Code gen for loading value of a __weak
5260/// object: objc_read_weak (id *src)
5261///
5262llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5263 CodeGen::CodeGenFunction &CGF,
5264 llvm::Value *AddrWeakObj)
5265{
Eli Friedman8339b352009-03-07 03:57:15 +00005266 const llvm::Type* DestTy =
5267 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005268 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5269 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5270 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005271 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005272 return read_weak;
5273}
5274
5275/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5276/// objc_assign_weak (id src, id *dst)
5277///
5278void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5279 llvm::Value *src, llvm::Value *dst)
5280{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005281 const llvm::Type * SrcTy = src->getType();
5282 if (!isa<llvm::PointerType>(SrcTy)) {
5283 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5284 assert(Size <= 8 && "does not support size > 8");
5285 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5286 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005287 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5288 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005289 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5290 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005291 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005292 src, dst, "weakassign");
5293 return;
5294}
5295
5296/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5297/// objc_assign_global (id src, id *dst)
5298///
5299void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5300 llvm::Value *src, llvm::Value *dst)
5301{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005302 const llvm::Type * SrcTy = src->getType();
5303 if (!isa<llvm::PointerType>(SrcTy)) {
5304 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5305 assert(Size <= 8 && "does not support size > 8");
5306 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5307 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005308 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5309 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005310 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5311 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5312 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5313 src, dst, "globalassign");
5314 return;
5315}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005316
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005317void
5318CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5319 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005320 bool isTry = isa<ObjCAtTryStmt>(S);
5321 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5322 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005323 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005324 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005325 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005326 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5327
5328 // For @synchronized, call objc_sync_enter(sync.expr). The
5329 // evaluation of the expression must occur before we enter the
5330 // @synchronized. We can safely avoid a temp here because jumps into
5331 // @synchronized are illegal & this will dominate uses.
5332 llvm::Value *SyncArg = 0;
5333 if (!isTry) {
5334 SyncArg =
5335 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5336 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005337 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005338 }
5339
5340 // Push an EH context entry, used for handling rethrows and jumps
5341 // through finally.
5342 CGF.PushCleanupBlock(FinallyBlock);
5343
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005344 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005345
5346 CGF.EmitBlock(TryBlock);
5347 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5348 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5349 CGF.EmitBranchThroughCleanup(FinallyEnd);
5350
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005351 // Emit the exception handler.
5352
5353 CGF.EmitBlock(TryHandler);
5354
5355 llvm::Value *llvm_eh_exception =
5356 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5357 llvm::Value *llvm_eh_selector_i64 =
5358 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5359 llvm::Value *llvm_eh_typeid_for_i64 =
5360 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5361 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5362 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5363
5364 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5365 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005366 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005367
5368 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005369 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005370 bool HasCatchAll = false;
5371 if (isTry) {
5372 if (const ObjCAtCatchStmt* CatchStmt =
5373 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5374 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005375 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005376 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005377
5378 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005379 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005380 // Use i8* null here to signal this is a catch all, not a cleanup.
5381 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5382 SelectorArgs.push_back(Null);
5383 HasCatchAll = true;
5384 break;
5385 }
5386
Daniel Dunbarede8de92009-03-06 00:01:21 +00005387 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5388 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005389 llvm::Value *IDEHType =
5390 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5391 if (!IDEHType)
5392 IDEHType =
5393 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5394 llvm::GlobalValue::ExternalLinkage,
5395 0, "OBJC_EHTYPE_id", &CGM.getModule());
5396 SelectorArgs.push_back(IDEHType);
5397 HasCatchAll = true;
5398 break;
5399 }
5400
5401 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005402 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005403 assert(PT && "Invalid @catch type.");
5404 const ObjCInterfaceType *IT =
5405 PT->getPointeeType()->getAsObjCInterfaceType();
5406 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005407 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005408 SelectorArgs.push_back(EHType);
5409 }
5410 }
5411 }
5412
5413 // We use a cleanup unless there was already a catch all.
5414 if (!HasCatchAll) {
5415 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005416 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005417 }
5418
5419 llvm::Value *Selector =
5420 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5421 SelectorArgs.begin(), SelectorArgs.end(),
5422 "selector");
5423 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005424 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005425 const Stmt *CatchBody = Handlers[i].second;
5426
5427 llvm::BasicBlock *Next = 0;
5428
5429 // The last handler always matches.
5430 if (i + 1 != e) {
5431 assert(CatchParam && "Only last handler can be a catch all.");
5432
5433 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5434 Next = CGF.createBasicBlock("catch.next");
5435 llvm::Value *Id =
5436 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5437 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5438 ObjCTypes.Int8PtrTy));
5439 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5440 Match, Next);
5441
5442 CGF.EmitBlock(Match);
5443 }
5444
5445 if (CatchBody) {
5446 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5447 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5448
5449 // Cleanups must call objc_end_catch.
5450 //
5451 // FIXME: It seems incorrect for objc_begin_catch to be inside
5452 // this context, but this matches gcc.
5453 CGF.PushCleanupBlock(MatchEnd);
5454 CGF.setInvokeDest(MatchHandler);
5455
5456 llvm::Value *ExcObject =
5457 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5458
5459 // Bind the catch parameter if it exists.
5460 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005461 ExcObject =
5462 CGF.Builder.CreateBitCast(ExcObject,
5463 CGF.ConvertType(CatchParam->getType()));
5464 // CatchParam is a ParmVarDecl because of the grammar
5465 // construction used to handle this, but for codegen purposes
5466 // we treat this as a local decl.
5467 CGF.EmitLocalBlockVarDecl(*CatchParam);
5468 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005469 }
5470
5471 CGF.ObjCEHValueStack.push_back(ExcObject);
5472 CGF.EmitStmt(CatchBody);
5473 CGF.ObjCEHValueStack.pop_back();
5474
5475 CGF.EmitBranchThroughCleanup(FinallyEnd);
5476
5477 CGF.EmitBlock(MatchHandler);
5478
5479 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5480 // We are required to emit this call to satisfy LLVM, even
5481 // though we don't use the result.
5482 llvm::SmallVector<llvm::Value*, 8> Args;
5483 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005484 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005485 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5486 0));
5487 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5488 CGF.Builder.CreateStore(Exc, RethrowPtr);
5489 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5490
5491 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5492
5493 CGF.EmitBlock(MatchEnd);
5494
5495 // Unfortunately, we also have to generate another EH frame here
5496 // in case this throws.
5497 llvm::BasicBlock *MatchEndHandler =
5498 CGF.createBasicBlock("match.end.handler");
5499 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5500 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5501 Cont, MatchEndHandler,
5502 Args.begin(), Args.begin());
5503
5504 CGF.EmitBlock(Cont);
5505 if (Info.SwitchBlock)
5506 CGF.EmitBlock(Info.SwitchBlock);
5507 if (Info.EndBlock)
5508 CGF.EmitBlock(Info.EndBlock);
5509
5510 CGF.EmitBlock(MatchEndHandler);
5511 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5512 // We are required to emit this call to satisfy LLVM, even
5513 // though we don't use the result.
5514 Args.clear();
5515 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005516 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005517 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5518 0));
5519 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5520 CGF.Builder.CreateStore(Exc, RethrowPtr);
5521 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5522
5523 if (Next)
5524 CGF.EmitBlock(Next);
5525 } else {
5526 assert(!Next && "catchup should be last handler.");
5527
5528 CGF.Builder.CreateStore(Exc, RethrowPtr);
5529 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5530 }
5531 }
5532
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005533 // Pop the cleanup entry, the @finally is outside this cleanup
5534 // scope.
5535 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5536 CGF.setInvokeDest(PrevLandingPad);
5537
5538 CGF.EmitBlock(FinallyBlock);
5539
5540 if (isTry) {
5541 if (const ObjCAtFinallyStmt* FinallyStmt =
5542 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5543 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5544 } else {
5545 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5546 // @synchronized.
5547 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005548 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005549
5550 if (Info.SwitchBlock)
5551 CGF.EmitBlock(Info.SwitchBlock);
5552 if (Info.EndBlock)
5553 CGF.EmitBlock(Info.EndBlock);
5554
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005555 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005556 CGF.EmitBranch(FinallyEnd);
5557
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005558 CGF.EmitBlock(FinallyRethrow);
5559 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5560 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005561 CGF.Builder.CreateUnreachable();
5562
5563 CGF.EmitBlock(FinallyEnd);
5564}
5565
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005566/// EmitThrowStmt - Generate code for a throw statement.
5567void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5568 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005569 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005570 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005571 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005572 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005573 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5574 "Unexpected rethrow outside @catch block.");
5575 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005576 }
5577
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005578 llvm::Value *ExceptionAsObject =
5579 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5580 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5581 if (InvokeDest) {
5582 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5583 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5584 Cont, InvokeDest,
5585 &ExceptionAsObject, &ExceptionAsObject + 1);
5586 CGF.EmitBlock(Cont);
5587 } else
5588 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5589 CGF.Builder.CreateUnreachable();
5590
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005591 // Clear the insertion point to indicate we are in unreachable code.
5592 CGF.Builder.ClearInsertionPoint();
5593}
Daniel Dunbare588b992009-03-01 04:46:24 +00005594
5595llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005596CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5597 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005598 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005599
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005600 // If we don't need a definition, return the entry if found or check
5601 // if we use an external reference.
5602 if (!ForDefinition) {
5603 if (Entry)
5604 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005605
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005606 // If this type (or a super class) has the __objc_exception__
5607 // attribute, emit an external reference.
5608 if (hasObjCExceptionAttribute(ID))
5609 return Entry =
5610 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5611 llvm::GlobalValue::ExternalLinkage,
5612 0,
5613 (std::string("OBJC_EHTYPE_$_") +
5614 ID->getIdentifier()->getName()),
5615 &CGM.getModule());
5616 }
5617
5618 // Otherwise we need to either make a new entry or fill in the
5619 // initializer.
5620 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005621 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005622 std::string VTableName = "objc_ehtype_vtable";
5623 llvm::GlobalVariable *VTableGV =
5624 CGM.getModule().getGlobalVariable(VTableName);
5625 if (!VTableGV)
5626 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5627 llvm::GlobalValue::ExternalLinkage,
5628 0, VTableName, &CGM.getModule());
5629
5630 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5631
5632 std::vector<llvm::Constant*> Values(3);
5633 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5634 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005635 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005636 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5637
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005638 if (Entry) {
5639 Entry->setInitializer(Init);
5640 } else {
5641 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5642 llvm::GlobalValue::WeakAnyLinkage,
5643 Init,
5644 (std::string("OBJC_EHTYPE_$_") +
5645 ID->getIdentifier()->getName()),
5646 &CGM.getModule());
5647 }
5648
Daniel Dunbar04d40782009-04-14 06:00:08 +00005649 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005650 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005651 Entry->setAlignment(8);
5652
5653 if (ForDefinition) {
5654 Entry->setSection("__DATA,__objc_const");
5655 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5656 } else {
5657 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5658 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005659
5660 return Entry;
5661}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005662
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005663/* *** */
5664
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005665CodeGen::CGObjCRuntime *
5666CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005667 return new CGObjCMac(CGM);
5668}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005669
5670CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005671CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005672 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005673}