blob: 323b5c9f54f2b4f3f2be6ad4d67c9f893e640cd7 [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 Lattner34b02a12009-04-22 02:26:14 +0000197 llvm::Constant *getExceptionTryEnterFn() {
198 std::vector<const llvm::Type*> Params;
199 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
200 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
201 Params, false),
202 "objc_exception_try_enter");
203 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000204
205 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000206 llvm::Constant *getExceptionTryExitFn() {
207 std::vector<const llvm::Type*> Params;
208 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
209 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
210 Params, false),
211 "objc_exception_try_exit");
212 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000213
214 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000215 llvm::Constant *getExceptionExtractFn() {
216 std::vector<const llvm::Type*> Params;
217 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
218 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
219 Params, false),
220 "objc_exception_extract");
221
222 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000223
224 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000225 llvm::Constant *getExceptionMatchFn() {
226 std::vector<const llvm::Type*> Params;
227 Params.push_back(ClassPtrTy);
228 Params.push_back(ObjectPtrTy);
229 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
230 Params, false),
231 "objc_exception_match");
232
233 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000234
235 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000236 llvm::Constant *getSetJmpFn() {
237 std::vector<const llvm::Type*> Params;
238 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
239 return
240 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
241 Params, false),
242 "_setjmp");
243
244 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000245
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000246public:
247 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000248 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000249
250
Chris Lattner74391b42009-03-22 21:03:39 +0000251 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000252 return IsSuper ? MessageSendSuperFn : MessageSendFn;
253 }
254
Chris Lattner74391b42009-03-22 21:03:39 +0000255 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000256 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
257 }
258
Chris Lattner74391b42009-03-22 21:03:39 +0000259 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000260 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
261 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000262};
263
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000264/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000265/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000266class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000267public:
Chris Lattner74391b42009-03-22 21:03:39 +0000268 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000269 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
270 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
271 *MessageSendSuper2StretFixupFn;
272
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000273 // MethodListnfABITy - LLVM for struct _method_list_t
274 const llvm::StructType *MethodListnfABITy;
275
276 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
277 const llvm::Type *MethodListnfABIPtrTy;
278
279 // ProtocolnfABITy = LLVM for struct _protocol_t
280 const llvm::StructType *ProtocolnfABITy;
281
Daniel Dunbar948e2582009-02-15 07:36:20 +0000282 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
283 const llvm::Type *ProtocolnfABIPtrTy;
284
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000285 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
286 const llvm::StructType *ProtocolListnfABITy;
287
288 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
289 const llvm::Type *ProtocolListnfABIPtrTy;
290
291 // ClassnfABITy - LLVM for struct _class_t
292 const llvm::StructType *ClassnfABITy;
293
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000294 // ClassnfABIPtrTy - LLVM for struct _class_t*
295 const llvm::Type *ClassnfABIPtrTy;
296
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000297 // IvarnfABITy - LLVM for struct _ivar_t
298 const llvm::StructType *IvarnfABITy;
299
300 // IvarListnfABITy - LLVM for struct _ivar_list_t
301 const llvm::StructType *IvarListnfABITy;
302
303 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
304 const llvm::Type *IvarListnfABIPtrTy;
305
306 // ClassRonfABITy - LLVM for struct _class_ro_t
307 const llvm::StructType *ClassRonfABITy;
308
309 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
310 const llvm::Type *ImpnfABITy;
311
312 // CategorynfABITy - LLVM for struct _category_t
313 const llvm::StructType *CategorynfABITy;
314
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000315 // New types for nonfragile abi messaging.
316
317 // MessageRefTy - LLVM for:
318 // struct _message_ref_t {
319 // IMP messenger;
320 // SEL name;
321 // };
322 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000323 // MessageRefCTy - clang type for struct _message_ref_t
324 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000325
326 // MessageRefPtrTy - LLVM for struct _message_ref_t*
327 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000328 // MessageRefCPtrTy - clang type for struct _message_ref_t*
329 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000330
Fariborz Jahanianef163782009-02-05 01:13:09 +0000331 // MessengerTy - Type of the messenger (shown as IMP above)
332 const llvm::FunctionType *MessengerTy;
333
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000334 // SuperMessageRefTy - LLVM for:
335 // struct _super_message_ref_t {
336 // SUPER_IMP messenger;
337 // SEL name;
338 // };
339 const llvm::StructType *SuperMessageRefTy;
340
341 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
342 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000343
344 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
345 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000346 llvm::Value *getEHPersonalityPtr() {
347 llvm::Constant *Personality =
348 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
349 std::vector<const llvm::Type*>(),
350 true),
351 "__objc_personality_v0");
352 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
353 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000354
Chris Lattner8a569112009-04-22 02:15:23 +0000355 llvm::Constant *getUnwindResumeOrRethrowFn() {
356 std::vector<const llvm::Type*> Params;
357 Params.push_back(Int8PtrTy);
358 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
359 Params, false),
360 "_Unwind_Resume_or_Rethrow");
361 }
362
363 llvm::Constant *getObjCEndCatchFn() {
364 std::vector<const llvm::Type*> Params;
365 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
366 Params, false),
367 "objc_end_catch");
368
369 }
370
371 llvm::Constant *getObjCBeginCatchFn() {
372 std::vector<const llvm::Type*> Params;
373 Params.push_back(Int8PtrTy);
374 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
375 Params, false),
376 "objc_begin_catch");
377 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000378
379 const llvm::StructType *EHTypeTy;
380 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000381
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000382 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
383 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000384};
385
386class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000387public:
388 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000389 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000390 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000391 unsigned int ivar_bytepos;
392 unsigned int ivar_size;
393 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
394 };
395
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000396 class SKIP_SCAN {
397 public:
398 unsigned int skip;
399 unsigned int scan;
400 SKIP_SCAN() : skip(0), scan(0) {}
401 };
402
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000403protected:
404 CodeGen::CodeGenModule &CGM;
405 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000406 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000407
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000408 // gc ivar layout bitmap calculation helper caches.
409 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
410 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
411 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000412
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000413 /// LazySymbols - Symbols to generate a lazy reference for. See
414 /// DefinedSymbols and FinishModule().
415 std::set<IdentifierInfo*> LazySymbols;
416
417 /// DefinedSymbols - External symbols which are defined by this
418 /// module. The symbols in this list and LazySymbols are used to add
419 /// special linker symbols which ensure that Objective-C modules are
420 /// linked properly.
421 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000422
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000423 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000424 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000425
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000426 /// MethodVarNames - uniqued method variable names.
427 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000428
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000429 /// MethodVarTypes - uniqued method type signatures. We have to use
430 /// a StringMap here because have no other unique reference.
431 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000432
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000433 /// MethodDefinitions - map of methods which have been defined in
434 /// this translation unit.
435 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000436
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000437 /// PropertyNames - uniqued method variable names.
438 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000439
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000440 /// ClassReferences - uniqued class references.
441 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000442
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000443 /// SelectorReferences - uniqued selector references.
444 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000445
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000446 /// Protocols - Protocols for which an objc_protocol structure has
447 /// been emitted. Forward declarations are handled by creating an
448 /// empty structure whose initializer is filled in when/if defined.
449 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000450
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000451 /// DefinedProtocols - Protocols which have actually been
452 /// defined. We should not need this, see FIXME in GenerateProtocol.
453 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000454
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000455 /// DefinedClasses - List of defined classes.
456 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000457
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000458 /// DefinedCategories - List of defined categories.
459 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000460
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000461 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000462 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000463 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000464
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000465 /// GetNameForMethod - Return a name for the given method.
466 /// \param[out] NameOut - The return value.
467 void GetNameForMethod(const ObjCMethodDecl *OMD,
468 const ObjCContainerDecl *CD,
469 std::string &NameOut);
470
471 /// GetMethodVarName - Return a unique constant for the given
472 /// selector's name. The return value has type char *.
473 llvm::Constant *GetMethodVarName(Selector Sel);
474 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
475 llvm::Constant *GetMethodVarName(const std::string &Name);
476
477 /// GetMethodVarType - Return a unique constant for the given
478 /// selector's name. The return value has type char *.
479
480 // FIXME: This is a horrible name.
481 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000482 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000483
484 /// GetPropertyName - Return a unique constant for the given
485 /// name. The return value has type char *.
486 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
487
488 // FIXME: This can be dropped once string functions are unified.
489 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
490 const Decl *Container);
491
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000492 /// GetClassName - Return a unique constant for the given selector's
493 /// name. The return value has type char *.
494 llvm::Constant *GetClassName(IdentifierInfo *Ident);
495
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000496 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
497 /// interface declaration.
498 const llvm::StructLayout *GetInterfaceDeclStructLayout(
499 const ObjCInterfaceDecl *ID) const;
500
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000501 /// BuildIvarLayout - Builds ivar layout bitmap for the class
502 /// implementation for the __strong or __weak case.
503 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000504 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
505 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000506
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000507 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
508 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000509 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000510 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000511 unsigned int BytePos, bool ForStrongLayout,
512 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000513
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000514 /// GetIvarLayoutName - Returns a unique constant for the given
515 /// ivar layout bitmap.
516 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
517 const ObjCCommonTypesHelper &ObjCTypes);
518
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000519 /// EmitPropertyList - Emit the given property list. The return
520 /// value has type PropertyListPtrTy.
521 llvm::Constant *EmitPropertyList(const std::string &Name,
522 const Decl *Container,
523 const ObjCContainerDecl *OCD,
524 const ObjCCommonTypesHelper &ObjCTypes);
525
Fariborz Jahanianda320092009-01-29 19:24:30 +0000526 /// GetProtocolRef - Return a reference to the internal protocol
527 /// description, creating an empty one if it has not been
528 /// defined. The return value has type ProtocolPtrTy.
529 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000530
531 /// GetIvarBaseOffset - returns ivars byte offset.
532 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000533 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000534
Chris Lattnercd0ee142009-03-31 08:33:16 +0000535 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000536 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
537 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000538 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000539
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000540 /// CreateMetadataVar - Create a global variable with internal
541 /// linkage for use by the Objective-C runtime.
542 ///
543 /// This is a convenience wrapper which not only creates the
544 /// variable, but also sets the section and alignment and adds the
545 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000546 ///
547 /// \param Name - The variable name.
548 /// \param Init - The variable initializer; this is also used to
549 /// define the type of the variable.
550 /// \param Section - The section the variable should go into, or 0.
551 /// \param Align - The alignment for the variable, or 0.
552 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000553 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000554 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
555 llvm::Constant *Init,
556 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000557 unsigned Align,
558 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000559
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000560 /// GetNamedIvarList - Return the list of ivars in the interface
561 /// itself (not including super classes and not including unnamed
562 /// bitfields).
563 ///
564 /// For the non-fragile ABI, this also includes synthesized property
565 /// ivars.
566 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
567 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
568
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000569public:
570 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
571 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000572
Steve Naroff33fdb732009-03-31 16:53:37 +0000573 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000574
575 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
576 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000577
578 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
579
580 /// GetOrEmitProtocol - Get the protocol object for the given
581 /// declaration, emitting it if necessary. The return value has type
582 /// ProtocolPtrTy.
583 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
584
585 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
586 /// object for the given declaration, emitting it if needed. These
587 /// forward references will be filled in with empty bodies if no
588 /// definition is seen. The return value has type ProtocolPtrTy.
589 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000590};
591
592class CGObjCMac : public CGObjCCommonMac {
593private:
594 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000595 /// EmitImageInfo - Emit the image info marker used to encode some module
596 /// level information.
597 void EmitImageInfo();
598
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000599 /// EmitModuleInfo - Another marker encoding module level
600 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000601 void EmitModuleInfo();
602
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000603 /// EmitModuleSymols - Emit module symbols, the list of defined
604 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000605 llvm::Constant *EmitModuleSymbols();
606
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000607 /// FinishModule - Write out global data structures at the end of
608 /// processing a translation unit.
609 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000610
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000611 /// EmitClassExtension - Generate the class extension structure used
612 /// to store the weak ivar layout and properties. The return value
613 /// has type ClassExtensionPtrTy.
614 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
615
616 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
617 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000618 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000619 const ObjCInterfaceDecl *ID);
620
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000621 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000622 QualType ResultType,
623 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000624 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000625 QualType Arg0Ty,
626 bool IsSuper,
627 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000628
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000629 /// EmitIvarList - Emit the ivar list for the given
630 /// implementation. If ForClass is true the list of class ivars
631 /// (i.e. metaclass ivars) is emitted, otherwise the list of
632 /// interface ivars will be emitted. The return value has type
633 /// IvarListPtrTy.
634 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000635 bool ForClass);
636
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000637 /// EmitMetaClass - Emit a forward reference to the class structure
638 /// for the metaclass of the given interface. The return value has
639 /// type ClassPtrTy.
640 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
641
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000642 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000643 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000644 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
645 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000646 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000647 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000648
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000649 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000650
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000651 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000652
653 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000654 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000655 llvm::Constant *EmitMethodList(const std::string &Name,
656 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000657 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000658
659 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000660 /// method declarations.
661 /// - TypeName: The name for the type containing the methods.
662 /// - IsProtocol: True iff these methods are for a protocol.
663 /// - ClassMethds: True iff these are class methods.
664 /// - Required: When true, only "required" methods are
665 /// listed. Similarly, when false only "optional" methods are
666 /// listed. For classes this should always be true.
667 /// - begin, end: The method list to output.
668 ///
669 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000670 llvm::Constant *EmitMethodDescList(const std::string &Name,
671 const char *Section,
672 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000673
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000674 /// GetOrEmitProtocol - Get the protocol object for the given
675 /// declaration, emitting it if necessary. The return value has type
676 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000677 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000678
679 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
680 /// object for the given declaration, emitting it if needed. These
681 /// forward references will be filled in with empty bodies if no
682 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000683 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000684
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000685 /// EmitProtocolExtension - Generate the protocol extension
686 /// structure used to store optional instance and class methods, and
687 /// protocol properties. The return value has type
688 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000689 llvm::Constant *
690 EmitProtocolExtension(const ObjCProtocolDecl *PD,
691 const ConstantVector &OptInstanceMethods,
692 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000693
694 /// EmitProtocolList - Generate the list of referenced
695 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000696 llvm::Constant *EmitProtocolList(const std::string &Name,
697 ObjCProtocolDecl::protocol_iterator begin,
698 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000699
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000700 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
701 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000702 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000703
Fariborz Jahanianda320092009-01-29 19:24:30 +0000704 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000705 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000706
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000707 virtual llvm::Function *ModuleInitFunction();
708
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000709 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000710 QualType ResultType,
711 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000712 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000713 bool IsClassMessage,
714 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000715
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000716 virtual CodeGen::RValue
717 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000718 QualType ResultType,
719 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000720 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000721 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000722 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000723 bool IsClassMessage,
724 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000725
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000726 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000727 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000728
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000729 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000730
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000731 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000732
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000733 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000734
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000735 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000736 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000737
Chris Lattner74391b42009-03-22 21:03:39 +0000738 virtual llvm::Constant *GetPropertyGetFunction();
739 virtual llvm::Constant *GetPropertySetFunction();
740 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000741
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000742 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
743 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000744 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
745 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000746 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000747 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000748 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
749 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000750 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
751 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000752 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
753 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000754 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
755 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000756
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000757 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
758 QualType ObjectTy,
759 llvm::Value *BaseValue,
760 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000761 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000762 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
763 ObjCInterfaceDecl *Interface,
764 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000765};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000766
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000767class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000768private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000769 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000770 llvm::GlobalVariable* ObjCEmptyCacheVar;
771 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000772
Daniel Dunbar11394522009-04-18 08:51:00 +0000773 /// SuperClassReferences - uniqued super class references.
774 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
775
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000776 /// MetaClassReferences - uniqued meta class references.
777 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000778
779 /// EHTypeReferences - uniqued class ehtype references.
780 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000781
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000782 /// FinishNonFragileABIModule - Write out global data structures at the end of
783 /// processing a translation unit.
784 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000785
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000786 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
787 unsigned InstanceStart,
788 unsigned InstanceSize,
789 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000790 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
791 llvm::Constant *IsAGV,
792 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000793 llvm::Constant *ClassRoGV,
794 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000795
796 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
797
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000798 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
799
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000800 /// EmitMethodList - Emit the method list for the given
801 /// implementation. The return value has type MethodListnfABITy.
802 llvm::Constant *EmitMethodList(const std::string &Name,
803 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000804 const ConstantVector &Methods);
805 /// EmitIvarList - Emit the ivar list for the given
806 /// implementation. If ForClass is true the list of class ivars
807 /// (i.e. metaclass ivars) is emitted, otherwise the list of
808 /// interface ivars will be emitted. The return value has type
809 /// IvarListnfABIPtrTy.
810 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000811
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000812 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000813 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000814 unsigned long int offset);
815
Fariborz Jahanianda320092009-01-29 19:24:30 +0000816 /// GetOrEmitProtocol - Get the protocol object for the given
817 /// declaration, emitting it if necessary. The return value has type
818 /// ProtocolPtrTy.
819 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
820
821 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
822 /// object for the given declaration, emitting it if needed. These
823 /// forward references will be filled in with empty bodies if no
824 /// definition is seen. The return value has type ProtocolPtrTy.
825 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
826
827 /// EmitProtocolList - Generate the list of referenced
828 /// protocols. The return value has type ProtocolListPtrTy.
829 llvm::Constant *EmitProtocolList(const std::string &Name,
830 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000831 ObjCProtocolDecl::protocol_iterator end);
832
833 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
834 QualType ResultType,
835 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000836 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000837 QualType Arg0Ty,
838 bool IsSuper,
839 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000840
841 /// GetClassGlobal - Return the global variable for the Objective-C
842 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +0000843 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
844
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000845 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +0000846 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000847 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +0000848 const ObjCInterfaceDecl *ID);
849
850 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
851 /// for the given super class reference.
852 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
853 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000854
855 /// EmitMetaClassRef - Return a Value * of the address of _class_t
856 /// meta-data
857 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
858 const ObjCInterfaceDecl *ID);
859
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000860 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
861 /// the given ivar.
862 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +0000863 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000864 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000865 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000866
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000867 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
868 /// for the given selector.
869 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000870
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000871 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +0000872 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000873 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
874 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000875
876 const char *getMetaclassSymbolPrefix() const {
877 return "OBJC_METACLASS_$_";
878 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000879
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000880 const char *getClassSymbolPrefix() const {
881 return "OBJC_CLASS_$_";
882 }
883
Daniel Dunbarb02532a2009-04-19 23:41:48 +0000884 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
885 uint32_t &InstanceStart,
886 uint32_t &InstanceSize);
887
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000888public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000889 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000890 // FIXME. All stubs for now!
891 virtual llvm::Function *ModuleInitFunction();
892
893 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
894 QualType ResultType,
895 Selector Sel,
896 llvm::Value *Receiver,
897 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000898 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000899
900 virtual CodeGen::RValue
901 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
902 QualType ResultType,
903 Selector Sel,
904 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000905 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000906 llvm::Value *Receiver,
907 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000908 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000909
910 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000911 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000912
913 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000914 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000915
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000916 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000917
918 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000919 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000920 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000921
Chris Lattner74391b42009-03-22 21:03:39 +0000922 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000923 return ObjCTypes.GetPropertyFn;
924 }
Chris Lattner74391b42009-03-22 21:03:39 +0000925 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000926 return ObjCTypes.SetPropertyFn;
927 }
Chris Lattner74391b42009-03-22 21:03:39 +0000928 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000929 return ObjCTypes.EnumerationMutationFn;
930 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000931
932 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000933 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000934 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000935 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000936 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000937 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000938 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000939 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000940 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000941 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000942 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000943 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000944 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000945 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000946 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
947 QualType ObjectTy,
948 llvm::Value *BaseValue,
949 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000950 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000951 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
952 ObjCInterfaceDecl *Interface,
953 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000954};
955
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000956} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000957
958/* *** Helper Functions *** */
959
960/// getConstantGEP() - Help routine to construct simple GEPs.
961static llvm::Constant *getConstantGEP(llvm::Constant *C,
962 unsigned idx0,
963 unsigned idx1) {
964 llvm::Value *Idxs[] = {
965 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
966 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
967 };
968 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
969}
970
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000971/// hasObjCExceptionAttribute - Return true if this class or any super
972/// class has the __objc_exception__ attribute.
973static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000974 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000975 return true;
976 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
977 return hasObjCExceptionAttribute(Super);
978 return false;
979}
980
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000981/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000982
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000983CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
984 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000985{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000986 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000987 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000988}
989
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000990/// GetClass - Return a reference to the class for the given interface
991/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000992llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000993 const ObjCInterfaceDecl *ID) {
994 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000995}
996
997/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000998llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000999 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001000}
1001
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001002/// Generate a constant CFString object.
1003/*
1004 struct __builtin_CFString {
1005 const int *isa; // point to __CFConstantStringClassReference
1006 int flags;
1007 const char *str;
1008 long length;
1009 };
1010*/
1011
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001012llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001013 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001014 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001015}
1016
1017/// Generates a message send where the super is the receiver. This is
1018/// a message send to self with special delivery semantics indicating
1019/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001020CodeGen::RValue
1021CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001022 QualType ResultType,
1023 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001024 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001025 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001026 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001027 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001028 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001029 // Create and init a super structure; this is a (receiver, class)
1030 // pair we will pass to objc_msgSendSuper.
1031 llvm::Value *ObjCSuper =
1032 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1033 llvm::Value *ReceiverAsObject =
1034 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1035 CGF.Builder.CreateStore(ReceiverAsObject,
1036 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001037
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001038 // If this is a class message the metaclass is passed as the target.
1039 llvm::Value *Target;
1040 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001041 if (isCategoryImpl) {
1042 // Message sent to 'super' in a class method defined in a category
1043 // implementation requires an odd treatment.
1044 // If we are in a class method, we must retrieve the
1045 // _metaclass_ for the current class, pointed at by
1046 // the class's "isa" pointer. The following assumes that
1047 // isa" is the first ivar in a class (which it must be).
1048 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1049 Target = CGF.Builder.CreateStructGEP(Target, 0);
1050 Target = CGF.Builder.CreateLoad(Target);
1051 }
1052 else {
1053 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1054 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1055 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1056 Target = Super;
1057 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001058 } else {
1059 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1060 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001061 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1062 // and ObjCTypes types.
1063 const llvm::Type *ClassTy =
1064 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001065 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001066 CGF.Builder.CreateStore(Target,
1067 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1068
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001069 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001070 ObjCSuper, ObjCTypes.SuperPtrCTy,
1071 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001072}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001073
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001074/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001075CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001076 QualType ResultType,
1077 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001078 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001079 bool IsClassMessage,
1080 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001081 llvm::Value *Arg0 =
1082 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001083 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001084 Arg0, CGF.getContext().getObjCIdType(),
1085 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001086}
1087
1088CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001089 QualType ResultType,
1090 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001091 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001092 QualType Arg0Ty,
1093 bool IsSuper,
1094 const CallArgList &CallArgs) {
1095 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001096 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1097 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1098 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001099 CGF.getContext().getObjCSelType()));
1100 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001101
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001102 CodeGenTypes &Types = CGM.getTypes();
1103 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1104 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001105
1106 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001107 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001108 Fn = ObjCTypes.getSendStretFn(IsSuper);
1109 } else if (ResultType->isFloatingType()) {
1110 // FIXME: Sadly, this is wrong. This actually depends on the
1111 // architecture. This happens to be right for x86-32 though.
1112 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1113 } else {
1114 Fn = ObjCTypes.getSendFn(IsSuper);
1115 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001116 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001117 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001118}
1119
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001120llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001121 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001122 // FIXME: I don't understand why gcc generates this, or where it is
1123 // resolved. Investigate. Its also wasteful to look this up over and
1124 // over.
1125 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1126
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001127 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1128 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001129}
1130
Fariborz Jahanianda320092009-01-29 19:24:30 +00001131void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001132 // FIXME: We shouldn't need this, the protocol decl should contain
1133 // enough information to tell us whether this was a declaration or a
1134 // definition.
1135 DefinedProtocols.insert(PD->getIdentifier());
1136
1137 // If we have generated a forward reference to this protocol, emit
1138 // it now. Otherwise do nothing, the protocol objects are lazily
1139 // emitted.
1140 if (Protocols.count(PD->getIdentifier()))
1141 GetOrEmitProtocol(PD);
1142}
1143
Fariborz Jahanianda320092009-01-29 19:24:30 +00001144llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001145 if (DefinedProtocols.count(PD->getIdentifier()))
1146 return GetOrEmitProtocol(PD);
1147 return GetOrEmitProtocolRef(PD);
1148}
1149
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001150/*
1151 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1152 struct _objc_protocol {
1153 struct _objc_protocol_extension *isa;
1154 char *protocol_name;
1155 struct _objc_protocol_list *protocol_list;
1156 struct _objc__method_prototype_list *instance_methods;
1157 struct _objc__method_prototype_list *class_methods
1158 };
1159
1160 See EmitProtocolExtension().
1161*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001162llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1163 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1164
1165 // Early exit if a defining object has already been generated.
1166 if (Entry && Entry->hasInitializer())
1167 return Entry;
1168
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001169 // FIXME: I don't understand why gcc generates this, or where it is
1170 // resolved. Investigate. Its also wasteful to look this up over and
1171 // over.
1172 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1173
Chris Lattner8ec03f52008-11-24 03:54:41 +00001174 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001175
1176 // Construct method lists.
1177 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1178 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001179 for (ObjCProtocolDecl::instmeth_iterator
1180 i = PD->instmeth_begin(CGM.getContext()),
1181 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001182 ObjCMethodDecl *MD = *i;
1183 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1184 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1185 OptInstanceMethods.push_back(C);
1186 } else {
1187 InstanceMethods.push_back(C);
1188 }
1189 }
1190
Douglas Gregor6ab35242009-04-09 21:40:53 +00001191 for (ObjCProtocolDecl::classmeth_iterator
1192 i = PD->classmeth_begin(CGM.getContext()),
1193 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001194 ObjCMethodDecl *MD = *i;
1195 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1196 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1197 OptClassMethods.push_back(C);
1198 } else {
1199 ClassMethods.push_back(C);
1200 }
1201 }
1202
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001203 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001204 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001205 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001206 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001207 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001208 PD->protocol_begin(),
1209 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001210 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001211 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1212 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001213 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1214 InstanceMethods);
1215 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001216 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1217 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001218 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1219 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001220 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1221 Values);
1222
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001223 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001224 // Already created, fix the linkage and update the initializer.
1225 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001226 Entry->setInitializer(Init);
1227 } else {
1228 Entry =
1229 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1230 llvm::GlobalValue::InternalLinkage,
1231 Init,
1232 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1233 &CGM.getModule());
1234 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001235 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001236 UsedGlobals.push_back(Entry);
1237 // FIXME: Is this necessary? Why only for protocol?
1238 Entry->setAlignment(4);
1239 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001240
1241 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001242}
1243
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001244llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001245 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1246
1247 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001248 // We use the initializer as a marker of whether this is a forward
1249 // reference or not. At module finalization we add the empty
1250 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001251 Entry =
1252 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001253 llvm::GlobalValue::ExternalLinkage,
1254 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001255 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001256 &CGM.getModule());
1257 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001258 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001259 UsedGlobals.push_back(Entry);
1260 // FIXME: Is this necessary? Why only for protocol?
1261 Entry->setAlignment(4);
1262 }
1263
1264 return Entry;
1265}
1266
1267/*
1268 struct _objc_protocol_extension {
1269 uint32_t size;
1270 struct objc_method_description_list *optional_instance_methods;
1271 struct objc_method_description_list *optional_class_methods;
1272 struct objc_property_list *instance_properties;
1273 };
1274*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001275llvm::Constant *
1276CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1277 const ConstantVector &OptInstanceMethods,
1278 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001279 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001280 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001281 std::vector<llvm::Constant*> Values(4);
1282 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001283 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001284 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1285 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001286 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1287 OptInstanceMethods);
1288 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001289 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1290 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001291 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1292 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001293 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1294 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001295 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001296
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001297 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001298 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1299 Values[3]->isNullValue())
1300 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1301
1302 llvm::Constant *Init =
1303 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001304
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001305 // No special section, but goes in llvm.used
1306 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1307 Init,
1308 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001309}
1310
1311/*
1312 struct objc_protocol_list {
1313 struct objc_protocol_list *next;
1314 long count;
1315 Protocol *list[];
1316 };
1317*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001318llvm::Constant *
1319CGObjCMac::EmitProtocolList(const std::string &Name,
1320 ObjCProtocolDecl::protocol_iterator begin,
1321 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001322 std::vector<llvm::Constant*> ProtocolRefs;
1323
Daniel Dunbardbc933702008-08-21 21:57:41 +00001324 for (; begin != end; ++begin)
1325 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001326
1327 // Just return null for empty protocol lists
1328 if (ProtocolRefs.empty())
1329 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1330
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001331 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001332 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1333
1334 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001335 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001336 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1337 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1338 Values[2] =
1339 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1340 ProtocolRefs.size()),
1341 ProtocolRefs);
1342
1343 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1344 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001345 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001346 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001347 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1348}
1349
1350/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001351 struct _objc_property {
1352 const char * const name;
1353 const char * const attributes;
1354 };
1355
1356 struct _objc_property_list {
1357 uint32_t entsize; // sizeof (struct _objc_property)
1358 uint32_t prop_count;
1359 struct _objc_property[prop_count];
1360 };
1361*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001362llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1363 const Decl *Container,
1364 const ObjCContainerDecl *OCD,
1365 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001366 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001367 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1368 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001369 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001370 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001371 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001372 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1373 Prop));
1374 }
1375
1376 // Return null for empty list.
1377 if (Properties.empty())
1378 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1379
1380 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001381 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001382 std::vector<llvm::Constant*> Values(3);
1383 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1384 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1385 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1386 Properties.size());
1387 Values[2] = llvm::ConstantArray::get(AT, Properties);
1388 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1389
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001390 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001391 CreateMetadataVar(Name, Init,
1392 (ObjCABI == 2) ? "__DATA, __objc_const" :
1393 "__OBJC,__property,regular,no_dead_strip",
1394 (ObjCABI == 2) ? 8 : 4,
1395 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001396 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001397}
1398
1399/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001400 struct objc_method_description_list {
1401 int count;
1402 struct objc_method_description list[];
1403 };
1404*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001405llvm::Constant *
1406CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1407 std::vector<llvm::Constant*> Desc(2);
1408 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1409 ObjCTypes.SelectorPtrTy);
1410 Desc[1] = GetMethodVarType(MD);
1411 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1412 Desc);
1413}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001414
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001415llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1416 const char *Section,
1417 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001418 // Return null for empty list.
1419 if (Methods.empty())
1420 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1421
1422 std::vector<llvm::Constant*> Values(2);
1423 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1424 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1425 Methods.size());
1426 Values[1] = llvm::ConstantArray::get(AT, Methods);
1427 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1428
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001429 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001430 return llvm::ConstantExpr::getBitCast(GV,
1431 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001432}
1433
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001434/*
1435 struct _objc_category {
1436 char *category_name;
1437 char *class_name;
1438 struct _objc_method_list *instance_methods;
1439 struct _objc_method_list *class_methods;
1440 struct _objc_protocol_list *protocols;
1441 uint32_t size; // <rdar://4585769>
1442 struct _objc_property_list *instance_properties;
1443 };
1444 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001445void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001446 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001447
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001448 // FIXME: This is poor design, the OCD should have a pointer to the
1449 // category decl. Additionally, note that Category can be null for
1450 // the @implementation w/o an @interface case. Sema should just
1451 // create one for us as it does for @implementation so everyone else
1452 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001453 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001454 const ObjCCategoryDecl *Category =
1455 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001456 std::string ExtName(Interface->getNameAsString() + "_" +
1457 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001458
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001459 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1460 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1461 e = OCD->instmeth_end(); i != e; ++i) {
1462 // Instance methods should always be defined.
1463 InstanceMethods.push_back(GetMethodConstant(*i));
1464 }
1465 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1466 e = OCD->classmeth_end(); i != e; ++i) {
1467 // Class methods should always be defined.
1468 ClassMethods.push_back(GetMethodConstant(*i));
1469 }
1470
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001471 std::vector<llvm::Constant*> Values(7);
1472 Values[0] = GetClassName(OCD->getIdentifier());
1473 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001474 Values[2] =
1475 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1476 ExtName,
1477 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001478 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001479 Values[3] =
1480 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001481 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001482 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001483 if (Category) {
1484 Values[4] =
1485 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1486 Category->protocol_begin(),
1487 Category->protocol_end());
1488 } else {
1489 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1490 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001491 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001492
1493 // If there is no category @interface then there can be no properties.
1494 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001495 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001496 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001497 } else {
1498 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1499 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001500
1501 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1502 Values);
1503
1504 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001505 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1506 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001507 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001508 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001509}
1510
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001511// FIXME: Get from somewhere?
1512enum ClassFlags {
1513 eClassFlags_Factory = 0x00001,
1514 eClassFlags_Meta = 0x00002,
1515 // <rdr://5142207>
1516 eClassFlags_HasCXXStructors = 0x02000,
1517 eClassFlags_Hidden = 0x20000,
1518 eClassFlags_ABI2_Hidden = 0x00010,
1519 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1520};
1521
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001522/*
1523 struct _objc_class {
1524 Class isa;
1525 Class super_class;
1526 const char *name;
1527 long version;
1528 long info;
1529 long instance_size;
1530 struct _objc_ivar_list *ivars;
1531 struct _objc_method_list *methods;
1532 struct _objc_cache *cache;
1533 struct _objc_protocol_list *protocols;
1534 // Objective-C 1.0 extensions (<rdr://4585769>)
1535 const char *ivar_layout;
1536 struct _objc_class_ext *ext;
1537 };
1538
1539 See EmitClassExtension();
1540 */
1541void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001542 DefinedSymbols.insert(ID->getIdentifier());
1543
Chris Lattner8ec03f52008-11-24 03:54:41 +00001544 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001545 // FIXME: Gross
1546 ObjCInterfaceDecl *Interface =
1547 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001548 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001549 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001550 Interface->protocol_begin(),
1551 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001552 const llvm::Type *InterfaceTy;
1553 if (Interface->isForwardDecl())
1554 InterfaceTy = llvm::StructType::get(NULL, NULL);
1555 else
1556 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001557 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001558 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001559 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001560
1561 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001562 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001563 Flags |= eClassFlags_Hidden;
1564
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001565 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1566 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1567 e = ID->instmeth_end(); i != e; ++i) {
1568 // Instance methods should always be defined.
1569 InstanceMethods.push_back(GetMethodConstant(*i));
1570 }
1571 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1572 e = ID->classmeth_end(); i != e; ++i) {
1573 // Class methods should always be defined.
1574 ClassMethods.push_back(GetMethodConstant(*i));
1575 }
1576
1577 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1578 e = ID->propimpl_end(); i != e; ++i) {
1579 ObjCPropertyImplDecl *PID = *i;
1580
1581 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1582 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1583
1584 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1585 if (llvm::Constant *C = GetMethodConstant(MD))
1586 InstanceMethods.push_back(C);
1587 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1588 if (llvm::Constant *C = GetMethodConstant(MD))
1589 InstanceMethods.push_back(C);
1590 }
1591 }
1592
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001593 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001594 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001595 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001596 // Record a reference to the super class.
1597 LazySymbols.insert(Super->getIdentifier());
1598
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001599 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, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001611 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001612 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001613 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001614 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001615 // cache is always NULL.
1616 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1617 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001618 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001619 // Values[10] = BuildIvarLayout(ID, true);
1620 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001621 Values[11] = EmitClassExtension(ID);
1622 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1623 Values);
1624
1625 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001626 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1627 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001628 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001629 DefinedClasses.push_back(GV);
1630}
1631
1632llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1633 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001634 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001635 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001636 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001637 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001638
Daniel Dunbar04d40782009-04-14 06:00:08 +00001639 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001640 Flags |= eClassFlags_Hidden;
1641
1642 std::vector<llvm::Constant*> Values(12);
1643 // The isa for the metaclass is the root of the hierarchy.
1644 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1645 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1646 Root = Super;
1647 Values[ 0] =
1648 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1649 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001650 // The super class for the metaclass is emitted as the name of the
1651 // super class. The runtime fixes this up to point to the
1652 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001653 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1654 Values[ 1] =
1655 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1656 ObjCTypes.ClassPtrTy);
1657 } else {
1658 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1659 }
1660 Values[ 2] = GetClassName(ID->getIdentifier());
1661 // Version is always 0.
1662 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1663 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1664 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001665 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001666 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001667 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001668 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001669 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001670 // cache is always NULL.
1671 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1672 Values[ 9] = Protocols;
1673 // ivar_layout for metaclass is always NULL.
1674 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1675 // The class extension is always unused for metaclasses.
1676 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1677 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1678 Values);
1679
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001680 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001681 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001682
1683 // Check for a forward reference.
1684 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1685 if (GV) {
1686 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1687 "Forward metaclass reference has incorrect type.");
1688 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1689 GV->setInitializer(Init);
1690 } else {
1691 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1692 llvm::GlobalValue::InternalLinkage,
1693 Init, Name,
1694 &CGM.getModule());
1695 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001696 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001697 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001698 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001699
1700 return GV;
1701}
1702
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001703llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001704 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001705
1706 // FIXME: Should we look these up somewhere other than the
1707 // module. Its a bit silly since we only generate these while
1708 // processing an implementation, so exactly one pointer would work
1709 // if know when we entered/exitted an implementation block.
1710
1711 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001712 // Previously, metaclass with internal linkage may have been defined.
1713 // pass 'true' as 2nd argument so it is returned.
1714 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001715 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1716 "Forward metaclass reference has incorrect type.");
1717 return GV;
1718 } else {
1719 // Generate as an external reference to keep a consistent
1720 // module. This will be patched up when we emit the metaclass.
1721 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1722 llvm::GlobalValue::ExternalLinkage,
1723 0,
1724 Name,
1725 &CGM.getModule());
1726 }
1727}
1728
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001729/*
1730 struct objc_class_ext {
1731 uint32_t size;
1732 const char *weak_ivar_layout;
1733 struct _objc_property_list *properties;
1734 };
1735*/
1736llvm::Constant *
1737CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1738 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001739 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001740
1741 std::vector<llvm::Constant*> Values(3);
1742 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001743 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001744 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001745 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001746 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001747 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001748
1749 // Return null if no extension bits are used.
1750 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1751 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1752
1753 llvm::Constant *Init =
1754 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001755 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001756 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1757 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001758}
1759
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001760/// getInterfaceDeclForIvar - Get the interface declaration node where
1761/// this ivar is declared in.
1762/// FIXME. Ideally, this info should be in the ivar node. But currently
1763/// it is not and prevailing wisdom is that ASTs should not have more
1764/// info than is absolutely needed, even though this info reflects the
1765/// source language.
1766///
1767static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1768 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001769 const ObjCIvarDecl *IVD,
1770 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001771 if (!OI)
1772 return 0;
1773 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1774 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1775 E = OI->ivar_end(); I != E; ++I)
1776 if ((*I)->getIdentifier() == IVD->getIdentifier())
1777 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001778 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001779 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1780 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001781 ObjCPropertyDecl *PDecl = (*I);
1782 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1783 if (IV->getIdentifier() == IVD->getIdentifier())
1784 return OI;
1785 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001786 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001787}
1788
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001789/*
1790 struct objc_ivar {
1791 char *ivar_name;
1792 char *ivar_type;
1793 int ivar_offset;
1794 };
1795
1796 struct objc_ivar_list {
1797 int ivar_count;
1798 struct objc_ivar list[count];
1799 };
1800 */
1801llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001802 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001803 std::vector<llvm::Constant*> Ivars, Ivar(3);
1804
1805 // When emitting the root class GCC emits ivar entries for the
1806 // actual class structure. It is not clear if we need to follow this
1807 // behavior; for now lets try and get away with not doing it. If so,
1808 // the cleanest solution would be to make up an ObjCInterfaceDecl
1809 // for the class.
1810 if (ForClass)
1811 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001812
1813 ObjCInterfaceDecl *OID =
1814 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001815 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001816
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001817 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1818 GetNamedIvarList(OID, OIvars);
1819
1820 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1821 ObjCIvarDecl *IVD = OIvars[i];
1822 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00001823 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00001824 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00001825 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
1826 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001827 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001828 }
1829
1830 // Return null for empty list.
1831 if (Ivars.empty())
1832 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1833
1834 std::vector<llvm::Constant*> Values(2);
1835 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1836 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1837 Ivars.size());
1838 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1839 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1840
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001841 llvm::GlobalVariable *GV;
1842 if (ForClass)
1843 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001844 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1845 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001846 else
1847 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1848 + ID->getNameAsString(),
1849 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001850 4, true);
1851 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001852}
1853
1854/*
1855 struct objc_method {
1856 SEL method_name;
1857 char *method_types;
1858 void *method;
1859 };
1860
1861 struct objc_method_list {
1862 struct objc_method_list *obsolete;
1863 int count;
1864 struct objc_method methods_list[count];
1865 };
1866*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001867
1868/// GetMethodConstant - Return a struct objc_method constant for the
1869/// given method if it has been defined. The result is null if the
1870/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001871llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001872 // FIXME: Use DenseMap::lookup
1873 llvm::Function *Fn = MethodDefinitions[MD];
1874 if (!Fn)
1875 return 0;
1876
1877 std::vector<llvm::Constant*> Method(3);
1878 Method[0] =
1879 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1880 ObjCTypes.SelectorPtrTy);
1881 Method[1] = GetMethodVarType(MD);
1882 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1883 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1884}
1885
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001886llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1887 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001888 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001889 // Return null for empty list.
1890 if (Methods.empty())
1891 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1892
1893 std::vector<llvm::Constant*> Values(3);
1894 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1895 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1896 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1897 Methods.size());
1898 Values[2] = llvm::ConstantArray::get(AT, Methods);
1899 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1900
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001901 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001902 return llvm::ConstantExpr::getBitCast(GV,
1903 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001904}
1905
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001906llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001907 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001908 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001909 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001910
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001911 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001912 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001913 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001914 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001915 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001916 llvm::GlobalValue::InternalLinkage,
1917 Name,
1918 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001919 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001920
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001921 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001922}
1923
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001924uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001925 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001926 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001927 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
1928
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001929 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001930 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
1931 // FIXME: The "field no" for bitfields is something completely
1932 // different; it is the offset in multiples of the base type size!
1933 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
1934 const llvm::Type *Ty =
1935 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1936 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1937 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001938}
1939
Daniel Dunbar48fa0642009-04-19 02:03:42 +00001940/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001941uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1942 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001943 const FieldDecl *Field) {
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00001944 // Is this a c struct?
1945 if (!OI)
1946 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001947 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001948 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1949 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001950}
1951
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001952llvm::GlobalVariable *
1953CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1954 llvm::Constant *Init,
1955 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001956 unsigned Align,
1957 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001958 const llvm::Type *Ty = Init->getType();
1959 llvm::GlobalVariable *GV =
1960 new llvm::GlobalVariable(Ty, false,
1961 llvm::GlobalValue::InternalLinkage,
1962 Init,
1963 Name,
1964 &CGM.getModule());
1965 if (Section)
1966 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001967 if (Align)
1968 GV->setAlignment(Align);
1969 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001970 UsedGlobals.push_back(GV);
1971 return GV;
1972}
1973
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001974llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001975 // Abuse this interface function as a place to finalize.
1976 FinishModule();
1977
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001978 return NULL;
1979}
1980
Chris Lattner74391b42009-03-22 21:03:39 +00001981llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001982 return ObjCTypes.GetPropertyFn;
1983}
1984
Chris Lattner74391b42009-03-22 21:03:39 +00001985llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001986 return ObjCTypes.SetPropertyFn;
1987}
1988
Chris Lattner74391b42009-03-22 21:03:39 +00001989llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001990 return ObjCTypes.EnumerationMutationFn;
1991}
1992
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001993/*
1994
1995Objective-C setjmp-longjmp (sjlj) Exception Handling
1996--
1997
1998The basic framework for a @try-catch-finally is as follows:
1999{
2000 objc_exception_data d;
2001 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002002 bool _call_try_exit = true;
2003
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002004 objc_exception_try_enter(&d);
2005 if (!setjmp(d.jmp_buf)) {
2006 ... try body ...
2007 } else {
2008 // exception path
2009 id _caught = objc_exception_extract(&d);
2010
2011 // enter new try scope for handlers
2012 if (!setjmp(d.jmp_buf)) {
2013 ... match exception and execute catch blocks ...
2014
2015 // fell off end, rethrow.
2016 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002017 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002018 } else {
2019 // exception in catch block
2020 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002021 _call_try_exit = false;
2022 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002023 }
2024 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002025 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002026
2027finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002028 if (_call_try_exit)
2029 objc_exception_try_exit(&d);
2030
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002031 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002032 ... dispatch to finally destination ...
2033
2034finally_rethrow:
2035 objc_exception_throw(_rethrow);
2036
2037finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002038}
2039
2040This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002041uses _rethrow to determine if objc_exception_try_exit should be called
2042and if the object should be rethrown. This breaks in the face of
2043throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002044
2045We specialize this framework for a few particular circumstances:
2046
2047 - If there are no catch blocks, then we avoid emitting the second
2048 exception handling context.
2049
2050 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2051 e)) we avoid emitting the code to rethrow an uncaught exception.
2052
2053 - FIXME: If there is no @finally block we can do a few more
2054 simplifications.
2055
2056Rethrows and Jumps-Through-Finally
2057--
2058
2059Support for implicit rethrows and jumping through the finally block is
2060handled by storing the current exception-handling context in
2061ObjCEHStack.
2062
Daniel Dunbar898d5082008-09-30 01:06:03 +00002063In order to implement proper @finally semantics, we support one basic
2064mechanism for jumping through the finally block to an arbitrary
2065destination. Constructs which generate exits from a @try or @catch
2066block use this mechanism to implement the proper semantics by chaining
2067jumps, as necessary.
2068
2069This mechanism works like the one used for indirect goto: we
2070arbitrarily assign an ID to each destination and store the ID for the
2071destination in a variable prior to entering the finally block. At the
2072end of the finally block we simply create a switch to the proper
2073destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002074
2075Code gen for @synchronized(expr) stmt;
2076Effectively generating code for:
2077objc_sync_enter(expr);
2078@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002079*/
2080
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002081void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2082 const Stmt &S) {
2083 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002084 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002085 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002086 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002087 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2088 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2089 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002090
2091 // For @synchronized, call objc_sync_enter(sync.expr). The
2092 // evaluation of the expression must occur before we enter the
2093 // @synchronized. We can safely avoid a temp here because jumps into
2094 // @synchronized are illegal & this will dominate uses.
2095 llvm::Value *SyncArg = 0;
2096 if (!isTry) {
2097 SyncArg =
2098 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2099 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002100 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002101 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002102
2103 // Push an EH context entry, used for handling rethrows and jumps
2104 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002105 CGF.PushCleanupBlock(FinallyBlock);
2106
Anders Carlsson273558f2009-02-07 21:37:21 +00002107 CGF.ObjCEHValueStack.push_back(0);
2108
Daniel Dunbar898d5082008-09-30 01:06:03 +00002109 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002110 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2111 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002112 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2113 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002114 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2115 "_call_try_exit");
2116 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2117
Anders Carlsson80f25672008-09-09 17:59:25 +00002118 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002119 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002120 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2121 "jmpbufarray");
2122 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002123 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002124 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002125
Daniel Dunbar55e87422008-11-11 02:29:29 +00002126 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2127 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002128 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002129 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002130
2131 // Emit the @try block.
2132 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002133 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2134 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002135 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002136
2137 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002138 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002139
2140 // Retrieve the exception object. We may emit multiple blocks but
2141 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002142 llvm::Value *Caught =
2143 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2144 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002145 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002146 if (!isTry)
2147 {
2148 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002149 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002150 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002151 }
2152 else if (const ObjCAtCatchStmt* CatchStmt =
2153 cast<ObjCAtTryStmt>(S).getCatchStmts())
2154 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002155 // Enter a new exception try block (in case a @catch block throws
2156 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002157 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002158
Chris Lattner34b02a12009-04-22 02:26:14 +00002159 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002160 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002161 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002162
Daniel Dunbar55e87422008-11-11 02:29:29 +00002163 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2164 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002165 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002166
2167 CGF.EmitBlock(CatchBlock);
2168
Daniel Dunbar55e40722008-09-27 07:03:52 +00002169 // Handle catch list. As a special case we check if everything is
2170 // matched and avoid generating code for falling off the end if
2171 // so.
2172 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002173 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002174 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002175
Steve Naroff7ba138a2009-03-03 19:52:17 +00002176 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002177 const PointerType *PT = 0;
2178
Anders Carlsson80f25672008-09-09 17:59:25 +00002179 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002180 if (!CatchParam) {
2181 AllMatched = true;
2182 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002183 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002184
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002185 // catch(id e) always matches.
2186 // FIXME: For the time being we also match id<X>; this should
2187 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002188 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002189 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002190 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002191 }
2192
Daniel Dunbar55e40722008-09-27 07:03:52 +00002193 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002194 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002195 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002196 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002197 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002198 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002199
Anders Carlssondde0a942008-09-11 09:15:33 +00002200 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002201 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002202 break;
2203 }
2204
Daniel Dunbar129271a2008-09-27 07:36:24 +00002205 assert(PT && "Unexpected non-pointer type in @catch");
2206 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002207 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002208 assert(ObjCType && "Catch parameter must have Objective-C type!");
2209
2210 // Check if the @catch block matches the exception object.
2211 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2212
Chris Lattner34b02a12009-04-22 02:26:14 +00002213 llvm::Value *Match =
2214 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2215 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002216
Daniel Dunbar55e87422008-11-11 02:29:29 +00002217 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002218
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002219 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002220 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002221
2222 // Emit the @catch block.
2223 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002224 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002225 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002226
2227 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002228 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002229 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002230 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002231
2232 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002233 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002234
2235 CGF.EmitBlock(NextCatchBlock);
2236 }
2237
Daniel Dunbar55e40722008-09-27 07:03:52 +00002238 if (!AllMatched) {
2239 // None of the handlers caught the exception, so store it to be
2240 // rethrown at the end of the @finally block.
2241 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002242 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002243 }
2244
2245 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002246 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002247 CGF.Builder.CreateStore(
2248 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2249 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002250 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002251 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002252 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002253 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002254 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002255 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002256 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002257 }
2258
Daniel Dunbar898d5082008-09-30 01:06:03 +00002259 // Pop the exception-handling stack entry. It is important to do
2260 // this now, because the code in the @finally block is not in this
2261 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002262 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2263
Anders Carlsson273558f2009-02-07 21:37:21 +00002264 CGF.ObjCEHValueStack.pop_back();
2265
Anders Carlsson80f25672008-09-09 17:59:25 +00002266 // Emit the @finally block.
2267 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002268 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2269
2270 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2271
2272 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002273 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002274
2275 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002276 if (isTry) {
2277 if (const ObjCAtFinallyStmt* FinallyStmt =
2278 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2279 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002280 } else {
2281 // Emit objc_sync_exit(expr); as finally's sole statement for
2282 // @synchronized.
2283 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002284 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002285
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002286 // Emit the switch block
2287 if (Info.SwitchBlock)
2288 CGF.EmitBlock(Info.SwitchBlock);
2289 if (Info.EndBlock)
2290 CGF.EmitBlock(Info.EndBlock);
2291
Daniel Dunbar898d5082008-09-30 01:06:03 +00002292 CGF.EmitBlock(FinallyRethrow);
2293 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2294 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002295 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002296
2297 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002298}
2299
2300void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002301 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002302 llvm::Value *ExceptionAsObject;
2303
2304 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2305 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2306 ExceptionAsObject =
2307 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2308 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002309 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002310 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002311 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002312 }
2313
2314 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002315 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002316
2317 // Clear the insertion point to indicate we are in unreachable code.
2318 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002319}
2320
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002321/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002322/// object: objc_read_weak (id *src)
2323///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002324llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002325 llvm::Value *AddrWeakObj)
2326{
Eli Friedman8339b352009-03-07 03:57:15 +00002327 const llvm::Type* DestTy =
2328 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002329 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002330 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002331 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002332 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002333 return read_weak;
2334}
2335
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002336/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2337/// objc_assign_weak (id src, id *dst)
2338///
2339void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2340 llvm::Value *src, llvm::Value *dst)
2341{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002342 const llvm::Type * SrcTy = src->getType();
2343 if (!isa<llvm::PointerType>(SrcTy)) {
2344 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2345 assert(Size <= 8 && "does not support size > 8");
2346 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2347 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002348 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2349 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002350 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2351 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002352 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002353 src, dst, "weakassign");
2354 return;
2355}
2356
Fariborz Jahanian58626502008-11-19 00:59:10 +00002357/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2358/// objc_assign_global (id src, id *dst)
2359///
2360void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2361 llvm::Value *src, llvm::Value *dst)
2362{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002363 const llvm::Type * SrcTy = src->getType();
2364 if (!isa<llvm::PointerType>(SrcTy)) {
2365 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2366 assert(Size <= 8 && "does not support size > 8");
2367 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2368 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002369 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2370 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002371 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2372 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002373 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2374 src, dst, "globalassign");
2375 return;
2376}
2377
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002378/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2379/// objc_assign_ivar (id src, id *dst)
2380///
2381void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2382 llvm::Value *src, llvm::Value *dst)
2383{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002384 const llvm::Type * SrcTy = src->getType();
2385 if (!isa<llvm::PointerType>(SrcTy)) {
2386 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2387 assert(Size <= 8 && "does not support size > 8");
2388 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2389 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002390 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2391 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002392 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2393 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2394 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2395 src, dst, "assignivar");
2396 return;
2397}
2398
Fariborz Jahanian58626502008-11-19 00:59:10 +00002399/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2400/// objc_assign_strongCast (id src, id *dst)
2401///
2402void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2403 llvm::Value *src, llvm::Value *dst)
2404{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002405 const llvm::Type * SrcTy = src->getType();
2406 if (!isa<llvm::PointerType>(SrcTy)) {
2407 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2408 assert(Size <= 8 && "does not support size > 8");
2409 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2410 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002411 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2412 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002413 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2414 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002415 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2416 src, dst, "weakassign");
2417 return;
2418}
2419
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002420/// EmitObjCValueForIvar - Code Gen for ivar reference.
2421///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002422LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2423 QualType ObjectTy,
2424 llvm::Value *BaseValue,
2425 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002426 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002427 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2428 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002429 if (Ivar->isBitField())
2430 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2431 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002432 // TODO: Add a special case for isa (index 0)
2433 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2434 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002435 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002436 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2437 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002438 LValue::SetObjCIvar(LV, true);
2439 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002440}
2441
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002442llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2443 ObjCInterfaceDecl *Interface,
2444 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002445 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002446 const FieldDecl *Field =
2447 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002448 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002449 return llvm::ConstantInt::get(
2450 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2451 Offset);
2452}
2453
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002454/* *** Private Interface *** */
2455
2456/// EmitImageInfo - Emit the image info marker used to encode some module
2457/// level information.
2458///
2459/// See: <rdr://4810609&4810587&4810587>
2460/// struct IMAGE_INFO {
2461/// unsigned version;
2462/// unsigned flags;
2463/// };
2464enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002465 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2466 // this implies.
2467 eImageInfo_GarbageCollected = (1 << 1),
2468 eImageInfo_GCOnly = (1 << 2),
2469 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2470
2471 // A flag indicating that the module has no instances of an
2472 // @synthesize of a superclass variable. <rdar://problem/6803242>
2473 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002474};
2475
2476void CGObjCMac::EmitImageInfo() {
2477 unsigned version = 0; // Version is unused?
2478 unsigned flags = 0;
2479
2480 // FIXME: Fix and continue?
2481 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2482 flags |= eImageInfo_GarbageCollected;
2483 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2484 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002485
2486 // We never allow @synthesize of a superclass property.
2487 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002488
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002489 // Emitted as int[2];
2490 llvm::Constant *values[2] = {
2491 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2492 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2493 };
2494 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002495
2496 const char *Section;
2497 if (ObjCABI == 1)
2498 Section = "__OBJC, __image_info,regular";
2499 else
2500 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002501 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002502 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2503 llvm::ConstantArray::get(AT, values, 2),
2504 Section,
2505 0,
2506 true);
2507 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002508}
2509
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002510
2511// struct objc_module {
2512// unsigned long version;
2513// unsigned long size;
2514// const char *name;
2515// Symtab symtab;
2516// };
2517
2518// FIXME: Get from somewhere
2519static const int ModuleVersion = 7;
2520
2521void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002522 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002523
2524 std::vector<llvm::Constant*> Values(4);
2525 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2526 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002527 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002528 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002529 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002530 CreateMetadataVar("\01L_OBJC_MODULES",
2531 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2532 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002533 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002534}
2535
2536llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002537 unsigned NumClasses = DefinedClasses.size();
2538 unsigned NumCategories = DefinedCategories.size();
2539
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002540 // Return null if no symbols were defined.
2541 if (!NumClasses && !NumCategories)
2542 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2543
2544 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002545 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2546 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2547 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2548 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2549
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002550 // The runtime expects exactly the list of defined classes followed
2551 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002552 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002553 for (unsigned i=0; i<NumClasses; i++)
2554 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2555 ObjCTypes.Int8PtrTy);
2556 for (unsigned i=0; i<NumCategories; i++)
2557 Symbols[NumClasses + i] =
2558 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2559 ObjCTypes.Int8PtrTy);
2560
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002561 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002562 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002563 NumClasses + NumCategories),
2564 Symbols);
2565
2566 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2567
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002568 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002569 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2570 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002571 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002572 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2573}
2574
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002575llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002576 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002577 LazySymbols.insert(ID->getIdentifier());
2578
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002579 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2580
2581 if (!Entry) {
2582 llvm::Constant *Casted =
2583 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2584 ObjCTypes.ClassPtrTy);
2585 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002586 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2587 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002588 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002589 }
2590
2591 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002592}
2593
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002594llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002595 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2596
2597 if (!Entry) {
2598 llvm::Constant *Casted =
2599 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2600 ObjCTypes.SelectorPtrTy);
2601 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002602 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2603 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002604 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002605 }
2606
2607 return Builder.CreateLoad(Entry, false, "tmp");
2608}
2609
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002610llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002611 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002612
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002613 if (!Entry)
2614 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2615 llvm::ConstantArray::get(Ident->getName()),
2616 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002617 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002618
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002619 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002620}
2621
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002622/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2623/// interface declaration.
2624const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2625 const ObjCInterfaceDecl *OID) const {
Daniel Dunbar24c89912009-04-21 21:41:56 +00002626 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002627 QualType T =
2628 CGM.getContext().getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID));
2629 const llvm::StructType *InterfaceTy =
2630 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2631 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002632}
2633
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002634/// GetIvarLayoutName - Returns a unique constant for the given
2635/// ivar layout bitmap.
2636llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2637 const ObjCCommonTypesHelper &ObjCTypes) {
2638 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2639}
2640
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002641void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2642 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002643 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002644 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002645 unsigned int BytePos, bool ForStrongLayout,
2646 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002647 bool IsUnion = (RD && RD->isUnion());
2648 uint64_t MaxUnionIvarSize = 0;
2649 uint64_t MaxSkippedUnionIvarSize = 0;
2650 FieldDecl *MaxField = 0;
2651 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002652 FieldDecl *LastFieldBitfield = 0;
2653
Chris Lattnerf1690852009-03-31 08:48:01 +00002654 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002655 if (RecFields.empty())
2656 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002657 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002658 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002659 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2660 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2661
2662 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2663
2664 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002665 FieldDecl *Field = RecFields[i];
2666 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002667 if (!Field->getIdentifier() || Field->isBitField()) {
2668 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002669 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002670 }
2671 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002672 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002673 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002674 if (FQT->isUnionType())
2675 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002676 else
2677 assert(FQT->isRecordType() &&
2678 "only union/record is supported for ivar layout bitmap");
2679
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002680 const RecordType *RT = FQT->getAsRecordType();
2681 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002682 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002683 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2684 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002685 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2686 const llvm::StructLayout *RecLayout =
2687 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2688
2689 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002690 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002691 ForStrongLayout, Index, SkIndex,
2692 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002693 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002694 continue;
2695 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002696
2697 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002698 const ConstantArrayType *CArray =
2699 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002700 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002701 assert(CArray && "only array with know element size is supported");
2702 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002703 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2704 const ConstantArrayType *CArray =
2705 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002706 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002707 FQT = CArray->getElementType();
2708 }
2709
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002710 assert(!FQT->isUnionType() &&
2711 "layout for array of unions not supported");
2712 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002713 int OldIndex = Index;
2714 int OldSkIndex = SkIndex;
2715
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002716 // FIXME - Use a common routine with the above!
2717 const RecordType *RT = FQT->getAsRecordType();
2718 const RecordDecl *RD = RT->getDecl();
2719 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002720 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2721 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002722 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2723 const llvm::StructLayout *RecLayout =
2724 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002725
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002726 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002727 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002728 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002729 ForStrongLayout, Index, SkIndex,
2730 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002731 TmpRecFields.clear();
2732
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002733 // Replicate layout information for each array element. Note that
2734 // one element is already done.
2735 uint64_t ElIx = 1;
2736 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2737 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002738 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002739 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2740 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002741 GC_IVAR gcivar;
2742 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2743 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2744 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002745 }
2746
Chris Lattnerf1690852009-03-31 08:48:01 +00002747 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002748 GC_IVAR skivar;
2749 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2750 skivar.ivar_size = SkipIvars[i].ivar_size;
2751 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002752 }
2753 }
2754 continue;
2755 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002756 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002757 // At this point, we are done with Record/Union and array there of.
2758 // For other arrays we are down to its element type.
2759 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2760 do {
2761 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2762 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2763 break;
2764 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002765 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002766 GCAttr = QualType::Strong;
2767 break;
2768 }
2769 else if (const PointerType *PT = FQT->getAsPointerType()) {
2770 FQT = PT->getPointeeType();
2771 }
2772 else {
2773 break;
2774 }
2775 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002776
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002777 if ((ForStrongLayout && GCAttr == QualType::Strong)
2778 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2779 if (IsUnion)
2780 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002781 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2782 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002783 if (UnionIvarSize > MaxUnionIvarSize)
2784 {
2785 MaxUnionIvarSize = UnionIvarSize;
2786 MaxField = Field;
2787 }
2788 }
2789 else
2790 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002791 GC_IVAR gcivar;
2792 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2793 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2794 WordSizeInBits;
2795 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002796 }
2797 }
2798 else if ((ForStrongLayout &&
2799 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2800 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2801 if (IsUnion)
2802 {
2803 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2804 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2805 {
2806 MaxSkippedUnionIvarSize = UnionIvarSize;
2807 MaxSkippedField = Field;
2808 }
2809 }
2810 else
2811 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002812 GC_IVAR skivar;
2813 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2814 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002815 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002816 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002817 }
2818 }
2819 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002820 if (LastFieldBitfield) {
2821 // Last field was a bitfield. Must update skip info.
2822 GC_IVAR skivar;
2823 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
2824 LastFieldBitfield);
2825 Expr *BitWidth = LastFieldBitfield->getBitWidth();
2826 uint64_t BitFieldSize =
2827 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
2828 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
2829 + ((BitFieldSize % ByteSizeInBits) != 0);
2830 SkipIvars.push_back(skivar); ++SkIndex;
2831 }
2832
Chris Lattnerf1690852009-03-31 08:48:01 +00002833 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002834 GC_IVAR gcivar;
2835 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2836 gcivar.ivar_size = MaxUnionIvarSize;
2837 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002838 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002839
2840 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002841 GC_IVAR skivar;
2842 skivar.ivar_bytepos = BytePos +
2843 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2844 skivar.ivar_size = MaxSkippedUnionIvarSize;
2845 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002846 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002847}
2848
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002849static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002850IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002851{
2852 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2853 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2854
2855 if (sa < sb)
2856 return -1;
2857 if (sa > sb)
2858 return 1;
2859 return 0;
2860}
2861
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002862/// BuildIvarLayout - Builds ivar layout bitmap for the class
2863/// implementation for the __strong or __weak case.
2864/// The layout map displays which words in ivar list must be skipped
2865/// and which must be scanned by GC (see below). String is built of bytes.
2866/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2867/// of words to skip and right nibble is count of words to scan. So, each
2868/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2869/// represented by a 0x00 byte which also ends the string.
2870/// 1. when ForStrongLayout is true, following ivars are scanned:
2871/// - id, Class
2872/// - object *
2873/// - __strong anything
2874///
2875/// 2. When ForStrongLayout is false, following ivars are scanned:
2876/// - __weak anything
2877///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002878llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002879 const ObjCImplementationDecl *OMD,
2880 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002881 int Index = -1;
2882 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002883 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002884 int SkipScan;
2885 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002886 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2887 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2888 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002889
Chris Lattnerf1690852009-03-31 08:48:01 +00002890 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002891 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002892 CGM.getContext().CollectObjCIvars(OI, RecFields);
2893 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002894 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002895
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002896 SkipIvars.clear();
2897 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002898
2899 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002900 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2901 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002902 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002903 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002904
2905 // Sort on byte position in case we encounterred a union nested in
2906 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002907 if (hasUnion && !IvarsInfo.empty())
2908 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2909 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002910 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2911
2912 // Build the string of skip/scan nibbles
2913 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002914 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002915 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002916 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002917 if (IvarsInfo[0].ivar_bytepos == 0) {
2918 WordsToSkip = 0;
2919 WordsToScan = IvarsInfo[0].ivar_size;
2920 }
2921 else {
2922 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2923 WordsToScan = IvarsInfo[0].ivar_size;
2924 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002925 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002926 {
2927 unsigned int TailPrevGCObjC =
2928 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2929 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2930 {
2931 // consecutive 'scanned' object pointers.
2932 WordsToScan += IvarsInfo[i].ivar_size;
2933 }
2934 else
2935 {
2936 // Skip over 'gc'able object pointer which lay over each other.
2937 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2938 continue;
2939 // Must skip over 1 or more words. We save current skip/scan values
2940 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002941 SKIP_SCAN SkScan;
2942 SkScan.skip = WordsToSkip;
2943 SkScan.scan = WordsToScan;
2944 SkipScanIvars.push_back(SkScan); ++SkipScan;
2945
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002946 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002947 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2948 SkScan.scan = 0;
2949 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002950 WordsToSkip = 0;
2951 WordsToScan = IvarsInfo[i].ivar_size;
2952 }
2953 }
2954 if (WordsToScan > 0)
2955 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002956 SKIP_SCAN SkScan;
2957 SkScan.skip = WordsToSkip;
2958 SkScan.scan = WordsToScan;
2959 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002960 }
2961
2962 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002963 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002964 {
2965 int LastByteSkipped =
2966 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2967 int LastByteScanned =
2968 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2969 BytesSkipped = (LastByteSkipped > LastByteScanned);
2970 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2971 if (BytesSkipped)
2972 {
2973 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002974 SKIP_SCAN SkScan;
2975 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2976 SkScan.scan = 0;
2977 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002978 }
2979 }
2980 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2981 // as 0xMN.
2982 for (int i = 0; i <= SkipScan; i++)
2983 {
2984 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2985 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2986 // 0xM0 followed by 0x0N detected.
2987 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2988 for (int j = i+1; j < SkipScan; j++)
2989 SkipScanIvars[j] = SkipScanIvars[j+1];
2990 --SkipScan;
2991 }
2992 }
2993
2994 // Generate the string.
2995 std::string BitMap;
2996 for (int i = 0; i <= SkipScan; i++)
2997 {
2998 unsigned char byte;
2999 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3000 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3001 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3002 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3003
3004 if (skip_small > 0 || skip_big > 0)
3005 BytesSkipped = true;
3006 // first skip big.
3007 for (unsigned int ix = 0; ix < skip_big; ix++)
3008 BitMap += (unsigned char)(0xf0);
3009
3010 // next (skip small, scan)
3011 if (skip_small)
3012 {
3013 byte = skip_small << 4;
3014 if (scan_big > 0)
3015 {
3016 byte |= 0xf;
3017 --scan_big;
3018 }
3019 else if (scan_small)
3020 {
3021 byte |= scan_small;
3022 scan_small = 0;
3023 }
3024 BitMap += byte;
3025 }
3026 // next scan big
3027 for (unsigned int ix = 0; ix < scan_big; ix++)
3028 BitMap += (unsigned char)(0x0f);
3029 // last scan small
3030 if (scan_small)
3031 {
3032 byte = scan_small;
3033 BitMap += byte;
3034 }
3035 }
3036 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003037 unsigned char zero = 0;
3038 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003039
3040 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3041 printf("\n%s ivar layout for class '%s': ",
3042 ForStrongLayout ? "strong" : "weak",
3043 OMD->getClassInterface()->getNameAsCString());
3044 const unsigned char *s = (unsigned char*)BitMap.c_str();
3045 for (unsigned i = 0; i < BitMap.size(); i++)
3046 if (!(s[i] & 0xf0))
3047 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3048 else
3049 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3050 printf("\n");
3051 }
3052
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003053 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3054 // final layout.
3055 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003056 return llvm::Constant::getNullValue(PtrTy);
3057 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3058 llvm::ConstantArray::get(BitMap.c_str()),
3059 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003060 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003061 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003062}
3063
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003064llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003065 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3066
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003067 // FIXME: Avoid std::string copying.
3068 if (!Entry)
3069 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3070 llvm::ConstantArray::get(Sel.getAsString()),
3071 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003072 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003073
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003074 return getConstantGEP(Entry, 0, 0);
3075}
3076
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003077// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003078llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003079 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3080}
3081
3082// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003083llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003084 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3085}
3086
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003087llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003088 std::string TypeStr;
3089 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3090
3091 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003092
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003093 if (!Entry)
3094 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3095 llvm::ConstantArray::get(TypeStr),
3096 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003097 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003098
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003099 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003100}
3101
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003102llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003103 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003104 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3105 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003106
3107 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3108
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003109 if (!Entry)
3110 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3111 llvm::ConstantArray::get(TypeStr),
3112 "__TEXT,__cstring,cstring_literals",
3113 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003114
3115 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003116}
3117
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003118// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003119llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003120 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3121
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003122 if (!Entry)
3123 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3124 llvm::ConstantArray::get(Ident->getName()),
3125 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003126 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003127
3128 return getConstantGEP(Entry, 0, 0);
3129}
3130
3131// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003132// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003133llvm::Constant *
3134 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3135 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003136 std::string TypeStr;
3137 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003138 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3139}
3140
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003141void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3142 const ObjCContainerDecl *CD,
3143 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003144 NameOut = '\01';
3145 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003146 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003147 assert (CD && "Missing container decl in GetNameForMethod");
3148 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003149 if (const ObjCCategoryImplDecl *CID =
3150 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3151 NameOut += '(';
3152 NameOut += CID->getNameAsString();
3153 NameOut+= ')';
3154 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003155 NameOut += ' ';
3156 NameOut += D->getSelector().getAsString();
3157 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003158}
3159
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003160void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003161 EmitModuleInfo();
3162
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003163 // Emit the dummy bodies for any protocols which were referenced but
3164 // never defined.
3165 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3166 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3167 if (i->second->hasInitializer())
3168 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003169
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003170 std::vector<llvm::Constant*> Values(5);
3171 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3172 Values[1] = GetClassName(i->first);
3173 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3174 Values[3] = Values[4] =
3175 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3176 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3177 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3178 Values));
3179 }
3180
3181 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003182 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003183 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003184 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003185 }
3186
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003187 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003188 llvm::GlobalValue *GV =
3189 new llvm::GlobalVariable(AT, false,
3190 llvm::GlobalValue::AppendingLinkage,
3191 llvm::ConstantArray::get(AT, Used),
3192 "llvm.used",
3193 &CGM.getModule());
3194
3195 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003196
3197 // Add assembler directives to add lazy undefined symbol references
3198 // for classes which are referenced but not defined. This is
3199 // important for correct linker interaction.
3200
3201 // FIXME: Uh, this isn't particularly portable.
3202 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003203
3204 if (!CGM.getModule().getModuleInlineAsm().empty())
3205 s << "\n";
3206
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003207 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3208 e = LazySymbols.end(); i != e; ++i) {
3209 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3210 }
3211 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3212 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003213 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003214 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3215 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003216
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003217 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003218}
3219
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003220CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003221 : CGObjCCommonMac(cgm),
3222 ObjCTypes(cgm)
3223{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003224 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003225 ObjCABI = 2;
3226}
3227
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003228/* *** */
3229
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003230ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3231: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003232{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003233 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3234 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003235
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003236 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003237 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003238 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003239 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003240 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3241
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003242 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003243 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003244 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003245
3246 // FIXME: It would be nice to unify this with the opaque type, so
3247 // that the IR comes out a bit cleaner.
3248 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3249 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003250
3251 // I'm not sure I like this. The implicit coordination is a bit
3252 // gross. We should solve this in a reasonable fashion because this
3253 // is a pretty common task (match some runtime data structure with
3254 // an LLVM data structure).
3255
3256 // FIXME: This is leaked.
3257 // FIXME: Merge with rewriter code?
3258
3259 // struct _objc_super {
3260 // id self;
3261 // Class cls;
3262 // }
3263 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3264 SourceLocation(),
3265 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003266 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3267 Ctx.getObjCIdType(), 0, false));
3268 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3269 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003270 RD->completeDefinition(Ctx);
3271
3272 SuperCTy = Ctx.getTagDeclType(RD);
3273 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3274
3275 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003276 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3277
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003278 // struct _prop_t {
3279 // char *name;
3280 // char *attributes;
3281 // }
3282 PropertyTy = llvm::StructType::get(Int8PtrTy,
3283 Int8PtrTy,
3284 NULL);
3285 CGM.getModule().addTypeName("struct._prop_t",
3286 PropertyTy);
3287
3288 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003289 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003290 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003291 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003292 // }
3293 PropertyListTy = llvm::StructType::get(IntTy,
3294 IntTy,
3295 llvm::ArrayType::get(PropertyTy, 0),
3296 NULL);
3297 CGM.getModule().addTypeName("struct._prop_list_t",
3298 PropertyListTy);
3299 // struct _prop_list_t *
3300 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3301
3302 // struct _objc_method {
3303 // SEL _cmd;
3304 // char *method_type;
3305 // char *_imp;
3306 // }
3307 MethodTy = llvm::StructType::get(SelectorPtrTy,
3308 Int8PtrTy,
3309 Int8PtrTy,
3310 NULL);
3311 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003312
3313 // struct _objc_cache *
3314 CacheTy = llvm::OpaqueType::get();
3315 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3316 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003317
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003318 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003319
3320 QualType IdType = Ctx.getObjCIdType();
3321 QualType SelType = Ctx.getObjCSelType();
3322 llvm::SmallVector<QualType,16> Params;
3323 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003324
3325 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003326 Params.push_back(IdType);
3327 Params.push_back(SelType);
3328 Params.push_back(Ctx.LongTy);
3329 Params.push_back(Ctx.BoolTy);
3330 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3331 false);
3332 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003333
3334 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3335 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003336 Params.push_back(IdType);
3337 Params.push_back(SelType);
3338 Params.push_back(Ctx.LongTy);
3339 Params.push_back(IdType);
3340 Params.push_back(Ctx.BoolTy);
3341 Params.push_back(Ctx.BoolTy);
3342 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3343 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3344
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003345 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003346
3347 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003348 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003349 Params.push_back(IdType);
3350 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3351 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3352 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003353
3354 // gc's API
3355 // id objc_read_weak (id *)
3356 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003357 Params.push_back(Ctx.getPointerType(IdType));
3358 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3359 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3360
Chris Lattner96508e12009-04-17 22:12:36 +00003361 // id objc_assign_global (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003362 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003363 Params.push_back(IdType);
3364 Params.push_back(Ctx.getPointerType(IdType));
3365
3366 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003367 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3368 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3369 GcAssignStrongCastFn =
3370 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003371
3372 // void objc_exception_throw(id)
3373 Params.clear();
3374 Params.push_back(IdType);
3375
3376 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003377 ExceptionThrowFn =
3378 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003379
3380 // synchronized APIs
Daniel Dunbar1c566672009-02-24 01:43:46 +00003381 // void objc_sync_exit (id)
3382 Params.clear();
3383 Params.push_back(IdType);
3384
3385 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Daniel Dunbar1c566672009-02-24 01:43:46 +00003386 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003387}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003388
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003389ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3390 : ObjCCommonTypesHelper(cgm)
3391{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003392 // struct _objc_method_description {
3393 // SEL name;
3394 // char *types;
3395 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003396 MethodDescriptionTy =
3397 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003398 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003399 NULL);
3400 CGM.getModule().addTypeName("struct._objc_method_description",
3401 MethodDescriptionTy);
3402
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003403 // struct _objc_method_description_list {
3404 // int count;
3405 // struct _objc_method_description[1];
3406 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003407 MethodDescriptionListTy =
3408 llvm::StructType::get(IntTy,
3409 llvm::ArrayType::get(MethodDescriptionTy, 0),
3410 NULL);
3411 CGM.getModule().addTypeName("struct._objc_method_description_list",
3412 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003413
3414 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003415 MethodDescriptionListPtrTy =
3416 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3417
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003418 // Protocol description structures
3419
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003420 // struct _objc_protocol_extension {
3421 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3422 // struct _objc_method_description_list *optional_instance_methods;
3423 // struct _objc_method_description_list *optional_class_methods;
3424 // struct _objc_property_list *instance_properties;
3425 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003426 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003427 llvm::StructType::get(IntTy,
3428 MethodDescriptionListPtrTy,
3429 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003430 PropertyListPtrTy,
3431 NULL);
3432 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3433 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003434
3435 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003436 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3437
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003438 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003439
3440 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3441 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3442
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003443 const llvm::Type *T =
3444 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3445 LongTy,
3446 llvm::ArrayType::get(ProtocolTyHolder, 0),
3447 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003448 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3449
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003450 // struct _objc_protocol {
3451 // struct _objc_protocol_extension *isa;
3452 // char *protocol_name;
3453 // struct _objc_protocol **_objc_protocol_list;
3454 // struct _objc_method_description_list *instance_methods;
3455 // struct _objc_method_description_list *class_methods;
3456 // }
3457 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003458 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003459 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3460 MethodDescriptionListPtrTy,
3461 MethodDescriptionListPtrTy,
3462 NULL);
3463 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3464
3465 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3466 CGM.getModule().addTypeName("struct._objc_protocol_list",
3467 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003468 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003469 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3470
3471 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003472 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003473 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003474
3475 // Class description structures
3476
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003477 // struct _objc_ivar {
3478 // char *ivar_name;
3479 // char *ivar_type;
3480 // int ivar_offset;
3481 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003482 IvarTy = llvm::StructType::get(Int8PtrTy,
3483 Int8PtrTy,
3484 IntTy,
3485 NULL);
3486 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3487
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003488 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003489 IvarListTy = llvm::OpaqueType::get();
3490 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3491 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3492
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003493 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003494 MethodListTy = llvm::OpaqueType::get();
3495 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3496 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3497
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003498 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003499 ClassExtensionTy =
3500 llvm::StructType::get(IntTy,
3501 Int8PtrTy,
3502 PropertyListPtrTy,
3503 NULL);
3504 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3505 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3506
3507 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3508
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003509 // struct _objc_class {
3510 // Class isa;
3511 // Class super_class;
3512 // char *name;
3513 // long version;
3514 // long info;
3515 // long instance_size;
3516 // struct _objc_ivar_list *ivars;
3517 // struct _objc_method_list *methods;
3518 // struct _objc_cache *cache;
3519 // struct _objc_protocol_list *protocols;
3520 // char *ivar_layout;
3521 // struct _objc_class_ext *ext;
3522 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003523 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3524 llvm::PointerType::getUnqual(ClassTyHolder),
3525 Int8PtrTy,
3526 LongTy,
3527 LongTy,
3528 LongTy,
3529 IvarListPtrTy,
3530 MethodListPtrTy,
3531 CachePtrTy,
3532 ProtocolListPtrTy,
3533 Int8PtrTy,
3534 ClassExtensionPtrTy,
3535 NULL);
3536 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3537
3538 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3539 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3540 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3541
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003542 // struct _objc_category {
3543 // char *category_name;
3544 // char *class_name;
3545 // struct _objc_method_list *instance_method;
3546 // struct _objc_method_list *class_method;
3547 // uint32_t size; // sizeof(struct _objc_category)
3548 // struct _objc_property_list *instance_properties;// category's @property
3549 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003550 CategoryTy = llvm::StructType::get(Int8PtrTy,
3551 Int8PtrTy,
3552 MethodListPtrTy,
3553 MethodListPtrTy,
3554 ProtocolListPtrTy,
3555 IntTy,
3556 PropertyListPtrTy,
3557 NULL);
3558 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3559
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003560 // Global metadata structures
3561
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003562 // struct _objc_symtab {
3563 // long sel_ref_cnt;
3564 // SEL *refs;
3565 // short cls_def_cnt;
3566 // short cat_def_cnt;
3567 // char *defs[cls_def_cnt + cat_def_cnt];
3568 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003569 SymtabTy = llvm::StructType::get(LongTy,
3570 SelectorPtrTy,
3571 ShortTy,
3572 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003573 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003574 NULL);
3575 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3576 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3577
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003578 // struct _objc_module {
3579 // long version;
3580 // long size; // sizeof(struct _objc_module)
3581 // char *name;
3582 // struct _objc_symtab* symtab;
3583 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003584 ModuleTy =
3585 llvm::StructType::get(LongTy,
3586 LongTy,
3587 Int8PtrTy,
3588 SymtabPtrTy,
3589 NULL);
3590 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003591
Daniel Dunbar49f66022008-09-24 03:38:44 +00003592 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003593
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003594 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003595 std::vector<const llvm::Type*> Params;
3596 Params.push_back(ObjectPtrTy);
3597 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003598 MessageSendFn =
3599 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3600 Params,
3601 true),
3602 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003603
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003604 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003605 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003606 Params.push_back(ObjectPtrTy);
3607 Params.push_back(SelectorPtrTy);
3608 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003609 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3610 Params,
3611 true),
3612 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003613
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003614 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003615 Params.clear();
3616 Params.push_back(ObjectPtrTy);
3617 Params.push_back(SelectorPtrTy);
3618 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003619 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003620 MessageSendFpretFn =
3621 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3622 Params,
3623 true),
3624 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003625
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003626 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003627 Params.clear();
3628 Params.push_back(SuperPtrTy);
3629 Params.push_back(SelectorPtrTy);
3630 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003631 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3632 Params,
3633 true),
3634 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003635
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003636 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3637 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003638 Params.clear();
3639 Params.push_back(Int8PtrTy);
3640 Params.push_back(SuperPtrTy);
3641 Params.push_back(SelectorPtrTy);
3642 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003643 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3644 Params,
3645 true),
3646 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003647
3648 // There is no objc_msgSendSuper_fpret? How can that work?
3649 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003650
Anders Carlsson124526b2008-09-09 10:10:21 +00003651 // FIXME: This is the size of the setjmp buffer and should be
3652 // target specific. 18 is what's used on 32-bit X86.
3653 uint64_t SetJmpBufferSize = 18;
3654
3655 // Exceptions
3656 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003657 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003658
3659 ExceptionDataTy =
3660 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3661 SetJmpBufferSize),
3662 StackPtrTy, NULL);
3663 CGM.getModule().addTypeName("struct._objc_exception_data",
3664 ExceptionDataTy);
3665
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003666}
3667
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003668ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003669: ObjCCommonTypesHelper(cgm)
3670{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003671 // struct _method_list_t {
3672 // uint32_t entsize; // sizeof(struct _objc_method)
3673 // uint32_t method_count;
3674 // struct _objc_method method_list[method_count];
3675 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003676 MethodListnfABITy = llvm::StructType::get(IntTy,
3677 IntTy,
3678 llvm::ArrayType::get(MethodTy, 0),
3679 NULL);
3680 CGM.getModule().addTypeName("struct.__method_list_t",
3681 MethodListnfABITy);
3682 // struct method_list_t *
3683 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003684
3685 // struct _protocol_t {
3686 // id isa; // NULL
3687 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003688 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003689 // const struct method_list_t * const instance_methods;
3690 // const struct method_list_t * const class_methods;
3691 // const struct method_list_t *optionalInstanceMethods;
3692 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003693 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003694 // const uint32_t size; // sizeof(struct _protocol_t)
3695 // const uint32_t flags; // = 0
3696 // }
3697
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003698 // Holder for struct _protocol_list_t *
3699 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3700
3701 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3702 Int8PtrTy,
3703 llvm::PointerType::getUnqual(
3704 ProtocolListTyHolder),
3705 MethodListnfABIPtrTy,
3706 MethodListnfABIPtrTy,
3707 MethodListnfABIPtrTy,
3708 MethodListnfABIPtrTy,
3709 PropertyListPtrTy,
3710 IntTy,
3711 IntTy,
3712 NULL);
3713 CGM.getModule().addTypeName("struct._protocol_t",
3714 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003715
3716 // struct _protocol_t*
3717 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003718
Fariborz Jahanianda320092009-01-29 19:24:30 +00003719 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003720 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003721 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003722 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003723 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3724 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003725 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003726 NULL);
3727 CGM.getModule().addTypeName("struct._objc_protocol_list",
3728 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003729 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3730 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003731
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003732 // struct _objc_protocol_list*
3733 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003734
3735 // struct _ivar_t {
3736 // unsigned long int *offset; // pointer to ivar offset location
3737 // char *name;
3738 // char *type;
3739 // uint32_t alignment;
3740 // uint32_t size;
3741 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003742 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3743 Int8PtrTy,
3744 Int8PtrTy,
3745 IntTy,
3746 IntTy,
3747 NULL);
3748 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3749
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003750 // struct _ivar_list_t {
3751 // uint32 entsize; // sizeof(struct _ivar_t)
3752 // uint32 count;
3753 // struct _iver_t list[count];
3754 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003755 IvarListnfABITy = llvm::StructType::get(IntTy,
3756 IntTy,
3757 llvm::ArrayType::get(
3758 IvarnfABITy, 0),
3759 NULL);
3760 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3761
3762 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003763
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003764 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003765 // uint32_t const flags;
3766 // uint32_t const instanceStart;
3767 // uint32_t const instanceSize;
3768 // uint32_t const reserved; // only when building for 64bit targets
3769 // const uint8_t * const ivarLayout;
3770 // const char *const name;
3771 // const struct _method_list_t * const baseMethods;
3772 // const struct _objc_protocol_list *const baseProtocols;
3773 // const struct _ivar_list_t *const ivars;
3774 // const uint8_t * const weakIvarLayout;
3775 // const struct _prop_list_t * const properties;
3776 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003777
3778 // FIXME. Add 'reserved' field in 64bit abi mode!
3779 ClassRonfABITy = llvm::StructType::get(IntTy,
3780 IntTy,
3781 IntTy,
3782 Int8PtrTy,
3783 Int8PtrTy,
3784 MethodListnfABIPtrTy,
3785 ProtocolListnfABIPtrTy,
3786 IvarListnfABIPtrTy,
3787 Int8PtrTy,
3788 PropertyListPtrTy,
3789 NULL);
3790 CGM.getModule().addTypeName("struct._class_ro_t",
3791 ClassRonfABITy);
3792
3793 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3794 std::vector<const llvm::Type*> Params;
3795 Params.push_back(ObjectPtrTy);
3796 Params.push_back(SelectorPtrTy);
3797 ImpnfABITy = llvm::PointerType::getUnqual(
3798 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3799
3800 // struct _class_t {
3801 // struct _class_t *isa;
3802 // struct _class_t * const superclass;
3803 // void *cache;
3804 // IMP *vtable;
3805 // struct class_ro_t *ro;
3806 // }
3807
3808 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3809 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3810 llvm::PointerType::getUnqual(ClassTyHolder),
3811 CachePtrTy,
3812 llvm::PointerType::getUnqual(ImpnfABITy),
3813 llvm::PointerType::getUnqual(
3814 ClassRonfABITy),
3815 NULL);
3816 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3817
3818 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3819 ClassnfABITy);
3820
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003821 // LLVM for struct _class_t *
3822 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3823
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003824 // struct _category_t {
3825 // const char * const name;
3826 // struct _class_t *const cls;
3827 // const struct _method_list_t * const instance_methods;
3828 // const struct _method_list_t * const class_methods;
3829 // const struct _protocol_list_t * const protocols;
3830 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003831 // }
3832 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003833 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003834 MethodListnfABIPtrTy,
3835 MethodListnfABIPtrTy,
3836 ProtocolListnfABIPtrTy,
3837 PropertyListPtrTy,
3838 NULL);
3839 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003840
3841 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003842 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3843 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003844
3845 // MessageRefTy - LLVM for:
3846 // struct _message_ref_t {
3847 // IMP messenger;
3848 // SEL name;
3849 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003850
3851 // First the clang type for struct _message_ref_t
3852 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3853 SourceLocation(),
3854 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003855 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3856 Ctx.VoidPtrTy, 0, false));
3857 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3858 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003859 RD->completeDefinition(Ctx);
3860
3861 MessageRefCTy = Ctx.getTagDeclType(RD);
3862 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3863 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003864
3865 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3866 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3867
3868 // SuperMessageRefTy - LLVM for:
3869 // struct _super_message_ref_t {
3870 // SUPER_IMP messenger;
3871 // SEL name;
3872 // };
3873 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3874 SelectorPtrTy,
3875 NULL);
3876 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3877
3878 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3879 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3880
3881 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3882 Params.clear();
3883 Params.push_back(ObjectPtrTy);
3884 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003885 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3886 Params,
3887 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003888 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003889 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003890 "objc_msgSend_fixup");
3891
3892 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3893 MessageSendFpretFixupFn =
3894 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3895 Params,
3896 true),
3897 "objc_msgSend_fpret_fixup");
3898
3899 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3900 MessageSendStretFixupFn =
3901 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3902 Params,
3903 true),
3904 "objc_msgSend_stret_fixup");
3905
3906 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3907 MessageSendIdFixupFn =
3908 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3909 Params,
3910 true),
3911 "objc_msgSendId_fixup");
3912
3913
3914 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3915 MessageSendIdStretFixupFn =
3916 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3917 Params,
3918 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003919 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003920
3921 // id objc_msgSendSuper2_fixup (struct objc_super *,
3922 // struct _super_message_ref_t*, ...)
3923 Params.clear();
3924 Params.push_back(SuperPtrTy);
3925 Params.push_back(SuperMessageRefPtrTy);
3926 MessageSendSuper2FixupFn =
3927 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3928 Params,
3929 true),
3930 "objc_msgSendSuper2_fixup");
3931
3932
3933 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3934 // struct _super_message_ref_t*, ...)
3935 MessageSendSuper2StretFixupFn =
3936 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3937 Params,
3938 true),
3939 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003940
3941 Params.clear();
Daniel Dunbare588b992009-03-01 04:46:24 +00003942
3943 // struct objc_typeinfo {
3944 // const void** vtable; // objc_ehtype_vtable + 2
3945 // const char* name; // c++ typeinfo string
3946 // Class cls;
3947 // };
3948 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3949 Int8PtrTy,
3950 ClassnfABIPtrTy,
3951 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003952 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003953 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003954}
3955
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003956llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3957 FinishNonFragileABIModule();
3958
3959 return NULL;
3960}
3961
3962void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3963 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003964
3965 // Build list of all implemented classe addresses in array
3966 // L_OBJC_LABEL_CLASS_$.
3967 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3968 // list of 'nonlazy' implementations (defined as those with a +load{}
3969 // method!!).
3970 unsigned NumClasses = DefinedClasses.size();
3971 if (NumClasses) {
3972 std::vector<llvm::Constant*> Symbols(NumClasses);
3973 for (unsigned i=0; i<NumClasses; i++)
3974 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3975 ObjCTypes.Int8PtrTy);
3976 llvm::Constant* Init =
3977 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3978 NumClasses),
3979 Symbols);
3980
3981 llvm::GlobalVariable *GV =
3982 new llvm::GlobalVariable(Init->getType(), false,
3983 llvm::GlobalValue::InternalLinkage,
3984 Init,
3985 "\01L_OBJC_LABEL_CLASS_$",
3986 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003987 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003988 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3989 UsedGlobals.push_back(GV);
3990 }
3991
3992 // Build list of all implemented category addresses in array
3993 // L_OBJC_LABEL_CATEGORY_$.
3994 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3995 // list of 'nonlazy' category implementations (defined as those with a +load{}
3996 // method!!).
3997 unsigned NumCategory = DefinedCategories.size();
3998 if (NumCategory) {
3999 std::vector<llvm::Constant*> Symbols(NumCategory);
4000 for (unsigned i=0; i<NumCategory; i++)
4001 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4002 ObjCTypes.Int8PtrTy);
4003 llvm::Constant* Init =
4004 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4005 NumCategory),
4006 Symbols);
4007
4008 llvm::GlobalVariable *GV =
4009 new llvm::GlobalVariable(Init->getType(), false,
4010 llvm::GlobalValue::InternalLinkage,
4011 Init,
4012 "\01L_OBJC_LABEL_CATEGORY_$",
4013 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004014 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004015 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4016 UsedGlobals.push_back(GV);
4017 }
4018
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004019 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4020 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4021 std::vector<llvm::Constant*> Values(2);
4022 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004023 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004024 // FIXME: Fix and continue?
4025 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4026 flags |= eImageInfo_GarbageCollected;
4027 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4028 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004029 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004030 llvm::Constant* Init = llvm::ConstantArray::get(
4031 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4032 Values);
4033 llvm::GlobalVariable *IMGV =
4034 new llvm::GlobalVariable(Init->getType(), false,
4035 llvm::GlobalValue::InternalLinkage,
4036 Init,
4037 "\01L_OBJC_IMAGE_INFO",
4038 &CGM.getModule());
4039 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4040 UsedGlobals.push_back(IMGV);
4041
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004042 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004043
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004044 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4045 e = UsedGlobals.end(); i != e; ++i) {
4046 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4047 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004048
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004049 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4050 llvm::GlobalValue *GV =
4051 new llvm::GlobalVariable(AT, false,
4052 llvm::GlobalValue::AppendingLinkage,
4053 llvm::ConstantArray::get(AT, Used),
4054 "llvm.used",
4055 &CGM.getModule());
4056
4057 GV->setSection("llvm.metadata");
4058
4059}
4060
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004061// Metadata flags
4062enum MetaDataDlags {
4063 CLS = 0x0,
4064 CLS_META = 0x1,
4065 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004066 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004067 CLS_EXCEPTION = 0x20
4068};
4069/// BuildClassRoTInitializer - generate meta-data for:
4070/// struct _class_ro_t {
4071/// uint32_t const flags;
4072/// uint32_t const instanceStart;
4073/// uint32_t const instanceSize;
4074/// uint32_t const reserved; // only when building for 64bit targets
4075/// const uint8_t * const ivarLayout;
4076/// const char *const name;
4077/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004078/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004079/// const struct _ivar_list_t *const ivars;
4080/// const uint8_t * const weakIvarLayout;
4081/// const struct _prop_list_t * const properties;
4082/// }
4083///
4084llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4085 unsigned flags,
4086 unsigned InstanceStart,
4087 unsigned InstanceSize,
4088 const ObjCImplementationDecl *ID) {
4089 std::string ClassName = ID->getNameAsString();
4090 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4091 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4092 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4093 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4094 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004095 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004096 // Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4097 // : BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004098 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004099 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004100 // const struct _method_list_t * const baseMethods;
4101 std::vector<llvm::Constant*> Methods;
4102 std::string MethodListName("\01l_OBJC_$_");
4103 if (flags & CLS_META) {
4104 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4105 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4106 e = ID->classmeth_end(); i != e; ++i) {
4107 // Class methods should always be defined.
4108 Methods.push_back(GetMethodConstant(*i));
4109 }
4110 } else {
4111 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4112 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4113 e = ID->instmeth_end(); i != e; ++i) {
4114 // Instance methods should always be defined.
4115 Methods.push_back(GetMethodConstant(*i));
4116 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004117 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4118 e = ID->propimpl_end(); i != e; ++i) {
4119 ObjCPropertyImplDecl *PID = *i;
4120
4121 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4122 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4123
4124 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4125 if (llvm::Constant *C = GetMethodConstant(MD))
4126 Methods.push_back(C);
4127 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4128 if (llvm::Constant *C = GetMethodConstant(MD))
4129 Methods.push_back(C);
4130 }
4131 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004132 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004133 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004134 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004135
4136 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4137 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4138 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4139 + OID->getNameAsString(),
4140 OID->protocol_begin(),
4141 OID->protocol_end());
4142
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004143 if (flags & CLS_META)
4144 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4145 else
4146 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004147 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004148 // Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4149 // : BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004150 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004151 if (flags & CLS_META)
4152 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4153 else
4154 Values[ 9] =
4155 EmitPropertyList(
4156 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4157 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004158 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4159 Values);
4160 llvm::GlobalVariable *CLASS_RO_GV =
4161 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4162 llvm::GlobalValue::InternalLinkage,
4163 Init,
4164 (flags & CLS_META) ?
4165 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4166 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4167 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004168 CLASS_RO_GV->setAlignment(
4169 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004170 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004171 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004172
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004173}
4174
4175/// BuildClassMetaData - This routine defines that to-level meta-data
4176/// for the given ClassName for:
4177/// struct _class_t {
4178/// struct _class_t *isa;
4179/// struct _class_t * const superclass;
4180/// void *cache;
4181/// IMP *vtable;
4182/// struct class_ro_t *ro;
4183/// }
4184///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004185llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4186 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004187 llvm::Constant *IsAGV,
4188 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004189 llvm::Constant *ClassRoGV,
4190 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004191 std::vector<llvm::Constant*> Values(5);
4192 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004193 Values[1] = SuperClassGV
4194 ? SuperClassGV
4195 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004196 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4197 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4198 Values[4] = ClassRoGV; // &CLASS_RO_GV
4199 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4200 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004201 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4202 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004203 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004204 GV->setAlignment(
4205 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004206 if (HiddenVisibility)
4207 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004208 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004209}
4210
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004211/// countInheritedIvars - count number of ivars in class and its super class(s)
4212///
4213static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4214 ASTContext &Context) {
4215 int count = 0;
4216 if (!OI)
4217 return 0;
4218 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4219 if (SuperClass)
4220 count += countInheritedIvars(SuperClass, Context);
4221 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4222 E = OI->ivar_end(); I != E; ++I)
4223 ++count;
4224 // look into properties.
4225 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4226 E = OI->prop_end(Context); I != E; ++I) {
4227 if ((*I)->getPropertyIvarDecl())
4228 ++count;
4229 }
4230 return count;
4231}
4232
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004233void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4234 uint32_t &InstanceStart,
4235 uint32_t &InstanceSize) {
Daniel Dunbar24c89912009-04-21 21:41:56 +00004236 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004237 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4238
Daniel Dunbar6ec07162009-04-20 07:18:49 +00004239 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4240 CGM.getContext());
4241 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
4242 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4243 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4244 while (countSuperClassIvars-- > 0) {
4245 lastField = firstField;
4246 ++firstField;
4247 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004248
4249 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4250 ifield = firstField; ifield != e; ++ifield)
4251 lastField = ifield;
4252
4253 InstanceStart = InstanceSize = 0;
4254 if (lastField != RD->field_end(CGM.getContext())) {
4255 FieldDecl *Field = *lastField;
4256 const llvm::Type *FieldTy =
4257 CGM.getTypes().ConvertTypeForMem(Field->getType());
4258 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4259 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4260 if (firstField == RD->field_end(CGM.getContext()))
4261 InstanceStart = InstanceSize;
4262 else {
4263 Field = *firstField;
4264 InstanceStart = GetIvarBaseOffset(Layout, Field);
4265 }
4266 }
4267}
4268
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004269void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4270 std::string ClassName = ID->getNameAsString();
4271 if (!ObjCEmptyCacheVar) {
4272 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004273 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004274 false,
4275 llvm::GlobalValue::ExternalLinkage,
4276 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004277 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004278 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004279
4280 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004281 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004282 false,
4283 llvm::GlobalValue::ExternalLinkage,
4284 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004285 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004286 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004287 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004288 assert(ID->getClassInterface() &&
4289 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004290 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004291 uint32_t InstanceStart =
4292 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4293 uint32_t InstanceSize = InstanceStart;
4294 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004295 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4296 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004297
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004298 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004299
Daniel Dunbar04d40782009-04-14 06:00:08 +00004300 bool classIsHidden =
4301 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004302 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004303 flags |= OBJC2_CLS_HIDDEN;
4304 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004305 // class is root
4306 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004307 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004308 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004309 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004310 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004311 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4312 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4313 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004314 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004315 // work on super class metadata symbol.
4316 std::string SuperClassName =
4317 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004318 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004319 }
4320 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4321 InstanceStart,
4322 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004323 std::string TClassName = ObjCMetaClassName + ClassName;
4324 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004325 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4326 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004327
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004328 // Metadata for the class
4329 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004330 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004331 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004332
4333 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4334 flags |= CLS_EXCEPTION;
4335
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004336 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004337 flags |= CLS_ROOT;
4338 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004339 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004340 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004341 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004342 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004343 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004344 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004345 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004346 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004347 InstanceStart,
4348 InstanceSize,
4349 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004350
4351 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004352 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004353 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4354 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004355 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004356
4357 // Force the definition of the EHType if necessary.
4358 if (flags & CLS_EXCEPTION)
4359 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004360}
4361
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004362/// GenerateProtocolRef - This routine is called to generate code for
4363/// a protocol reference expression; as in:
4364/// @code
4365/// @protocol(Proto1);
4366/// @endcode
4367/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4368/// which will hold address of the protocol meta-data.
4369///
4370llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4371 const ObjCProtocolDecl *PD) {
4372
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004373 // This routine is called for @protocol only. So, we must build definition
4374 // of protocol's meta-data (not a reference to it!)
4375 //
4376 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004377 ObjCTypes.ExternalProtocolPtrTy);
4378
4379 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4380 ProtocolName += PD->getNameAsCString();
4381
4382 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4383 if (PTGV)
4384 return Builder.CreateLoad(PTGV, false, "tmp");
4385 PTGV = new llvm::GlobalVariable(
4386 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004387 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004388 Init,
4389 ProtocolName,
4390 &CGM.getModule());
4391 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4392 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4393 UsedGlobals.push_back(PTGV);
4394 return Builder.CreateLoad(PTGV, false, "tmp");
4395}
4396
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004397/// GenerateCategory - Build metadata for a category implementation.
4398/// struct _category_t {
4399/// const char * const name;
4400/// struct _class_t *const cls;
4401/// const struct _method_list_t * const instance_methods;
4402/// const struct _method_list_t * const class_methods;
4403/// const struct _protocol_list_t * const protocols;
4404/// const struct _prop_list_t * const properties;
4405/// }
4406///
4407void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4408{
4409 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004410 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4411 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004412 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004413 std::string ExtClassName(getClassSymbolPrefix() +
4414 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004415
4416 std::vector<llvm::Constant*> Values(6);
4417 Values[0] = GetClassName(OCD->getIdentifier());
4418 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004419 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004420 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004421 std::vector<llvm::Constant*> Methods;
4422 std::string MethodListName(Prefix);
4423 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4424 "_$_" + OCD->getNameAsString();
4425
4426 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4427 e = OCD->instmeth_end(); i != e; ++i) {
4428 // Instance methods should always be defined.
4429 Methods.push_back(GetMethodConstant(*i));
4430 }
4431
4432 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004433 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004434 Methods);
4435
4436 MethodListName = Prefix;
4437 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4438 OCD->getNameAsString();
4439 Methods.clear();
4440 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4441 e = OCD->classmeth_end(); i != e; ++i) {
4442 // Class methods should always be defined.
4443 Methods.push_back(GetMethodConstant(*i));
4444 }
4445
4446 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004447 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004448 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004449 const ObjCCategoryDecl *Category =
4450 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004451 if (Category) {
4452 std::string ExtName(Interface->getNameAsString() + "_$_" +
4453 OCD->getNameAsString());
4454 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4455 + Interface->getNameAsString() + "_$_"
4456 + Category->getNameAsString(),
4457 Category->protocol_begin(),
4458 Category->protocol_end());
4459 Values[5] =
4460 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4461 OCD, Category, ObjCTypes);
4462 }
4463 else {
4464 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4465 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4466 }
4467
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004468 llvm::Constant *Init =
4469 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4470 Values);
4471 llvm::GlobalVariable *GCATV
4472 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4473 false,
4474 llvm::GlobalValue::InternalLinkage,
4475 Init,
4476 ExtCatName,
4477 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004478 GCATV->setAlignment(
4479 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004480 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004481 UsedGlobals.push_back(GCATV);
4482 DefinedCategories.push_back(GCATV);
4483}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004484
4485/// GetMethodConstant - Return a struct objc_method constant for the
4486/// given method if it has been defined. The result is null if the
4487/// method has not been defined. The return value has type MethodPtrTy.
4488llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4489 const ObjCMethodDecl *MD) {
4490 // FIXME: Use DenseMap::lookup
4491 llvm::Function *Fn = MethodDefinitions[MD];
4492 if (!Fn)
4493 return 0;
4494
4495 std::vector<llvm::Constant*> Method(3);
4496 Method[0] =
4497 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4498 ObjCTypes.SelectorPtrTy);
4499 Method[1] = GetMethodVarType(MD);
4500 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4501 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4502}
4503
4504/// EmitMethodList - Build meta-data for method declarations
4505/// struct _method_list_t {
4506/// uint32_t entsize; // sizeof(struct _objc_method)
4507/// uint32_t method_count;
4508/// struct _objc_method method_list[method_count];
4509/// }
4510///
4511llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4512 const std::string &Name,
4513 const char *Section,
4514 const ConstantVector &Methods) {
4515 // Return null for empty list.
4516 if (Methods.empty())
4517 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4518
4519 std::vector<llvm::Constant*> Values(3);
4520 // sizeof(struct _objc_method)
4521 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4522 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4523 // method_count
4524 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4525 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4526 Methods.size());
4527 Values[2] = llvm::ConstantArray::get(AT, Methods);
4528 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4529
4530 llvm::GlobalVariable *GV =
4531 new llvm::GlobalVariable(Init->getType(), false,
4532 llvm::GlobalValue::InternalLinkage,
4533 Init,
4534 Name,
4535 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004536 GV->setAlignment(
4537 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004538 GV->setSection(Section);
4539 UsedGlobals.push_back(GV);
4540 return llvm::ConstantExpr::getBitCast(GV,
4541 ObjCTypes.MethodListnfABIPtrTy);
4542}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004543
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004544/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4545/// the given ivar.
4546///
4547llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004548 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004549 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004550 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004551 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4552 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004553 llvm::GlobalVariable *IvarOffsetGV =
4554 CGM.getModule().getGlobalVariable(Name);
4555 if (!IvarOffsetGV)
4556 IvarOffsetGV =
4557 new llvm::GlobalVariable(ObjCTypes.LongTy,
4558 false,
4559 llvm::GlobalValue::ExternalLinkage,
4560 0,
4561 Name,
4562 &CGM.getModule());
4563 return IvarOffsetGV;
4564}
4565
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004566llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004567 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004568 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004569 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004570 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4571 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4572 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004573 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004574 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004575
4576 // FIXME: This matches gcc, but shouldn't the visibility be set on
4577 // the use as well (i.e., in ObjCIvarOffsetVariable).
4578 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4579 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4580 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004581 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004582 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004583 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004584 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004585 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004586}
4587
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004588/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004589/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004590/// IvarListnfABIPtrTy.
4591/// struct _ivar_t {
4592/// unsigned long int *offset; // pointer to ivar offset location
4593/// char *name;
4594/// char *type;
4595/// uint32_t alignment;
4596/// uint32_t size;
4597/// }
4598/// struct _ivar_list_t {
4599/// uint32 entsize; // sizeof(struct _ivar_t)
4600/// uint32 count;
4601/// struct _iver_t list[count];
4602/// }
4603///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004604
4605void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4606 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4607 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4608 E = OID->ivar_end(); I != E; ++I) {
4609 // Ignore unnamed bit-fields.
4610 if (!(*I)->getDeclName())
4611 continue;
4612
4613 Res.push_back(*I);
4614 }
4615
4616 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4617 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4618 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4619 Res.push_back(IV);
4620}
4621
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004622llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4623 const ObjCImplementationDecl *ID) {
4624
4625 std::vector<llvm::Constant*> Ivars, Ivar(5);
4626
4627 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4628 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4629
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004630 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004631 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004632
Daniel Dunbar91636d62009-04-20 00:33:43 +00004633 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004634 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004635 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004636
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004637 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4638 ObjCIvarDecl *IVD = OIvars[i];
4639 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004640 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004641 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004642 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004643 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004644 const llvm::Type *FieldTy =
4645 CGM.getTypes().ConvertTypeForMem(Field->getType());
4646 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4647 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4648 Field->getType().getTypePtr()) >> 3;
4649 Align = llvm::Log2_32(Align);
4650 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004651 // NOTE. Size of a bitfield does not match gcc's, because of the
4652 // way bitfields are treated special in each. But I am told that
4653 // 'size' for bitfield ivars is ignored by the runtime so it does
4654 // not matter. If it matters, there is enough info to get the
4655 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004656 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4657 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4658 }
4659 // Return null for empty list.
4660 if (Ivars.empty())
4661 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4662 std::vector<llvm::Constant*> Values(3);
4663 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4664 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4665 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4666 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4667 Ivars.size());
4668 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4669 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4670 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4671 llvm::GlobalVariable *GV =
4672 new llvm::GlobalVariable(Init->getType(), false,
4673 llvm::GlobalValue::InternalLinkage,
4674 Init,
4675 Prefix + OID->getNameAsString(),
4676 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004677 GV->setAlignment(
4678 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004679 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004680
4681 UsedGlobals.push_back(GV);
4682 return llvm::ConstantExpr::getBitCast(GV,
4683 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004684}
4685
4686llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4687 const ObjCProtocolDecl *PD) {
4688 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4689
4690 if (!Entry) {
4691 // We use the initializer as a marker of whether this is a forward
4692 // reference or not. At module finalization we add the empty
4693 // contents for protocols which were referenced but never defined.
4694 Entry =
4695 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4696 llvm::GlobalValue::ExternalLinkage,
4697 0,
4698 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4699 &CGM.getModule());
4700 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4701 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004702 }
4703
4704 return Entry;
4705}
4706
4707/// GetOrEmitProtocol - Generate the protocol meta-data:
4708/// @code
4709/// struct _protocol_t {
4710/// id isa; // NULL
4711/// const char * const protocol_name;
4712/// const struct _protocol_list_t * protocol_list; // super protocols
4713/// const struct method_list_t * const instance_methods;
4714/// const struct method_list_t * const class_methods;
4715/// const struct method_list_t *optionalInstanceMethods;
4716/// const struct method_list_t *optionalClassMethods;
4717/// const struct _prop_list_t * properties;
4718/// const uint32_t size; // sizeof(struct _protocol_t)
4719/// const uint32_t flags; // = 0
4720/// }
4721/// @endcode
4722///
4723
4724llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4725 const ObjCProtocolDecl *PD) {
4726 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4727
4728 // Early exit if a defining object has already been generated.
4729 if (Entry && Entry->hasInitializer())
4730 return Entry;
4731
4732 const char *ProtocolName = PD->getNameAsCString();
4733
4734 // Construct method lists.
4735 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4736 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004737 for (ObjCProtocolDecl::instmeth_iterator
4738 i = PD->instmeth_begin(CGM.getContext()),
4739 e = PD->instmeth_end(CGM.getContext());
4740 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004741 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004742 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4744 OptInstanceMethods.push_back(C);
4745 } else {
4746 InstanceMethods.push_back(C);
4747 }
4748 }
4749
Douglas Gregor6ab35242009-04-09 21:40:53 +00004750 for (ObjCProtocolDecl::classmeth_iterator
4751 i = PD->classmeth_begin(CGM.getContext()),
4752 e = PD->classmeth_end(CGM.getContext());
4753 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004754 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004755 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004756 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4757 OptClassMethods.push_back(C);
4758 } else {
4759 ClassMethods.push_back(C);
4760 }
4761 }
4762
4763 std::vector<llvm::Constant*> Values(10);
4764 // isa is NULL
4765 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4766 Values[1] = GetClassName(PD->getIdentifier());
4767 Values[2] = EmitProtocolList(
4768 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4769 PD->protocol_begin(),
4770 PD->protocol_end());
4771
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004772 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004773 + PD->getNameAsString(),
4774 "__DATA, __objc_const",
4775 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004776 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004777 + PD->getNameAsString(),
4778 "__DATA, __objc_const",
4779 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004780 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004781 + PD->getNameAsString(),
4782 "__DATA, __objc_const",
4783 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004784 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004785 + PD->getNameAsString(),
4786 "__DATA, __objc_const",
4787 OptClassMethods);
4788 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4789 0, PD, ObjCTypes);
4790 uint32_t Size =
4791 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4792 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4793 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4794 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4795 Values);
4796
4797 if (Entry) {
4798 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004799 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004800 Entry->setInitializer(Init);
4801 } else {
4802 Entry =
4803 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004804 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004805 Init,
4806 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4807 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004808 Entry->setAlignment(
4809 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004811 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004812 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4813
4814 // Use this protocol meta-data to build protocol list table in section
4815 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004816 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004817 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004818 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004819 Entry,
4820 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4821 +ProtocolName,
4822 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004823 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004824 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004825 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004826 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4827 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004828 return Entry;
4829}
4830
4831/// EmitProtocolList - Generate protocol list meta-data:
4832/// @code
4833/// struct _protocol_list_t {
4834/// long protocol_count; // Note, this is 32/64 bit
4835/// struct _protocol_t[protocol_count];
4836/// }
4837/// @endcode
4838///
4839llvm::Constant *
4840CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4841 ObjCProtocolDecl::protocol_iterator begin,
4842 ObjCProtocolDecl::protocol_iterator end) {
4843 std::vector<llvm::Constant*> ProtocolRefs;
4844
Fariborz Jahanianda320092009-01-29 19:24:30 +00004845 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004846 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004847 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4848
Daniel Dunbar948e2582009-02-15 07:36:20 +00004849 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004850 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4851 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004852 return llvm::ConstantExpr::getBitCast(GV,
4853 ObjCTypes.ProtocolListnfABIPtrTy);
4854
4855 for (; begin != end; ++begin)
4856 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4857
Fariborz Jahanianda320092009-01-29 19:24:30 +00004858 // This list is null terminated.
4859 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004860 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004861
4862 std::vector<llvm::Constant*> Values(2);
4863 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4864 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004865 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004866 ProtocolRefs.size()),
4867 ProtocolRefs);
4868
4869 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4870 GV = new llvm::GlobalVariable(Init->getType(), false,
4871 llvm::GlobalValue::InternalLinkage,
4872 Init,
4873 Name,
4874 &CGM.getModule());
4875 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004876 GV->setAlignment(
4877 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004878 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004879 return llvm::ConstantExpr::getBitCast(GV,
4880 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004881}
4882
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004883/// GetMethodDescriptionConstant - This routine build following meta-data:
4884/// struct _objc_method {
4885/// SEL _cmd;
4886/// char *method_type;
4887/// char *_imp;
4888/// }
4889
4890llvm::Constant *
4891CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4892 std::vector<llvm::Constant*> Desc(3);
4893 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4894 ObjCTypes.SelectorPtrTy);
4895 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004896 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004897 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4898 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4899}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004900
4901/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4902/// This code gen. amounts to generating code for:
4903/// @code
4904/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4905/// @encode
4906///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004907LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004908 CodeGen::CodeGenFunction &CGF,
4909 QualType ObjectTy,
4910 llvm::Value *BaseValue,
4911 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004912 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004913 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4914 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004915 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004916
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004917 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004918 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004919 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4920 // (char*)BaseValue + Offset_symbol
4921 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4922 // (type *)((char*)BaseValue + Offset_symbol)
4923 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004924 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004925 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4926 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004927
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004928 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004929 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004930 CodeGenTypes::BitFieldInfo bitFieldInfo =
4931 CGM.getTypes().getBitFieldInfo(Field);
4932 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004933 FieldTy->isSignedIntegerType(),
4934 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004935 }
4936
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004937 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004938 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4939 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004940 LValue::SetObjCIvar(LV, true);
4941 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004942}
4943
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004944llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4945 CodeGen::CodeGenFunction &CGF,
4946 ObjCInterfaceDecl *Interface,
4947 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004948 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4949 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004950}
4951
Fariborz Jahanian46551122009-02-04 00:22:57 +00004952CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4953 CodeGen::CodeGenFunction &CGF,
4954 QualType ResultType,
4955 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004956 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004957 QualType Arg0Ty,
4958 bool IsSuper,
4959 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004960 // FIXME. Even though IsSuper is passes. This function doese not
4961 // handle calls to 'super' receivers.
4962 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004963 llvm::Value *Arg0 = Receiver;
4964 if (!IsSuper)
4965 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004966
4967 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004968 // FIXME. This is too much work to get the ABI-specific result type
4969 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004970 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4971 llvm::SmallVector<QualType, 16>());
4972 llvm::Constant *Fn;
4973 std::string Name("\01l_");
4974 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004975#if 0
4976 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004977 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4978 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4979 // FIXME. Is there a better way of getting these names.
4980 // They are available in RuntimeFunctions vector pair.
4981 Name += "objc_msgSendId_stret_fixup";
4982 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004983 else
4984#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004985 if (IsSuper) {
4986 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4987 Name += "objc_msgSendSuper2_stret_fixup";
4988 }
4989 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004990 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004991 Fn = ObjCTypes.MessageSendStretFixupFn;
4992 Name += "objc_msgSend_stret_fixup";
4993 }
4994 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004995 else if (ResultType->isFloatingType() &&
4996 // Selection of frret API only happens in 32bit nonfragile ABI.
4997 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004998 Fn = ObjCTypes.MessageSendFpretFixupFn;
4999 Name += "objc_msgSend_fpret_fixup";
5000 }
5001 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005002#if 0
5003// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005004 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
5005 Fn = ObjCTypes.MessageSendIdFixupFn;
5006 Name += "objc_msgSendId_fixup";
5007 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005008 else
5009#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005010 if (IsSuper) {
5011 Fn = ObjCTypes.MessageSendSuper2FixupFn;
5012 Name += "objc_msgSendSuper2_fixup";
5013 }
5014 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005015 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016 Fn = ObjCTypes.MessageSendFixupFn;
5017 Name += "objc_msgSend_fixup";
5018 }
5019 }
5020 Name += '_';
5021 std::string SelName(Sel.getAsString());
5022 // Replace all ':' in selector name with '_' ouch!
5023 for(unsigned i = 0; i < SelName.size(); i++)
5024 if (SelName[i] == ':')
5025 SelName[i] = '_';
5026 Name += SelName;
5027 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5028 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005029 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005030 std::vector<llvm::Constant*> Values(2);
5031 Values[0] = Fn;
5032 Values[1] = GetMethodVarName(Sel);
5033 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5034 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005035 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005036 Init,
5037 Name,
5038 &CGM.getModule());
5039 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005040 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005041 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005042 }
5043 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005044
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005045 CallArgList ActualArgs;
5046 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5047 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5048 ObjCTypes.MessageRefCPtrTy));
5049 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005050 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5051 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5052 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005053 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005054 Callee = CGF.Builder.CreateBitCast(Callee,
5055 llvm::PointerType::getUnqual(FTy));
5056 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005057}
5058
5059/// Generate code for a message send expression in the nonfragile abi.
5060CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5061 CodeGen::CodeGenFunction &CGF,
5062 QualType ResultType,
5063 Selector Sel,
5064 llvm::Value *Receiver,
5065 bool IsClassMessage,
5066 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005067 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005068 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005069 false, CallArgs);
5070}
5071
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005072llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005073CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005074 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5075
Daniel Dunbardfff2302009-03-02 05:18:14 +00005076 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005077 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5078 llvm::GlobalValue::ExternalLinkage,
5079 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005080 }
5081
5082 return GV;
5083}
5084
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005085llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005086 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005087 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5088
5089 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005090 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005091 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005092 Entry =
5093 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5094 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005095 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005096 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005097 &CGM.getModule());
5098 Entry->setAlignment(
5099 CGM.getTargetData().getPrefTypeAlignment(
5100 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005101 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5102 UsedGlobals.push_back(Entry);
5103 }
5104
5105 return Builder.CreateLoad(Entry, false, "tmp");
5106}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005107
Daniel Dunbar11394522009-04-18 08:51:00 +00005108llvm::Value *
5109CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5110 const ObjCInterfaceDecl *ID) {
5111 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5112
5113 if (!Entry) {
5114 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5115 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5116 Entry =
5117 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5118 llvm::GlobalValue::InternalLinkage,
5119 ClassGV,
5120 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5121 &CGM.getModule());
5122 Entry->setAlignment(
5123 CGM.getTargetData().getPrefTypeAlignment(
5124 ObjCTypes.ClassnfABIPtrTy));
5125 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005126 UsedGlobals.push_back(Entry);
5127 }
5128
5129 return Builder.CreateLoad(Entry, false, "tmp");
5130}
5131
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005132/// EmitMetaClassRef - Return a Value * of the address of _class_t
5133/// meta-data
5134///
5135llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5136 const ObjCInterfaceDecl *ID) {
5137 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5138 if (Entry)
5139 return Builder.CreateLoad(Entry, false, "tmp");
5140
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005141 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005142 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005143 Entry =
5144 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5145 llvm::GlobalValue::InternalLinkage,
5146 MetaClassGV,
5147 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5148 &CGM.getModule());
5149 Entry->setAlignment(
5150 CGM.getTargetData().getPrefTypeAlignment(
5151 ObjCTypes.ClassnfABIPtrTy));
5152
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005153 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005154 UsedGlobals.push_back(Entry);
5155
5156 return Builder.CreateLoad(Entry, false, "tmp");
5157}
5158
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005159/// GetClass - Return a reference to the class for the given interface
5160/// decl.
5161llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5162 const ObjCInterfaceDecl *ID) {
5163 return EmitClassRef(Builder, ID);
5164}
5165
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005166/// Generates a message send where the super is the receiver. This is
5167/// a message send to self with special delivery semantics indicating
5168/// which class's method should be called.
5169CodeGen::RValue
5170CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5171 QualType ResultType,
5172 Selector Sel,
5173 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005174 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005175 llvm::Value *Receiver,
5176 bool IsClassMessage,
5177 const CodeGen::CallArgList &CallArgs) {
5178 // ...
5179 // Create and init a super structure; this is a (receiver, class)
5180 // pair we will pass to objc_msgSendSuper.
5181 llvm::Value *ObjCSuper =
5182 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5183
5184 llvm::Value *ReceiverAsObject =
5185 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5186 CGF.Builder.CreateStore(ReceiverAsObject,
5187 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5188
5189 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005190 llvm::Value *Target;
5191 if (IsClassMessage) {
5192 if (isCategoryImpl) {
5193 // Message sent to "super' in a class method defined in
5194 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005195 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005196 Target = CGF.Builder.CreateStructGEP(Target, 0);
5197 Target = CGF.Builder.CreateLoad(Target);
5198 }
5199 else
5200 Target = EmitMetaClassRef(CGF.Builder, Class);
5201 }
5202 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005203 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005204
5205 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5206 // and ObjCTypes types.
5207 const llvm::Type *ClassTy =
5208 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5209 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5210 CGF.Builder.CreateStore(Target,
5211 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5212
5213 return EmitMessageSend(CGF, ResultType, Sel,
5214 ObjCSuper, ObjCTypes.SuperPtrCTy,
5215 true, CallArgs);
5216}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005217
5218llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5219 Selector Sel) {
5220 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5221
5222 if (!Entry) {
5223 llvm::Constant *Casted =
5224 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5225 ObjCTypes.SelectorPtrTy);
5226 Entry =
5227 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5228 llvm::GlobalValue::InternalLinkage,
5229 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5230 &CGM.getModule());
5231 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5232 UsedGlobals.push_back(Entry);
5233 }
5234
5235 return Builder.CreateLoad(Entry, false, "tmp");
5236}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005237/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5238/// objc_assign_ivar (id src, id *dst)
5239///
5240void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5241 llvm::Value *src, llvm::Value *dst)
5242{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005243 const llvm::Type * SrcTy = src->getType();
5244 if (!isa<llvm::PointerType>(SrcTy)) {
5245 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5246 assert(Size <= 8 && "does not support size > 8");
5247 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5248 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005249 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5250 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005251 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5252 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5253 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5254 src, dst, "assignivar");
5255 return;
5256}
5257
5258/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5259/// objc_assign_strongCast (id src, id *dst)
5260///
5261void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5262 CodeGen::CodeGenFunction &CGF,
5263 llvm::Value *src, llvm::Value *dst)
5264{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005265 const llvm::Type * SrcTy = src->getType();
5266 if (!isa<llvm::PointerType>(SrcTy)) {
5267 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5268 assert(Size <= 8 && "does not support size > 8");
5269 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5270 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005271 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5272 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005273 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5274 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5275 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5276 src, dst, "weakassign");
5277 return;
5278}
5279
5280/// EmitObjCWeakRead - Code gen for loading value of a __weak
5281/// object: objc_read_weak (id *src)
5282///
5283llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5284 CodeGen::CodeGenFunction &CGF,
5285 llvm::Value *AddrWeakObj)
5286{
Eli Friedman8339b352009-03-07 03:57:15 +00005287 const llvm::Type* DestTy =
5288 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005289 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5290 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5291 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005292 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005293 return read_weak;
5294}
5295
5296/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5297/// objc_assign_weak (id src, id *dst)
5298///
5299void CGObjCNonFragileABIMac::EmitObjCWeakAssign(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);
Chris Lattner96508e12009-04-17 22:12:36 +00005312 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005313 src, dst, "weakassign");
5314 return;
5315}
5316
5317/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5318/// objc_assign_global (id src, id *dst)
5319///
5320void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5321 llvm::Value *src, llvm::Value *dst)
5322{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005323 const llvm::Type * SrcTy = src->getType();
5324 if (!isa<llvm::PointerType>(SrcTy)) {
5325 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5326 assert(Size <= 8 && "does not support size > 8");
5327 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5328 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005329 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5330 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005331 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5332 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5333 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5334 src, dst, "globalassign");
5335 return;
5336}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005337
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005338void
5339CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5340 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005341 bool isTry = isa<ObjCAtTryStmt>(S);
5342 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5343 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005344 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005345 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005346 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005347 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5348
5349 // For @synchronized, call objc_sync_enter(sync.expr). The
5350 // evaluation of the expression must occur before we enter the
5351 // @synchronized. We can safely avoid a temp here because jumps into
5352 // @synchronized are illegal & this will dominate uses.
5353 llvm::Value *SyncArg = 0;
5354 if (!isTry) {
5355 SyncArg =
5356 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5357 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005358 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005359 }
5360
5361 // Push an EH context entry, used for handling rethrows and jumps
5362 // through finally.
5363 CGF.PushCleanupBlock(FinallyBlock);
5364
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005365 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005366
5367 CGF.EmitBlock(TryBlock);
5368 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5369 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5370 CGF.EmitBranchThroughCleanup(FinallyEnd);
5371
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005372 // Emit the exception handler.
5373
5374 CGF.EmitBlock(TryHandler);
5375
5376 llvm::Value *llvm_eh_exception =
5377 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5378 llvm::Value *llvm_eh_selector_i64 =
5379 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5380 llvm::Value *llvm_eh_typeid_for_i64 =
5381 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5382 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5383 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5384
5385 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5386 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005387 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005388
5389 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005390 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005391 bool HasCatchAll = false;
5392 if (isTry) {
5393 if (const ObjCAtCatchStmt* CatchStmt =
5394 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5395 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005396 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005397 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005398
5399 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005400 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005401 // Use i8* null here to signal this is a catch all, not a cleanup.
5402 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5403 SelectorArgs.push_back(Null);
5404 HasCatchAll = true;
5405 break;
5406 }
5407
Daniel Dunbarede8de92009-03-06 00:01:21 +00005408 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5409 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005410 llvm::Value *IDEHType =
5411 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5412 if (!IDEHType)
5413 IDEHType =
5414 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5415 llvm::GlobalValue::ExternalLinkage,
5416 0, "OBJC_EHTYPE_id", &CGM.getModule());
5417 SelectorArgs.push_back(IDEHType);
5418 HasCatchAll = true;
5419 break;
5420 }
5421
5422 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005423 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005424 assert(PT && "Invalid @catch type.");
5425 const ObjCInterfaceType *IT =
5426 PT->getPointeeType()->getAsObjCInterfaceType();
5427 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005428 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005429 SelectorArgs.push_back(EHType);
5430 }
5431 }
5432 }
5433
5434 // We use a cleanup unless there was already a catch all.
5435 if (!HasCatchAll) {
5436 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005437 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005438 }
5439
5440 llvm::Value *Selector =
5441 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5442 SelectorArgs.begin(), SelectorArgs.end(),
5443 "selector");
5444 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005445 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005446 const Stmt *CatchBody = Handlers[i].second;
5447
5448 llvm::BasicBlock *Next = 0;
5449
5450 // The last handler always matches.
5451 if (i + 1 != e) {
5452 assert(CatchParam && "Only last handler can be a catch all.");
5453
5454 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5455 Next = CGF.createBasicBlock("catch.next");
5456 llvm::Value *Id =
5457 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5458 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5459 ObjCTypes.Int8PtrTy));
5460 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5461 Match, Next);
5462
5463 CGF.EmitBlock(Match);
5464 }
5465
5466 if (CatchBody) {
5467 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5468 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5469
5470 // Cleanups must call objc_end_catch.
5471 //
5472 // FIXME: It seems incorrect for objc_begin_catch to be inside
5473 // this context, but this matches gcc.
5474 CGF.PushCleanupBlock(MatchEnd);
5475 CGF.setInvokeDest(MatchHandler);
5476
5477 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005478 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005479
5480 // Bind the catch parameter if it exists.
5481 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005482 ExcObject =
5483 CGF.Builder.CreateBitCast(ExcObject,
5484 CGF.ConvertType(CatchParam->getType()));
5485 // CatchParam is a ParmVarDecl because of the grammar
5486 // construction used to handle this, but for codegen purposes
5487 // we treat this as a local decl.
5488 CGF.EmitLocalBlockVarDecl(*CatchParam);
5489 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005490 }
5491
5492 CGF.ObjCEHValueStack.push_back(ExcObject);
5493 CGF.EmitStmt(CatchBody);
5494 CGF.ObjCEHValueStack.pop_back();
5495
5496 CGF.EmitBranchThroughCleanup(FinallyEnd);
5497
5498 CGF.EmitBlock(MatchHandler);
5499
5500 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5501 // We are required to emit this call to satisfy LLVM, even
5502 // though we don't use the result.
5503 llvm::SmallVector<llvm::Value*, 8> Args;
5504 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005505 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005506 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5507 0));
5508 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5509 CGF.Builder.CreateStore(Exc, RethrowPtr);
5510 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5511
5512 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5513
5514 CGF.EmitBlock(MatchEnd);
5515
5516 // Unfortunately, we also have to generate another EH frame here
5517 // in case this throws.
5518 llvm::BasicBlock *MatchEndHandler =
5519 CGF.createBasicBlock("match.end.handler");
5520 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005521 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005522 Cont, MatchEndHandler,
5523 Args.begin(), Args.begin());
5524
5525 CGF.EmitBlock(Cont);
5526 if (Info.SwitchBlock)
5527 CGF.EmitBlock(Info.SwitchBlock);
5528 if (Info.EndBlock)
5529 CGF.EmitBlock(Info.EndBlock);
5530
5531 CGF.EmitBlock(MatchEndHandler);
5532 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5533 // We are required to emit this call to satisfy LLVM, even
5534 // though we don't use the result.
5535 Args.clear();
5536 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005537 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005538 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5539 0));
5540 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5541 CGF.Builder.CreateStore(Exc, RethrowPtr);
5542 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5543
5544 if (Next)
5545 CGF.EmitBlock(Next);
5546 } else {
5547 assert(!Next && "catchup should be last handler.");
5548
5549 CGF.Builder.CreateStore(Exc, RethrowPtr);
5550 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5551 }
5552 }
5553
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005554 // Pop the cleanup entry, the @finally is outside this cleanup
5555 // scope.
5556 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5557 CGF.setInvokeDest(PrevLandingPad);
5558
5559 CGF.EmitBlock(FinallyBlock);
5560
5561 if (isTry) {
5562 if (const ObjCAtFinallyStmt* FinallyStmt =
5563 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5564 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5565 } else {
5566 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5567 // @synchronized.
5568 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005569 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005570
5571 if (Info.SwitchBlock)
5572 CGF.EmitBlock(Info.SwitchBlock);
5573 if (Info.EndBlock)
5574 CGF.EmitBlock(Info.EndBlock);
5575
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005576 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005577 CGF.EmitBranch(FinallyEnd);
5578
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005579 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005580 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005581 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005582 CGF.Builder.CreateUnreachable();
5583
5584 CGF.EmitBlock(FinallyEnd);
5585}
5586
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005587/// EmitThrowStmt - Generate code for a throw statement.
5588void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5589 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005590 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005591 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005592 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005593 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005594 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5595 "Unexpected rethrow outside @catch block.");
5596 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005597 }
5598
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005599 llvm::Value *ExceptionAsObject =
5600 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5601 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5602 if (InvokeDest) {
5603 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5604 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5605 Cont, InvokeDest,
5606 &ExceptionAsObject, &ExceptionAsObject + 1);
5607 CGF.EmitBlock(Cont);
5608 } else
5609 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5610 CGF.Builder.CreateUnreachable();
5611
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005612 // Clear the insertion point to indicate we are in unreachable code.
5613 CGF.Builder.ClearInsertionPoint();
5614}
Daniel Dunbare588b992009-03-01 04:46:24 +00005615
5616llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005617CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5618 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005619 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005620
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005621 // If we don't need a definition, return the entry if found or check
5622 // if we use an external reference.
5623 if (!ForDefinition) {
5624 if (Entry)
5625 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005626
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005627 // If this type (or a super class) has the __objc_exception__
5628 // attribute, emit an external reference.
5629 if (hasObjCExceptionAttribute(ID))
5630 return Entry =
5631 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5632 llvm::GlobalValue::ExternalLinkage,
5633 0,
5634 (std::string("OBJC_EHTYPE_$_") +
5635 ID->getIdentifier()->getName()),
5636 &CGM.getModule());
5637 }
5638
5639 // Otherwise we need to either make a new entry or fill in the
5640 // initializer.
5641 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005642 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005643 std::string VTableName = "objc_ehtype_vtable";
5644 llvm::GlobalVariable *VTableGV =
5645 CGM.getModule().getGlobalVariable(VTableName);
5646 if (!VTableGV)
5647 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5648 llvm::GlobalValue::ExternalLinkage,
5649 0, VTableName, &CGM.getModule());
5650
5651 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5652
5653 std::vector<llvm::Constant*> Values(3);
5654 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5655 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005656 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005657 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5658
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005659 if (Entry) {
5660 Entry->setInitializer(Init);
5661 } else {
5662 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5663 llvm::GlobalValue::WeakAnyLinkage,
5664 Init,
5665 (std::string("OBJC_EHTYPE_$_") +
5666 ID->getIdentifier()->getName()),
5667 &CGM.getModule());
5668 }
5669
Daniel Dunbar04d40782009-04-14 06:00:08 +00005670 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005671 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005672 Entry->setAlignment(8);
5673
5674 if (ForDefinition) {
5675 Entry->setSection("__DATA,__objc_const");
5676 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5677 } else {
5678 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5679 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005680
5681 return Entry;
5682}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005683
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005684/* *** */
5685
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005686CodeGen::CGObjCRuntime *
5687CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005688 return new CGObjCMac(CGM);
5689}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005690
5691CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005692CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005693 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005694}