blob: 6ffca8134afad8bf789fa300bd324241b2291b55 [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 Dunbar2bebbf02009-05-03 10:46:44 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000022#include "clang/AST/StmtObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000023#include "clang/Basic/LangOptions.h"
24
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000025#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000026#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000027#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000028#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000029#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000032using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000033
Daniel Dunbar97776872009-04-22 07:32:20 +000034// Common CGObjCRuntime functions, these don't belong here, but they
35// don't belong in CGObjCRuntime either so we will live with it for
36// now.
37
Daniel Dunbar532d4da2009-05-03 13:15:50 +000038/// FindIvarInterface - Find the interface containing the ivar.
Daniel Dunbara2435782009-04-22 12:00:04 +000039///
Daniel Dunbar532d4da2009-05-03 13:15:50 +000040/// FIXME: We shouldn't need to do this, the containing context should
41/// be fixed.
42static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
43 const ObjCInterfaceDecl *OID,
44 const ObjCIvarDecl *OIVD,
45 unsigned &Index) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000046 // FIXME: The index here is closely tied to how
47 // ASTContext::getObjCLayout is implemented. This should be fixed to
48 // get the information from the layout directly.
49 Index = 0;
Fariborz Jahanian98200742009-05-12 18:14:29 +000050 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +000051 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +000052 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
53 if (OIVD == Ivars[k])
54 return OID;
55 ++Index;
Daniel Dunbara80a0f62009-04-22 17:43:55 +000056 }
Fariborz Jahanian98200742009-05-12 18:14:29 +000057
Daniel Dunbar532d4da2009-05-03 13:15:50 +000058 // Otherwise check in the super class.
Daniel Dunbara81419d2009-05-05 00:36:57 +000059 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Daniel Dunbar532d4da2009-05-03 13:15:50 +000060 return FindIvarInterface(Context, Super, OIVD, Index);
61
62 return 0;
Daniel Dunbara2435782009-04-22 12:00:04 +000063}
64
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000065static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
66 const ObjCInterfaceDecl *OID,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000067 const ObjCImplementationDecl *ID,
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000068 const ObjCIvarDecl *Ivar) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000069 unsigned Index;
70 const ObjCInterfaceDecl *Container =
71 FindIvarInterface(CGM.getContext(), OID, Ivar, Index);
72 assert(Container && "Unable to find ivar container");
73
74 // If we know have an implementation (and the ivar is in it) then
75 // look up in the implementation layout.
76 const ASTRecordLayout *RL;
77 if (ID && ID->getClassInterface() == Container)
78 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
79 else
80 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
81 return RL->getFieldOffset(Index);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000082}
83
84uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
85 const ObjCInterfaceDecl *OID,
86 const ObjCIvarDecl *Ivar) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000087 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
88}
89
90uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
91 const ObjCImplementationDecl *OID,
92 const ObjCIvarDecl *Ivar) {
93 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
Daniel Dunbar97776872009-04-22 07:32:20 +000094}
95
96LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
97 const ObjCInterfaceDecl *OID,
98 llvm::Value *BaseValue,
99 const ObjCIvarDecl *Ivar,
100 unsigned CVRQualifiers,
101 llvm::Value *Offset) {
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000102 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar97776872009-04-22 07:32:20 +0000103 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000104 QualType IvarTy = Ivar->getType();
105 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar97776872009-04-22 07:32:20 +0000106 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar97776872009-04-22 07:32:20 +0000107 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000108 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000109
110 if (Ivar->isBitField()) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +0000111 // We need to compute the bit offset for the bit-field, the offset
112 // is to the byte. Note, there is a subtle invariant here: we can
113 // only call this routine on non-sythesized ivars but we may be
114 // called for synthesized ivars. However, a synthesized ivar can
115 // never be a bit-field so this is safe.
116 uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
117
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000118 uint64_t BitFieldSize =
119 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
120 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbare38df862009-05-03 07:52:00 +0000121 IvarTy->isSignedIntegerType(),
122 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar97776872009-04-22 07:32:20 +0000123 }
124
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000125 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
126 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000127 LValue::SetObjCIvar(LV, true);
128 return LV;
129}
130
131///
132
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000133namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000134
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000135 typedef std::vector<llvm::Constant*> ConstantVector;
136
Mike Stumpf5408fe2009-05-16 07:57:57 +0000137 // FIXME: We should find a nicer way to make the labels for metadata, string
138 // concatenation is lame.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000139
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000140class ObjCCommonTypesHelper {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000141private:
142 llvm::Constant *getMessageSendFn() const {
143 // id objc_msgSend (id, SEL, ...)
144 std::vector<const llvm::Type*> Params;
145 Params.push_back(ObjectPtrTy);
146 Params.push_back(SelectorPtrTy);
147 return
148 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
149 Params, true),
150 "objc_msgSend");
151 }
152
153 llvm::Constant *getMessageSendStretFn() const {
154 // id objc_msgSend_stret (id, SEL, ...)
155 std::vector<const llvm::Type*> Params;
156 Params.push_back(ObjectPtrTy);
157 Params.push_back(SelectorPtrTy);
158 return
159 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
160 Params, true),
161 "objc_msgSend_stret");
162
163 }
164
165 llvm::Constant *getMessageSendFpretFn() const {
166 // FIXME: This should be long double on x86_64?
167 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
168 std::vector<const llvm::Type*> Params;
169 Params.push_back(ObjectPtrTy);
170 Params.push_back(SelectorPtrTy);
171 return
172 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
173 Params,
174 true),
175 "objc_msgSend_fpret");
176
177 }
178
179 llvm::Constant *getMessageSendSuperFn() const {
180 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
181 const char *SuperName = "objc_msgSendSuper";
182 std::vector<const llvm::Type*> Params;
183 Params.push_back(SuperPtrTy);
184 Params.push_back(SelectorPtrTy);
185 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
186 Params, true),
187 SuperName);
188 }
189
190 llvm::Constant *getMessageSendSuperFn2() const {
191 // id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
192 const char *SuperName = "objc_msgSendSuper2";
193 std::vector<const llvm::Type*> Params;
194 Params.push_back(SuperPtrTy);
195 Params.push_back(SelectorPtrTy);
196 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
197 Params, true),
198 SuperName);
199 }
200
201 llvm::Constant *getMessageSendSuperStretFn() const {
202 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
203 // SEL op, ...)
204 std::vector<const llvm::Type*> Params;
205 Params.push_back(Int8PtrTy);
206 Params.push_back(SuperPtrTy);
207 Params.push_back(SelectorPtrTy);
208 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
209 Params, true),
210 "objc_msgSendSuper_stret");
211 }
212
213 llvm::Constant *getMessageSendSuperStretFn2() const {
214 // void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
215 // SEL op, ...)
216 std::vector<const llvm::Type*> Params;
217 Params.push_back(Int8PtrTy);
218 Params.push_back(SuperPtrTy);
219 Params.push_back(SelectorPtrTy);
220 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
221 Params, true),
222 "objc_msgSendSuper2_stret");
223 }
224
225 llvm::Constant *getMessageSendSuperFpretFn() const {
226 // There is no objc_msgSendSuper_fpret? How can that work?
227 return getMessageSendSuperFn();
228 }
229
230 llvm::Constant *getMessageSendSuperFpretFn2() const {
231 // There is no objc_msgSendSuper_fpret? How can that work?
232 return getMessageSendSuperFn2();
233 }
234
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000235protected:
236 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000237
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000238public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000239 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000240 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000241
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000242 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
243 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000244
245 /// PtrObjectPtrTy - LLVM type for id *
246 const llvm::Type *PtrObjectPtrTy;
247
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000248 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000249 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000250 /// ProtocolPtrTy - LLVM type for external protocol handles
251 /// (typeof(Protocol))
252 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000253
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000254 // SuperCTy - clang type for struct objc_super.
255 QualType SuperCTy;
256 // SuperPtrCTy - clang type for struct objc_super *.
257 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000258
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000259 /// SuperTy - LLVM type for struct objc_super.
260 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000261 /// SuperPtrTy - LLVM type for struct objc_super *.
262 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000263
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000264 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
265 /// in GCC parlance).
266 const llvm::StructType *PropertyTy;
267
268 /// PropertyListTy - LLVM type for struct objc_property_list
269 /// (_prop_list_t in GCC parlance).
270 const llvm::StructType *PropertyListTy;
271 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
272 const llvm::Type *PropertyListPtrTy;
273
274 // MethodTy - LLVM type for struct objc_method.
275 const llvm::StructType *MethodTy;
276
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000277 /// CacheTy - LLVM type for struct objc_cache.
278 const llvm::Type *CacheTy;
279 /// CachePtrTy - LLVM type for struct objc_cache *.
280 const llvm::Type *CachePtrTy;
281
Chris Lattner72db6c32009-04-22 02:44:54 +0000282 llvm::Constant *getGetPropertyFn() {
283 CodeGen::CodeGenTypes &Types = CGM.getTypes();
284 ASTContext &Ctx = CGM.getContext();
285 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
286 llvm::SmallVector<QualType,16> Params;
287 QualType IdType = Ctx.getObjCIdType();
288 QualType SelType = Ctx.getObjCSelType();
289 Params.push_back(IdType);
290 Params.push_back(SelType);
291 Params.push_back(Ctx.LongTy);
292 Params.push_back(Ctx.BoolTy);
293 const llvm::FunctionType *FTy =
294 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
295 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
296 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000297
Chris Lattner72db6c32009-04-22 02:44:54 +0000298 llvm::Constant *getSetPropertyFn() {
299 CodeGen::CodeGenTypes &Types = CGM.getTypes();
300 ASTContext &Ctx = CGM.getContext();
301 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
302 llvm::SmallVector<QualType,16> Params;
303 QualType IdType = Ctx.getObjCIdType();
304 QualType SelType = Ctx.getObjCSelType();
305 Params.push_back(IdType);
306 Params.push_back(SelType);
307 Params.push_back(Ctx.LongTy);
308 Params.push_back(IdType);
309 Params.push_back(Ctx.BoolTy);
310 Params.push_back(Ctx.BoolTy);
311 const llvm::FunctionType *FTy =
312 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
313 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
314 }
315
316 llvm::Constant *getEnumerationMutationFn() {
317 // void objc_enumerationMutation (id)
318 std::vector<const llvm::Type*> Args;
319 Args.push_back(ObjectPtrTy);
320 llvm::FunctionType *FTy =
321 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
322 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
323 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000324
325 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000326 llvm::Constant *getGcReadWeakFn() {
327 // id objc_read_weak (id *)
328 std::vector<const llvm::Type*> Args;
329 Args.push_back(ObjectPtrTy->getPointerTo());
330 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
331 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
332 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000333
334 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000335 llvm::Constant *getGcAssignWeakFn() {
336 // id objc_assign_weak (id, id *)
337 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
338 Args.push_back(ObjectPtrTy->getPointerTo());
339 llvm::FunctionType *FTy =
340 llvm::FunctionType::get(ObjectPtrTy, Args, false);
341 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
342 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000343
344 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000345 llvm::Constant *getGcAssignGlobalFn() {
346 // id objc_assign_global(id, id *)
347 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
348 Args.push_back(ObjectPtrTy->getPointerTo());
349 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
350 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
351 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000352
353 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000354 llvm::Constant *getGcAssignIvarFn() {
355 // id objc_assign_ivar(id, id *)
356 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
357 Args.push_back(ObjectPtrTy->getPointerTo());
358 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
359 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
360 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000361
362 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000363 llvm::Constant *getGcAssignStrongCastFn() {
364 // id objc_assign_global(id, id *)
365 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
366 Args.push_back(ObjectPtrTy->getPointerTo());
367 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
368 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
369 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000370
371 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000372 llvm::Constant *getExceptionThrowFn() {
373 // void objc_exception_throw(id)
374 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
375 llvm::FunctionType *FTy =
376 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
377 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
378 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000379
Daniel Dunbar1c566672009-02-24 01:43:46 +0000380 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000381 llvm::Constant *getSyncEnterFn() {
382 // void objc_sync_enter (id)
383 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
384 llvm::FunctionType *FTy =
385 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
386 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
387 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000388
389 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000390 llvm::Constant *getSyncExitFn() {
391 // void objc_sync_exit (id)
392 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
393 llvm::FunctionType *FTy =
394 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
395 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
396 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000397
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000398 llvm::Constant *getSendFn(bool IsSuper) const {
399 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
400 }
401
402 llvm::Constant *getSendFn2(bool IsSuper) const {
403 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
404 }
405
406 llvm::Constant *getSendStretFn(bool IsSuper) const {
407 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
408 }
409
410 llvm::Constant *getSendStretFn2(bool IsSuper) const {
411 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
412 }
413
414 llvm::Constant *getSendFpretFn(bool IsSuper) const {
415 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
416 }
417
418 llvm::Constant *getSendFpretFn2(bool IsSuper) const {
419 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
420 }
421
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000422 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
423 ~ObjCCommonTypesHelper(){}
424};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000425
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000426/// ObjCTypesHelper - Helper class that encapsulates lazy
427/// construction of varies types used during ObjC generation.
428class ObjCTypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000429public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000430 /// SymtabTy - LLVM type for struct objc_symtab.
431 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000432 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
433 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000434 /// ModuleTy - LLVM type for struct objc_module.
435 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000436
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000437 /// ProtocolTy - LLVM type for struct objc_protocol.
438 const llvm::StructType *ProtocolTy;
439 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
440 const llvm::Type *ProtocolPtrTy;
441 /// ProtocolExtensionTy - LLVM type for struct
442 /// objc_protocol_extension.
443 const llvm::StructType *ProtocolExtensionTy;
444 /// ProtocolExtensionTy - LLVM type for struct
445 /// objc_protocol_extension *.
446 const llvm::Type *ProtocolExtensionPtrTy;
447 /// MethodDescriptionTy - LLVM type for struct
448 /// objc_method_description.
449 const llvm::StructType *MethodDescriptionTy;
450 /// MethodDescriptionListTy - LLVM type for struct
451 /// objc_method_description_list.
452 const llvm::StructType *MethodDescriptionListTy;
453 /// MethodDescriptionListPtrTy - LLVM type for struct
454 /// objc_method_description_list *.
455 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000456 /// ProtocolListTy - LLVM type for struct objc_property_list.
457 const llvm::Type *ProtocolListTy;
458 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
459 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000460 /// CategoryTy - LLVM type for struct objc_category.
461 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000462 /// ClassTy - LLVM type for struct objc_class.
463 const llvm::StructType *ClassTy;
464 /// ClassPtrTy - LLVM type for struct objc_class *.
465 const llvm::Type *ClassPtrTy;
466 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
467 const llvm::StructType *ClassExtensionTy;
468 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
469 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000470 // IvarTy - LLVM type for struct objc_ivar.
471 const llvm::StructType *IvarTy;
472 /// IvarListTy - LLVM type for struct objc_ivar_list.
473 const llvm::Type *IvarListTy;
474 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
475 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000476 /// MethodListTy - LLVM type for struct objc_method_list.
477 const llvm::Type *MethodListTy;
478 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
479 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000480
481 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
482 const llvm::Type *ExceptionDataTy;
483
Anders Carlsson124526b2008-09-09 10:10:21 +0000484 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000485 llvm::Constant *getExceptionTryEnterFn() {
486 std::vector<const llvm::Type*> Params;
487 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
488 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
489 Params, false),
490 "objc_exception_try_enter");
491 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000492
493 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000494 llvm::Constant *getExceptionTryExitFn() {
495 std::vector<const llvm::Type*> Params;
496 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
497 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
498 Params, false),
499 "objc_exception_try_exit");
500 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000501
502 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000503 llvm::Constant *getExceptionExtractFn() {
504 std::vector<const llvm::Type*> Params;
505 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
506 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
507 Params, false),
508 "objc_exception_extract");
509
510 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000511
512 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000513 llvm::Constant *getExceptionMatchFn() {
514 std::vector<const llvm::Type*> Params;
515 Params.push_back(ClassPtrTy);
516 Params.push_back(ObjectPtrTy);
517 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
518 Params, false),
519 "objc_exception_match");
520
521 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000522
523 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000524 llvm::Constant *getSetJmpFn() {
525 std::vector<const llvm::Type*> Params;
526 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
527 return
528 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
529 Params, false),
530 "_setjmp");
531
532 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000533
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000534public:
535 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000536 ~ObjCTypesHelper() {}
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000537};
538
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000539/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000540/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000541class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000542public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000543
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000544 // MethodListnfABITy - LLVM for struct _method_list_t
545 const llvm::StructType *MethodListnfABITy;
546
547 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
548 const llvm::Type *MethodListnfABIPtrTy;
549
550 // ProtocolnfABITy = LLVM for struct _protocol_t
551 const llvm::StructType *ProtocolnfABITy;
552
Daniel Dunbar948e2582009-02-15 07:36:20 +0000553 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
554 const llvm::Type *ProtocolnfABIPtrTy;
555
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000556 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
557 const llvm::StructType *ProtocolListnfABITy;
558
559 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
560 const llvm::Type *ProtocolListnfABIPtrTy;
561
562 // ClassnfABITy - LLVM for struct _class_t
563 const llvm::StructType *ClassnfABITy;
564
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000565 // ClassnfABIPtrTy - LLVM for struct _class_t*
566 const llvm::Type *ClassnfABIPtrTy;
567
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000568 // IvarnfABITy - LLVM for struct _ivar_t
569 const llvm::StructType *IvarnfABITy;
570
571 // IvarListnfABITy - LLVM for struct _ivar_list_t
572 const llvm::StructType *IvarListnfABITy;
573
574 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
575 const llvm::Type *IvarListnfABIPtrTy;
576
577 // ClassRonfABITy - LLVM for struct _class_ro_t
578 const llvm::StructType *ClassRonfABITy;
579
580 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
581 const llvm::Type *ImpnfABITy;
582
583 // CategorynfABITy - LLVM for struct _category_t
584 const llvm::StructType *CategorynfABITy;
585
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000586 // New types for nonfragile abi messaging.
587
588 // MessageRefTy - LLVM for:
589 // struct _message_ref_t {
590 // IMP messenger;
591 // SEL name;
592 // };
593 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000594 // MessageRefCTy - clang type for struct _message_ref_t
595 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000596
597 // MessageRefPtrTy - LLVM for struct _message_ref_t*
598 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000599 // MessageRefCPtrTy - clang type for struct _message_ref_t*
600 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000601
Fariborz Jahanianef163782009-02-05 01:13:09 +0000602 // MessengerTy - Type of the messenger (shown as IMP above)
603 const llvm::FunctionType *MessengerTy;
604
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000605 // SuperMessageRefTy - LLVM for:
606 // struct _super_message_ref_t {
607 // SUPER_IMP messenger;
608 // SEL name;
609 // };
610 const llvm::StructType *SuperMessageRefTy;
611
612 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
613 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000614
Chris Lattner1c02f862009-04-22 02:53:24 +0000615 llvm::Constant *getMessageSendFixupFn() {
616 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
617 std::vector<const llvm::Type*> Params;
618 Params.push_back(ObjectPtrTy);
619 Params.push_back(MessageRefPtrTy);
620 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
621 Params, true),
622 "objc_msgSend_fixup");
623 }
624
625 llvm::Constant *getMessageSendFpretFixupFn() {
626 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
627 std::vector<const llvm::Type*> Params;
628 Params.push_back(ObjectPtrTy);
629 Params.push_back(MessageRefPtrTy);
630 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
631 Params, true),
632 "objc_msgSend_fpret_fixup");
633 }
634
635 llvm::Constant *getMessageSendStretFixupFn() {
636 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
637 std::vector<const llvm::Type*> Params;
638 Params.push_back(ObjectPtrTy);
639 Params.push_back(MessageRefPtrTy);
640 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
641 Params, true),
642 "objc_msgSend_stret_fixup");
643 }
644
645 llvm::Constant *getMessageSendIdFixupFn() {
646 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
647 std::vector<const llvm::Type*> Params;
648 Params.push_back(ObjectPtrTy);
649 Params.push_back(MessageRefPtrTy);
650 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
651 Params, true),
652 "objc_msgSendId_fixup");
653 }
654
655 llvm::Constant *getMessageSendIdStretFixupFn() {
656 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
657 std::vector<const llvm::Type*> Params;
658 Params.push_back(ObjectPtrTy);
659 Params.push_back(MessageRefPtrTy);
660 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
661 Params, true),
662 "objc_msgSendId_stret_fixup");
663 }
664 llvm::Constant *getMessageSendSuper2FixupFn() {
665 // id objc_msgSendSuper2_fixup (struct objc_super *,
666 // struct _super_message_ref_t*, ...)
667 std::vector<const llvm::Type*> Params;
668 Params.push_back(SuperPtrTy);
669 Params.push_back(SuperMessageRefPtrTy);
670 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
671 Params, true),
672 "objc_msgSendSuper2_fixup");
673 }
674
675 llvm::Constant *getMessageSendSuper2StretFixupFn() {
676 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
677 // struct _super_message_ref_t*, ...)
678 std::vector<const llvm::Type*> Params;
679 Params.push_back(SuperPtrTy);
680 Params.push_back(SuperMessageRefPtrTy);
681 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
682 Params, true),
683 "objc_msgSendSuper2_stret_fixup");
684 }
685
686
687
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000688 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
689 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000690 llvm::Value *getEHPersonalityPtr() {
691 llvm::Constant *Personality =
692 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
693 std::vector<const llvm::Type*>(),
694 true),
695 "__objc_personality_v0");
696 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
697 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000698
Chris Lattner8a569112009-04-22 02:15:23 +0000699 llvm::Constant *getUnwindResumeOrRethrowFn() {
700 std::vector<const llvm::Type*> Params;
701 Params.push_back(Int8PtrTy);
702 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
703 Params, false),
704 "_Unwind_Resume_or_Rethrow");
705 }
706
707 llvm::Constant *getObjCEndCatchFn() {
708 std::vector<const llvm::Type*> Params;
709 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
710 Params, false),
711 "objc_end_catch");
712
713 }
714
715 llvm::Constant *getObjCBeginCatchFn() {
716 std::vector<const llvm::Type*> Params;
717 Params.push_back(Int8PtrTy);
718 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
719 Params, false),
720 "objc_begin_catch");
721 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000722
723 const llvm::StructType *EHTypeTy;
724 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000725
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000726 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
727 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000728};
729
730class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000731public:
732 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000733 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000734 public:
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000735 unsigned ivar_bytepos;
736 unsigned ivar_size;
737 GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
738 : ivar_bytepos(bytepos), ivar_size(size) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000739
740 // Allow sorting based on byte pos.
741 bool operator<(const GC_IVAR &b) const {
742 return ivar_bytepos < b.ivar_bytepos;
743 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000744 };
745
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000746 class SKIP_SCAN {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000747 public:
748 unsigned skip;
749 unsigned scan;
750 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
751 : skip(_skip), scan(_scan) {}
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000752 };
753
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000754protected:
755 CodeGen::CodeGenModule &CGM;
756 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000757 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000758
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000759 // gc ivar layout bitmap calculation helper caches.
760 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
761 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000762
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000763 /// LazySymbols - Symbols to generate a lazy reference for. See
764 /// DefinedSymbols and FinishModule().
765 std::set<IdentifierInfo*> LazySymbols;
766
767 /// DefinedSymbols - External symbols which are defined by this
768 /// module. The symbols in this list and LazySymbols are used to add
769 /// special linker symbols which ensure that Objective-C modules are
770 /// linked properly.
771 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000772
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000773 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000774 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000775
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000776 /// MethodVarNames - uniqued method variable names.
777 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000778
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000779 /// MethodVarTypes - uniqued method type signatures. We have to use
780 /// a StringMap here because have no other unique reference.
781 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000782
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000783 /// MethodDefinitions - map of methods which have been defined in
784 /// this translation unit.
785 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000786
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000787 /// PropertyNames - uniqued method variable names.
788 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000789
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000790 /// ClassReferences - uniqued class references.
791 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000792
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000793 /// SelectorReferences - uniqued selector references.
794 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000795
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000796 /// Protocols - Protocols for which an objc_protocol structure has
797 /// been emitted. Forward declarations are handled by creating an
798 /// empty structure whose initializer is filled in when/if defined.
799 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000800
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000801 /// DefinedProtocols - Protocols which have actually been
802 /// defined. We should not need this, see FIXME in GenerateProtocol.
803 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000804
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000805 /// DefinedClasses - List of defined classes.
806 std::vector<llvm::GlobalValue*> DefinedClasses;
Daniel Dunbar74d4b122009-05-15 22:33:15 +0000807
808 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
809 std::vector<llvm::GlobalValue*> DefinedNonLazyClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000810
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000811 /// DefinedCategories - List of defined categories.
812 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000813
Daniel Dunbar74d4b122009-05-15 22:33:15 +0000814 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
815 std::vector<llvm::GlobalValue*> DefinedNonLazyCategories;
816
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000817 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000818 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000819 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000820
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000821 /// GetNameForMethod - Return a name for the given method.
822 /// \param[out] NameOut - The return value.
823 void GetNameForMethod(const ObjCMethodDecl *OMD,
824 const ObjCContainerDecl *CD,
825 std::string &NameOut);
826
827 /// GetMethodVarName - Return a unique constant for the given
828 /// selector's name. The return value has type char *.
829 llvm::Constant *GetMethodVarName(Selector Sel);
830 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
831 llvm::Constant *GetMethodVarName(const std::string &Name);
832
833 /// GetMethodVarType - Return a unique constant for the given
834 /// selector's name. The return value has type char *.
835
836 // FIXME: This is a horrible name.
837 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000838 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000839
840 /// GetPropertyName - Return a unique constant for the given
841 /// name. The return value has type char *.
842 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
843
844 // FIXME: This can be dropped once string functions are unified.
845 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
846 const Decl *Container);
847
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000848 /// GetClassName - Return a unique constant for the given selector's
849 /// name. The return value has type char *.
850 llvm::Constant *GetClassName(IdentifierInfo *Ident);
851
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000852 /// BuildIvarLayout - Builds ivar layout bitmap for the class
853 /// implementation for the __strong or __weak case.
854 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000855 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
856 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000857
Daniel Dunbard58edcb2009-05-03 14:10:34 +0000858 void BuildAggrIvarRecordLayout(const RecordType *RT,
859 unsigned int BytePos, bool ForStrongLayout,
860 bool &HasUnion);
Daniel Dunbar5a5a8032009-05-03 21:05:10 +0000861 void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000862 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000863 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000864 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000865 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000866 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000867
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000868 /// GetIvarLayoutName - Returns a unique constant for the given
869 /// ivar layout bitmap.
870 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
871 const ObjCCommonTypesHelper &ObjCTypes);
872
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000873 /// EmitPropertyList - Emit the given property list. The return
874 /// value has type PropertyListPtrTy.
875 llvm::Constant *EmitPropertyList(const std::string &Name,
876 const Decl *Container,
877 const ObjCContainerDecl *OCD,
878 const ObjCCommonTypesHelper &ObjCTypes);
879
Fariborz Jahanianda320092009-01-29 19:24:30 +0000880 /// GetProtocolRef - Return a reference to the internal protocol
881 /// description, creating an empty one if it has not been
882 /// defined. The return value has type ProtocolPtrTy.
883 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000884
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000885 /// CreateMetadataVar - Create a global variable with internal
886 /// linkage for use by the Objective-C runtime.
887 ///
888 /// This is a convenience wrapper which not only creates the
889 /// variable, but also sets the section and alignment and adds the
890 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000891 ///
892 /// \param Name - The variable name.
893 /// \param Init - The variable initializer; this is also used to
894 /// define the type of the variable.
895 /// \param Section - The section the variable should go into, or 0.
896 /// \param Align - The alignment for the variable, or 0.
897 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000898 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000899 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
900 llvm::Constant *Init,
901 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000902 unsigned Align,
903 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000904
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000905 CodeGen::RValue EmitLegacyMessageSend(CodeGen::CodeGenFunction &CGF,
906 QualType ResultType,
907 llvm::Value *Sel,
908 llvm::Value *Arg0,
909 QualType Arg0Ty,
910 bool IsSuper,
911 const CallArgList &CallArgs,
912 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000913
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000914public:
915 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
916 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000917
Steve Naroff33fdb732009-03-31 16:53:37 +0000918 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000919
920 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
921 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000922
923 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
924
925 /// GetOrEmitProtocol - Get the protocol object for the given
926 /// declaration, emitting it if necessary. The return value has type
927 /// ProtocolPtrTy.
928 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
929
930 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
931 /// object for the given declaration, emitting it if needed. These
932 /// forward references will be filled in with empty bodies if no
933 /// definition is seen. The return value has type ProtocolPtrTy.
934 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000935};
936
937class CGObjCMac : public CGObjCCommonMac {
938private:
939 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000940 /// EmitImageInfo - Emit the image info marker used to encode some module
941 /// level information.
942 void EmitImageInfo();
943
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000944 /// EmitModuleInfo - Another marker encoding module level
945 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000946 void EmitModuleInfo();
947
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000948 /// EmitModuleSymols - Emit module symbols, the list of defined
949 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000950 llvm::Constant *EmitModuleSymbols();
951
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000952 /// FinishModule - Write out global data structures at the end of
953 /// processing a translation unit.
954 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000955
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000956 /// EmitClassExtension - Generate the class extension structure used
957 /// to store the weak ivar layout and properties. The return value
958 /// has type ClassExtensionPtrTy.
959 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
960
961 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
962 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000963 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000964 const ObjCInterfaceDecl *ID);
965
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000966 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000967 QualType ResultType,
968 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000969 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000970 QualType Arg0Ty,
971 bool IsSuper,
972 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000973
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000974 /// EmitIvarList - Emit the ivar list for the given
975 /// implementation. If ForClass is true the list of class ivars
976 /// (i.e. metaclass ivars) is emitted, otherwise the list of
977 /// interface ivars will be emitted. The return value has type
978 /// IvarListPtrTy.
979 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000980 bool ForClass);
981
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000982 /// EmitMetaClass - Emit a forward reference to the class structure
983 /// for the metaclass of the given interface. The return value has
984 /// type ClassPtrTy.
985 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
986
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000987 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000988 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000989 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
990 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000991 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000992
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000993 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000994
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000995 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000996
997 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000998 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000999 llvm::Constant *EmitMethodList(const std::string &Name,
1000 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001001 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001002
1003 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001004 /// method declarations.
1005 /// - TypeName: The name for the type containing the methods.
1006 /// - IsProtocol: True iff these methods are for a protocol.
1007 /// - ClassMethds: True iff these are class methods.
1008 /// - Required: When true, only "required" methods are
1009 /// listed. Similarly, when false only "optional" methods are
1010 /// listed. For classes this should always be true.
1011 /// - begin, end: The method list to output.
1012 ///
1013 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001014 llvm::Constant *EmitMethodDescList(const std::string &Name,
1015 const char *Section,
1016 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001017
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001018 /// GetOrEmitProtocol - Get the protocol object for the given
1019 /// declaration, emitting it if necessary. The return value has type
1020 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001021 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001022
1023 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1024 /// object for the given declaration, emitting it if needed. These
1025 /// forward references will be filled in with empty bodies if no
1026 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001027 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001028
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001029 /// EmitProtocolExtension - Generate the protocol extension
1030 /// structure used to store optional instance and class methods, and
1031 /// protocol properties. The return value has type
1032 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001033 llvm::Constant *
1034 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1035 const ConstantVector &OptInstanceMethods,
1036 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001037
1038 /// EmitProtocolList - Generate the list of referenced
1039 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001040 llvm::Constant *EmitProtocolList(const std::string &Name,
1041 ObjCProtocolDecl::protocol_iterator begin,
1042 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001043
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001044 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1045 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001046 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001047
Fariborz Jahanianda320092009-01-29 19:24:30 +00001048 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001049 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001050
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001051 virtual llvm::Function *ModuleInitFunction();
1052
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001053 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001054 QualType ResultType,
1055 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001056 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001057 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001058 const CallArgList &CallArgs,
1059 const ObjCMethodDecl *Method);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001060
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001061 virtual CodeGen::RValue
1062 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001063 QualType ResultType,
1064 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001065 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001066 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001067 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001068 bool IsClassMessage,
1069 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001070
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001071 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001072 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001073
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001074 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001075
1076 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1077 /// untyped one.
1078 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1079 const ObjCMethodDecl *Method);
1080
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001081 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001082
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001083 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001084
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001085 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001086 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001087
Chris Lattner74391b42009-03-22 21:03:39 +00001088 virtual llvm::Constant *GetPropertyGetFunction();
1089 virtual llvm::Constant *GetPropertySetFunction();
1090 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001091
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001092 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1093 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001094 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1095 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001096 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001097 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001098 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1099 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001100 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1101 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001102 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1103 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001104 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1105 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001106
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001107 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1108 QualType ObjectTy,
1109 llvm::Value *BaseValue,
1110 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001111 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001112 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001113 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001114 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001115};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001116
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001117class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001118private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001119 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001120 llvm::GlobalVariable* ObjCEmptyCacheVar;
1121 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001122
Daniel Dunbar11394522009-04-18 08:51:00 +00001123 /// SuperClassReferences - uniqued super class references.
1124 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1125
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001126 /// MetaClassReferences - uniqued meta class references.
1127 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001128
1129 /// EHTypeReferences - uniqued class ehtype references.
1130 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001131
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001132 /// NonLegacyDispatchMethods - List of methods for which we do *not* generate
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001133 /// legacy messaging dispatch.
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001134 llvm::DenseSet<Selector> NonLegacyDispatchMethods;
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001135
1136 /// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001137 /// NonLegacyDispatchMethods; false otherwise.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001138 bool LegacyDispatchedSelector(Selector Sel);
1139
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001140 /// FinishNonFragileABIModule - Write out global data structures at the end of
1141 /// processing a translation unit.
1142 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001143
Daniel Dunbar463b8762009-05-15 21:48:48 +00001144 /// AddModuleClassList - Add the given list of class pointers to the
1145 /// module with the provided symbol and section names.
1146 void AddModuleClassList(const std::vector<llvm::GlobalValue*> &Container,
1147 const char *SymbolName,
1148 const char *SectionName);
1149
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001150 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1151 unsigned InstanceStart,
1152 unsigned InstanceSize,
1153 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001154 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1155 llvm::Constant *IsAGV,
1156 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001157 llvm::Constant *ClassRoGV,
1158 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001159
1160 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1161
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001162 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1163
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001164 /// EmitMethodList - Emit the method list for the given
1165 /// implementation. The return value has type MethodListnfABITy.
1166 llvm::Constant *EmitMethodList(const std::string &Name,
1167 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001168 const ConstantVector &Methods);
1169 /// EmitIvarList - Emit the ivar list for the given
1170 /// implementation. If ForClass is true the list of class ivars
1171 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1172 /// interface ivars will be emitted. The return value has type
1173 /// IvarListnfABIPtrTy.
1174 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001175
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001176 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001177 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001178 unsigned long int offset);
1179
Fariborz Jahanianda320092009-01-29 19:24:30 +00001180 /// GetOrEmitProtocol - Get the protocol object for the given
1181 /// declaration, emitting it if necessary. The return value has type
1182 /// ProtocolPtrTy.
1183 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1184
1185 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1186 /// object for the given declaration, emitting it if needed. These
1187 /// forward references will be filled in with empty bodies if no
1188 /// definition is seen. The return value has type ProtocolPtrTy.
1189 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1190
1191 /// EmitProtocolList - Generate the list of referenced
1192 /// protocols. The return value has type ProtocolListPtrTy.
1193 llvm::Constant *EmitProtocolList(const std::string &Name,
1194 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001195 ObjCProtocolDecl::protocol_iterator end);
1196
1197 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1198 QualType ResultType,
1199 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001200 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001201 QualType Arg0Ty,
1202 bool IsSuper,
1203 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001204
1205 /// GetClassGlobal - Return the global variable for the Objective-C
1206 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001207 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1208
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001209 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001210 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001211 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001212 const ObjCInterfaceDecl *ID);
1213
1214 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1215 /// for the given super class reference.
1216 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1217 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001218
1219 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1220 /// meta-data
1221 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1222 const ObjCInterfaceDecl *ID);
1223
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001224 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1225 /// the given ivar.
1226 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001227 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001228 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001229 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001230
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001231 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1232 /// for the given selector.
1233 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001234
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001235 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001236 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001237 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1238 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001239
1240 const char *getMetaclassSymbolPrefix() const {
1241 return "OBJC_METACLASS_$_";
1242 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001243
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001244 const char *getClassSymbolPrefix() const {
1245 return "OBJC_CLASS_$_";
1246 }
1247
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001248 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001249 uint32_t &InstanceStart,
1250 uint32_t &InstanceSize);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001251
1252 // Shamelessly stolen from Analysis/CFRefCount.cpp
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001253 Selector GetNullarySelector(const char* name) const {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001254 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1255 return CGM.getContext().Selectors.getSelector(0, &II);
1256 }
1257
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001258 Selector GetUnarySelector(const char* name) const {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001259 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1260 return CGM.getContext().Selectors.getSelector(1, &II);
1261 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001262
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001263 /// ImplementationIsNonLazy - Check whether the given category or
1264 /// class implementation is "non-lazy".
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00001265 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001266
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001267public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001268 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001269 // FIXME. All stubs for now!
1270 virtual llvm::Function *ModuleInitFunction();
1271
1272 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1273 QualType ResultType,
1274 Selector Sel,
1275 llvm::Value *Receiver,
1276 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001277 const CallArgList &CallArgs,
1278 const ObjCMethodDecl *Method);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001279
1280 virtual CodeGen::RValue
1281 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1282 QualType ResultType,
1283 Selector Sel,
1284 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001285 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001286 llvm::Value *Receiver,
1287 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001288 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001289
1290 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001291 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001292
1293 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001294 { return EmitSelector(Builder, Sel); }
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001295
1296 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1297 /// untyped one.
1298 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1299 const ObjCMethodDecl *Method)
1300 { return EmitSelector(Builder, Method->getSelector()); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001301
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001302 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001303
1304 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001305 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001306 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001307
Chris Lattner74391b42009-03-22 21:03:39 +00001308 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001309 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001310 }
Chris Lattner74391b42009-03-22 21:03:39 +00001311 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001312 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001313 }
Chris Lattner74391b42009-03-22 21:03:39 +00001314 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001315 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001316 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001317
1318 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001319 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001320 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001321 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001322 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001323 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001324 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001325 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001326 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001327 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001328 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001329 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001330 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001331 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001332 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1333 QualType ObjectTy,
1334 llvm::Value *BaseValue,
1335 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001336 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001337 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001338 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001339 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001340};
1341
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001342} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001343
1344/* *** Helper Functions *** */
1345
1346/// getConstantGEP() - Help routine to construct simple GEPs.
1347static llvm::Constant *getConstantGEP(llvm::Constant *C,
1348 unsigned idx0,
1349 unsigned idx1) {
1350 llvm::Value *Idxs[] = {
1351 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1352 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1353 };
1354 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1355}
1356
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001357/// hasObjCExceptionAttribute - Return true if this class or any super
1358/// class has the __objc_exception__ attribute.
Douglas Gregor68584ed2009-06-18 16:11:24 +00001359static bool hasObjCExceptionAttribute(ASTContext &Context,
1360 const ObjCInterfaceDecl *OID) {
1361 if (OID->hasAttr<ObjCExceptionAttr>(Context))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001362 return true;
1363 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Douglas Gregor68584ed2009-06-18 16:11:24 +00001364 return hasObjCExceptionAttribute(Context, Super);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001365 return false;
1366}
1367
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001368/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001369
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001370CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1371 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001372{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001373 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001374 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001375}
1376
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001377/// GetClass - Return a reference to the class for the given interface
1378/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001379llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001380 const ObjCInterfaceDecl *ID) {
1381 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001382}
1383
1384/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001385llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001386 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001387}
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001388llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
1389 *Method) {
1390 return EmitSelector(Builder, Method->getSelector());
1391}
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001392
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001393/// Generate a constant CFString object.
1394/*
1395 struct __builtin_CFString {
1396 const int *isa; // point to __CFConstantStringClassReference
1397 int flags;
1398 const char *str;
1399 long length;
1400 };
1401*/
1402
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001403llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001404 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001405 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001406}
1407
1408/// Generates a message send where the super is the receiver. This is
1409/// a message send to self with special delivery semantics indicating
1410/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001411CodeGen::RValue
1412CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001413 QualType ResultType,
1414 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001415 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001416 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001417 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001418 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001419 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001420 // Create and init a super structure; this is a (receiver, class)
1421 // pair we will pass to objc_msgSendSuper.
1422 llvm::Value *ObjCSuper =
1423 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1424 llvm::Value *ReceiverAsObject =
1425 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1426 CGF.Builder.CreateStore(ReceiverAsObject,
1427 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001428
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001429 // If this is a class message the metaclass is passed as the target.
1430 llvm::Value *Target;
1431 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001432 if (isCategoryImpl) {
1433 // Message sent to 'super' in a class method defined in a category
1434 // implementation requires an odd treatment.
1435 // If we are in a class method, we must retrieve the
1436 // _metaclass_ for the current class, pointed at by
1437 // the class's "isa" pointer. The following assumes that
1438 // isa" is the first ivar in a class (which it must be).
1439 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1440 Target = CGF.Builder.CreateStructGEP(Target, 0);
1441 Target = CGF.Builder.CreateLoad(Target);
1442 }
1443 else {
1444 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1445 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1446 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1447 Target = Super;
1448 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001449 } else {
1450 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1451 }
Mike Stumpf5408fe2009-05-16 07:57:57 +00001452 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1453 // ObjCTypes types.
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001454 const llvm::Type *ClassTy =
1455 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001456 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001457 CGF.Builder.CreateStore(Target,
1458 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001459 return EmitLegacyMessageSend(CGF, ResultType,
1460 EmitSelector(CGF.Builder, Sel),
1461 ObjCSuper, ObjCTypes.SuperPtrCTy,
1462 true, CallArgs, ObjCTypes);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001463}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001464
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001465/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001466CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001467 QualType ResultType,
1468 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001469 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001470 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001471 const CallArgList &CallArgs,
1472 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001473 return EmitLegacyMessageSend(CGF, ResultType,
1474 EmitSelector(CGF.Builder, Sel),
1475 Receiver, CGF.getContext().getObjCIdType(),
1476 false, CallArgs, ObjCTypes);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001477}
1478
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001479CodeGen::RValue CGObjCCommonMac::EmitLegacyMessageSend(
1480 CodeGen::CodeGenFunction &CGF,
1481 QualType ResultType,
1482 llvm::Value *Sel,
1483 llvm::Value *Arg0,
1484 QualType Arg0Ty,
1485 bool IsSuper,
1486 const CallArgList &CallArgs,
1487 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001488 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001489 if (!IsSuper)
1490 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001491 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001492 ActualArgs.push_back(std::make_pair(RValue::get(Sel),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001493 CGF.getContext().getObjCSelType()));
1494 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001495
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001496 CodeGenTypes &Types = CGM.getTypes();
1497 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001498 // In 64bit ABI, type must be assumed VARARG. In 32bit abi,
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001499 // it seems not to matter.
1500 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, (ObjCABI == 2));
1501
1502 llvm::Constant *Fn = NULL;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001503 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001504 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
1505 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001506 } else if (ResultType->isFloatingType()) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001507 if (ObjCABI == 2) {
1508 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
1509 BuiltinType::Kind k = BT->getKind();
1510 Fn = (k == BuiltinType::LongDouble) ? ObjCTypes.getSendFpretFn2(IsSuper)
1511 : ObjCTypes.getSendFn2(IsSuper);
Daniel Dunbar42f963d2009-06-10 04:38:50 +00001512 } else {
1513 Fn = ObjCTypes.getSendFn2(IsSuper);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001514 }
1515 }
1516 else
Mike Stumpf5408fe2009-05-16 07:57:57 +00001517 // FIXME. This currently matches gcc's API for x86-32. May need to change
1518 // for others if we have their API.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001519 Fn = ObjCTypes.getSendFpretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001520 } else {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001521 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1522 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001523 }
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001524 assert(Fn && "EmitLegacyMessageSend - unknown API");
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001525 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001526 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001527}
1528
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001529llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001530 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001531 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stumpf5408fe2009-05-16 07:57:57 +00001532 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001533 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1534
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001535 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1536 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001537}
1538
Fariborz Jahanianda320092009-01-29 19:24:30 +00001539void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001540 // FIXME: We shouldn't need this, the protocol decl should contain enough
1541 // information to tell us whether this was a declaration or a definition.
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001542 DefinedProtocols.insert(PD->getIdentifier());
1543
1544 // If we have generated a forward reference to this protocol, emit
1545 // it now. Otherwise do nothing, the protocol objects are lazily
1546 // emitted.
1547 if (Protocols.count(PD->getIdentifier()))
1548 GetOrEmitProtocol(PD);
1549}
1550
Fariborz Jahanianda320092009-01-29 19:24:30 +00001551llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001552 if (DefinedProtocols.count(PD->getIdentifier()))
1553 return GetOrEmitProtocol(PD);
1554 return GetOrEmitProtocolRef(PD);
1555}
1556
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001557/*
1558 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1559 struct _objc_protocol {
1560 struct _objc_protocol_extension *isa;
1561 char *protocol_name;
1562 struct _objc_protocol_list *protocol_list;
1563 struct _objc__method_prototype_list *instance_methods;
1564 struct _objc__method_prototype_list *class_methods
1565 };
1566
1567 See EmitProtocolExtension().
1568*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001569llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1570 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1571
1572 // Early exit if a defining object has already been generated.
1573 if (Entry && Entry->hasInitializer())
1574 return Entry;
1575
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001576 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stumpf5408fe2009-05-16 07:57:57 +00001577 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001578 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1579
Chris Lattner8ec03f52008-11-24 03:54:41 +00001580 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001581
1582 // Construct method lists.
1583 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1584 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001585 for (ObjCProtocolDecl::instmeth_iterator
1586 i = PD->instmeth_begin(CGM.getContext()),
1587 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001588 ObjCMethodDecl *MD = *i;
1589 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1590 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1591 OptInstanceMethods.push_back(C);
1592 } else {
1593 InstanceMethods.push_back(C);
1594 }
1595 }
1596
Douglas Gregor6ab35242009-04-09 21:40:53 +00001597 for (ObjCProtocolDecl::classmeth_iterator
1598 i = PD->classmeth_begin(CGM.getContext()),
1599 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001600 ObjCMethodDecl *MD = *i;
1601 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1602 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1603 OptClassMethods.push_back(C);
1604 } else {
1605 ClassMethods.push_back(C);
1606 }
1607 }
1608
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001609 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001610 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001611 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001612 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001613 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001614 PD->protocol_begin(),
1615 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001616 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001617 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1618 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001619 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1620 InstanceMethods);
1621 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001622 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1623 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001624 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1625 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001626 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1627 Values);
1628
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001629 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001630 // Already created, fix the linkage and update the initializer.
1631 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001632 Entry->setInitializer(Init);
1633 } else {
1634 Entry =
1635 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1636 llvm::GlobalValue::InternalLinkage,
1637 Init,
1638 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1639 &CGM.getModule());
1640 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001641 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001642 UsedGlobals.push_back(Entry);
1643 // FIXME: Is this necessary? Why only for protocol?
1644 Entry->setAlignment(4);
1645 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001646
1647 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001648}
1649
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001650llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001651 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1652
1653 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001654 // We use the initializer as a marker of whether this is a forward
1655 // reference or not. At module finalization we add the empty
1656 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001657 Entry =
1658 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001659 llvm::GlobalValue::ExternalLinkage,
1660 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001661 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001662 &CGM.getModule());
1663 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001664 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001665 UsedGlobals.push_back(Entry);
1666 // FIXME: Is this necessary? Why only for protocol?
1667 Entry->setAlignment(4);
1668 }
1669
1670 return Entry;
1671}
1672
1673/*
1674 struct _objc_protocol_extension {
1675 uint32_t size;
1676 struct objc_method_description_list *optional_instance_methods;
1677 struct objc_method_description_list *optional_class_methods;
1678 struct objc_property_list *instance_properties;
1679 };
1680*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001681llvm::Constant *
1682CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1683 const ConstantVector &OptInstanceMethods,
1684 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001685 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00001686 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001687 std::vector<llvm::Constant*> Values(4);
1688 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001689 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001690 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1691 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001692 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1693 OptInstanceMethods);
1694 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001695 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1696 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001697 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1698 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001699 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1700 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001701 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001702
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001703 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001704 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1705 Values[3]->isNullValue())
1706 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1707
1708 llvm::Constant *Init =
1709 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001710
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001711 // No special section, but goes in llvm.used
1712 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1713 Init,
1714 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001715}
1716
1717/*
1718 struct objc_protocol_list {
1719 struct objc_protocol_list *next;
1720 long count;
1721 Protocol *list[];
1722 };
1723*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001724llvm::Constant *
1725CGObjCMac::EmitProtocolList(const std::string &Name,
1726 ObjCProtocolDecl::protocol_iterator begin,
1727 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001728 std::vector<llvm::Constant*> ProtocolRefs;
1729
Daniel Dunbardbc933702008-08-21 21:57:41 +00001730 for (; begin != end; ++begin)
1731 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001732
1733 // Just return null for empty protocol lists
1734 if (ProtocolRefs.empty())
1735 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1736
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001737 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001738 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1739
1740 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001741 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001742 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1743 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1744 Values[2] =
1745 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1746 ProtocolRefs.size()),
1747 ProtocolRefs);
1748
1749 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1750 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001751 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001752 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001753 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1754}
1755
1756/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001757 struct _objc_property {
1758 const char * const name;
1759 const char * const attributes;
1760 };
1761
1762 struct _objc_property_list {
1763 uint32_t entsize; // sizeof (struct _objc_property)
1764 uint32_t prop_count;
1765 struct _objc_property[prop_count];
1766 };
1767*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001768llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1769 const Decl *Container,
1770 const ObjCContainerDecl *OCD,
1771 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001772 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001773 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1774 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001775 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001776 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001777 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001778 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1779 Prop));
1780 }
1781
1782 // Return null for empty list.
1783 if (Properties.empty())
1784 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1785
1786 unsigned PropertySize =
Duncan Sands9408c452009-05-09 07:08:47 +00001787 CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001788 std::vector<llvm::Constant*> Values(3);
1789 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1790 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1791 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1792 Properties.size());
1793 Values[2] = llvm::ConstantArray::get(AT, Properties);
1794 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1795
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001796 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001797 CreateMetadataVar(Name, Init,
1798 (ObjCABI == 2) ? "__DATA, __objc_const" :
1799 "__OBJC,__property,regular,no_dead_strip",
1800 (ObjCABI == 2) ? 8 : 4,
1801 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001802 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001803}
1804
1805/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001806 struct objc_method_description_list {
1807 int count;
1808 struct objc_method_description list[];
1809 };
1810*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001811llvm::Constant *
1812CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1813 std::vector<llvm::Constant*> Desc(2);
1814 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1815 ObjCTypes.SelectorPtrTy);
1816 Desc[1] = GetMethodVarType(MD);
1817 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1818 Desc);
1819}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001820
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001821llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1822 const char *Section,
1823 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001824 // Return null for empty list.
1825 if (Methods.empty())
1826 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1827
1828 std::vector<llvm::Constant*> Values(2);
1829 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1830 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1831 Methods.size());
1832 Values[1] = llvm::ConstantArray::get(AT, Methods);
1833 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1834
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001835 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001836 return llvm::ConstantExpr::getBitCast(GV,
1837 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001838}
1839
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001840/*
1841 struct _objc_category {
1842 char *category_name;
1843 char *class_name;
1844 struct _objc_method_list *instance_methods;
1845 struct _objc_method_list *class_methods;
1846 struct _objc_protocol_list *protocols;
1847 uint32_t size; // <rdar://4585769>
1848 struct _objc_property_list *instance_properties;
1849 };
1850 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001851void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Duncan Sands9408c452009-05-09 07:08:47 +00001852 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001853
Mike Stumpf5408fe2009-05-16 07:57:57 +00001854 // FIXME: This is poor design, the OCD should have a pointer to the category
1855 // decl. Additionally, note that Category can be null for the @implementation
1856 // w/o an @interface case. Sema should just create one for us as it does for
1857 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001858 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001859 const ObjCCategoryDecl *Category =
1860 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001861 std::string ExtName(Interface->getNameAsString() + "_" +
1862 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001863
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001864 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001865 for (ObjCCategoryImplDecl::instmeth_iterator
1866 i = OCD->instmeth_begin(CGM.getContext()),
1867 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001868 // Instance methods should always be defined.
1869 InstanceMethods.push_back(GetMethodConstant(*i));
1870 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001871 for (ObjCCategoryImplDecl::classmeth_iterator
1872 i = OCD->classmeth_begin(CGM.getContext()),
1873 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001874 // Class methods should always be defined.
1875 ClassMethods.push_back(GetMethodConstant(*i));
1876 }
1877
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001878 std::vector<llvm::Constant*> Values(7);
1879 Values[0] = GetClassName(OCD->getIdentifier());
1880 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001881 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001882 Values[2] =
1883 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1884 ExtName,
1885 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001886 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001887 Values[3] =
1888 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001889 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001890 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001891 if (Category) {
1892 Values[4] =
1893 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1894 Category->protocol_begin(),
1895 Category->protocol_end());
1896 } else {
1897 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1898 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001899 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001900
1901 // If there is no category @interface then there can be no properties.
1902 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001903 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001904 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001905 } else {
1906 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1907 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001908
1909 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1910 Values);
1911
1912 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001913 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1914 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001915 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001916 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001917}
1918
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001919// FIXME: Get from somewhere?
1920enum ClassFlags {
1921 eClassFlags_Factory = 0x00001,
1922 eClassFlags_Meta = 0x00002,
1923 // <rdr://5142207>
1924 eClassFlags_HasCXXStructors = 0x02000,
1925 eClassFlags_Hidden = 0x20000,
1926 eClassFlags_ABI2_Hidden = 0x00010,
1927 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1928};
1929
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001930/*
1931 struct _objc_class {
1932 Class isa;
1933 Class super_class;
1934 const char *name;
1935 long version;
1936 long info;
1937 long instance_size;
1938 struct _objc_ivar_list *ivars;
1939 struct _objc_method_list *methods;
1940 struct _objc_cache *cache;
1941 struct _objc_protocol_list *protocols;
1942 // Objective-C 1.0 extensions (<rdr://4585769>)
1943 const char *ivar_layout;
1944 struct _objc_class_ext *ext;
1945 };
1946
1947 See EmitClassExtension();
1948 */
1949void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001950 DefinedSymbols.insert(ID->getIdentifier());
1951
Chris Lattner8ec03f52008-11-24 03:54:41 +00001952 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001953 // FIXME: Gross
1954 ObjCInterfaceDecl *Interface =
1955 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001956 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001957 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001958 Interface->protocol_begin(),
1959 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001960 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001961 unsigned Size =
1962 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001963
1964 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001965 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001966 Flags |= eClassFlags_Hidden;
1967
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001968 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001969 for (ObjCImplementationDecl::instmeth_iterator
1970 i = ID->instmeth_begin(CGM.getContext()),
1971 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001972 // Instance methods should always be defined.
1973 InstanceMethods.push_back(GetMethodConstant(*i));
1974 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001975 for (ObjCImplementationDecl::classmeth_iterator
1976 i = ID->classmeth_begin(CGM.getContext()),
1977 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001978 // Class methods should always be defined.
1979 ClassMethods.push_back(GetMethodConstant(*i));
1980 }
1981
Douglas Gregor653f1b12009-04-23 01:02:12 +00001982 for (ObjCImplementationDecl::propimpl_iterator
1983 i = ID->propimpl_begin(CGM.getContext()),
1984 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001985 ObjCPropertyImplDecl *PID = *i;
1986
1987 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1988 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1989
1990 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1991 if (llvm::Constant *C = GetMethodConstant(MD))
1992 InstanceMethods.push_back(C);
1993 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1994 if (llvm::Constant *C = GetMethodConstant(MD))
1995 InstanceMethods.push_back(C);
1996 }
1997 }
1998
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001999 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00002000 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002001 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002002 // Record a reference to the super class.
2003 LazySymbols.insert(Super->getIdentifier());
2004
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002005 Values[ 1] =
2006 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2007 ObjCTypes.ClassPtrTy);
2008 } else {
2009 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2010 }
2011 Values[ 2] = GetClassName(ID->getIdentifier());
2012 // Version is always 0.
2013 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2014 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2015 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002016 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002017 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002018 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002019 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002020 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002021 // cache is always NULL.
2022 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2023 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002024 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002025 Values[11] = EmitClassExtension(ID);
2026 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2027 Values);
2028
2029 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002030 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
2031 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002032 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002033 DefinedClasses.push_back(GV);
2034}
2035
2036llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2037 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002038 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002039 unsigned Flags = eClassFlags_Meta;
Duncan Sands9408c452009-05-09 07:08:47 +00002040 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002041
Daniel Dunbar04d40782009-04-14 06:00:08 +00002042 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002043 Flags |= eClassFlags_Hidden;
2044
2045 std::vector<llvm::Constant*> Values(12);
2046 // The isa for the metaclass is the root of the hierarchy.
2047 const ObjCInterfaceDecl *Root = ID->getClassInterface();
2048 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2049 Root = Super;
2050 Values[ 0] =
2051 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2052 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002053 // The super class for the metaclass is emitted as the name of the
2054 // super class. The runtime fixes this up to point to the
2055 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002056 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2057 Values[ 1] =
2058 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2059 ObjCTypes.ClassPtrTy);
2060 } else {
2061 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2062 }
2063 Values[ 2] = GetClassName(ID->getIdentifier());
2064 // Version is always 0.
2065 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2066 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2067 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002068 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002069 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002070 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002071 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002072 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002073 // cache is always NULL.
2074 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2075 Values[ 9] = Protocols;
2076 // ivar_layout for metaclass is always NULL.
2077 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2078 // The class extension is always unused for metaclasses.
2079 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2080 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2081 Values);
2082
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002083 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002084 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002085
2086 // Check for a forward reference.
2087 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2088 if (GV) {
2089 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2090 "Forward metaclass reference has incorrect type.");
2091 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2092 GV->setInitializer(Init);
2093 } else {
2094 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2095 llvm::GlobalValue::InternalLinkage,
2096 Init, Name,
2097 &CGM.getModule());
2098 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002099 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002100 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002101 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002102
2103 return GV;
2104}
2105
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002106llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002107 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002108
Mike Stumpf5408fe2009-05-16 07:57:57 +00002109 // FIXME: Should we look these up somewhere other than the module. Its a bit
2110 // silly since we only generate these while processing an implementation, so
2111 // exactly one pointer would work if know when we entered/exitted an
2112 // implementation block.
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002113
2114 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002115 // Previously, metaclass with internal linkage may have been defined.
2116 // pass 'true' as 2nd argument so it is returned.
2117 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002118 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2119 "Forward metaclass reference has incorrect type.");
2120 return GV;
2121 } else {
2122 // Generate as an external reference to keep a consistent
2123 // module. This will be patched up when we emit the metaclass.
2124 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2125 llvm::GlobalValue::ExternalLinkage,
2126 0,
2127 Name,
2128 &CGM.getModule());
2129 }
2130}
2131
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002132/*
2133 struct objc_class_ext {
2134 uint32_t size;
2135 const char *weak_ivar_layout;
2136 struct _objc_property_list *properties;
2137 };
2138*/
2139llvm::Constant *
2140CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2141 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00002142 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002143
2144 std::vector<llvm::Constant*> Values(3);
2145 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002146 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002147 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002148 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002149
2150 // Return null if no extension bits are used.
2151 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2152 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2153
2154 llvm::Constant *Init =
2155 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002156 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002157 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2158 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002159}
2160
2161/*
2162 struct objc_ivar {
2163 char *ivar_name;
2164 char *ivar_type;
2165 int ivar_offset;
2166 };
2167
2168 struct objc_ivar_list {
2169 int ivar_count;
2170 struct objc_ivar list[count];
2171 };
2172 */
2173llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002174 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002175 std::vector<llvm::Constant*> Ivars, Ivar(3);
2176
2177 // When emitting the root class GCC emits ivar entries for the
2178 // actual class structure. It is not clear if we need to follow this
2179 // behavior; for now lets try and get away with not doing it. If so,
2180 // the cleanest solution would be to make up an ObjCInterfaceDecl
2181 // for the class.
2182 if (ForClass)
2183 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002184
2185 ObjCInterfaceDecl *OID =
2186 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002187
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002188 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002189 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002190
2191 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2192 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002193 // Ignore unnamed bit-fields.
2194 if (!IVD->getDeclName())
2195 continue;
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002196 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2197 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002198 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002199 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002200 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002201 }
2202
2203 // Return null for empty list.
2204 if (Ivars.empty())
2205 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2206
2207 std::vector<llvm::Constant*> Values(2);
2208 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2209 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2210 Ivars.size());
2211 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2212 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2213
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002214 llvm::GlobalVariable *GV;
2215 if (ForClass)
2216 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002217 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2218 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002219 else
2220 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2221 + ID->getNameAsString(),
2222 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002223 4, true);
2224 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002225}
2226
2227/*
2228 struct objc_method {
2229 SEL method_name;
2230 char *method_types;
2231 void *method;
2232 };
2233
2234 struct objc_method_list {
2235 struct objc_method_list *obsolete;
2236 int count;
2237 struct objc_method methods_list[count];
2238 };
2239*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002240
2241/// GetMethodConstant - Return a struct objc_method constant for the
2242/// given method if it has been defined. The result is null if the
2243/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002244llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002245 // FIXME: Use DenseMap::lookup
2246 llvm::Function *Fn = MethodDefinitions[MD];
2247 if (!Fn)
2248 return 0;
2249
2250 std::vector<llvm::Constant*> Method(3);
2251 Method[0] =
2252 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2253 ObjCTypes.SelectorPtrTy);
2254 Method[1] = GetMethodVarType(MD);
2255 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2256 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2257}
2258
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002259llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2260 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002261 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002262 // Return null for empty list.
2263 if (Methods.empty())
2264 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2265
2266 std::vector<llvm::Constant*> Values(3);
2267 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2268 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2269 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2270 Methods.size());
2271 Values[2] = llvm::ConstantArray::get(AT, Methods);
2272 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2273
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002274 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002275 return llvm::ConstantExpr::getBitCast(GV,
2276 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002277}
2278
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002279llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002280 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002281 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002282 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002283
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002284 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002285 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002286 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002287 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002288 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002289 llvm::GlobalValue::InternalLinkage,
2290 Name,
2291 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002292 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002293
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002294 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002295}
2296
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002297llvm::GlobalVariable *
2298CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2299 llvm::Constant *Init,
2300 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002301 unsigned Align,
2302 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002303 const llvm::Type *Ty = Init->getType();
2304 llvm::GlobalVariable *GV =
2305 new llvm::GlobalVariable(Ty, false,
2306 llvm::GlobalValue::InternalLinkage,
2307 Init,
2308 Name,
2309 &CGM.getModule());
2310 if (Section)
2311 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002312 if (Align)
2313 GV->setAlignment(Align);
2314 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002315 UsedGlobals.push_back(GV);
2316 return GV;
2317}
2318
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002319llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002320 // Abuse this interface function as a place to finalize.
2321 FinishModule();
2322
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002323 return NULL;
2324}
2325
Chris Lattner74391b42009-03-22 21:03:39 +00002326llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002327 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002328}
2329
Chris Lattner74391b42009-03-22 21:03:39 +00002330llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002331 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002332}
2333
Chris Lattner74391b42009-03-22 21:03:39 +00002334llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002335 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002336}
2337
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002338/*
2339
2340Objective-C setjmp-longjmp (sjlj) Exception Handling
2341--
2342
2343The basic framework for a @try-catch-finally is as follows:
2344{
2345 objc_exception_data d;
2346 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002347 bool _call_try_exit = true;
2348
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002349 objc_exception_try_enter(&d);
2350 if (!setjmp(d.jmp_buf)) {
2351 ... try body ...
2352 } else {
2353 // exception path
2354 id _caught = objc_exception_extract(&d);
2355
2356 // enter new try scope for handlers
2357 if (!setjmp(d.jmp_buf)) {
2358 ... match exception and execute catch blocks ...
2359
2360 // fell off end, rethrow.
2361 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002362 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002363 } else {
2364 // exception in catch block
2365 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002366 _call_try_exit = false;
2367 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002368 }
2369 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002370 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002371
2372finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002373 if (_call_try_exit)
2374 objc_exception_try_exit(&d);
2375
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002376 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002377 ... dispatch to finally destination ...
2378
2379finally_rethrow:
2380 objc_exception_throw(_rethrow);
2381
2382finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002383}
2384
2385This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002386uses _rethrow to determine if objc_exception_try_exit should be called
2387and if the object should be rethrown. This breaks in the face of
2388throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002389
2390We specialize this framework for a few particular circumstances:
2391
2392 - If there are no catch blocks, then we avoid emitting the second
2393 exception handling context.
2394
2395 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2396 e)) we avoid emitting the code to rethrow an uncaught exception.
2397
2398 - FIXME: If there is no @finally block we can do a few more
2399 simplifications.
2400
2401Rethrows and Jumps-Through-Finally
2402--
2403
2404Support for implicit rethrows and jumping through the finally block is
2405handled by storing the current exception-handling context in
2406ObjCEHStack.
2407
Daniel Dunbar898d5082008-09-30 01:06:03 +00002408In order to implement proper @finally semantics, we support one basic
2409mechanism for jumping through the finally block to an arbitrary
2410destination. Constructs which generate exits from a @try or @catch
2411block use this mechanism to implement the proper semantics by chaining
2412jumps, as necessary.
2413
2414This mechanism works like the one used for indirect goto: we
2415arbitrarily assign an ID to each destination and store the ID for the
2416destination in a variable prior to entering the finally block. At the
2417end of the finally block we simply create a switch to the proper
2418destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002419
2420Code gen for @synchronized(expr) stmt;
2421Effectively generating code for:
2422objc_sync_enter(expr);
2423@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002424*/
2425
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002426void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2427 const Stmt &S) {
2428 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002429 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002430 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002431 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002432 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2433 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2434 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002435
2436 // For @synchronized, call objc_sync_enter(sync.expr). The
2437 // evaluation of the expression must occur before we enter the
2438 // @synchronized. We can safely avoid a temp here because jumps into
2439 // @synchronized are illegal & this will dominate uses.
2440 llvm::Value *SyncArg = 0;
2441 if (!isTry) {
2442 SyncArg =
2443 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2444 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002445 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002446 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002447
2448 // Push an EH context entry, used for handling rethrows and jumps
2449 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002450 CGF.PushCleanupBlock(FinallyBlock);
2451
Anders Carlsson273558f2009-02-07 21:37:21 +00002452 CGF.ObjCEHValueStack.push_back(0);
2453
Daniel Dunbar898d5082008-09-30 01:06:03 +00002454 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002455 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2456 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002457 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2458 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002459 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2460 "_call_try_exit");
2461 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2462
Anders Carlsson80f25672008-09-09 17:59:25 +00002463 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002464 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002465 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2466 "jmpbufarray");
2467 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002468 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002469 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002470
Daniel Dunbar55e87422008-11-11 02:29:29 +00002471 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2472 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002473 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002474 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002475
2476 // Emit the @try block.
2477 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002478 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2479 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002480 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002481
2482 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002483 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002484
2485 // Retrieve the exception object. We may emit multiple blocks but
2486 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002487 llvm::Value *Caught =
2488 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2489 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002490 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002491 if (!isTry)
2492 {
2493 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002494 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002495 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002496 }
2497 else if (const ObjCAtCatchStmt* CatchStmt =
2498 cast<ObjCAtTryStmt>(S).getCatchStmts())
2499 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002500 // Enter a new exception try block (in case a @catch block throws
2501 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002502 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002503
Chris Lattner34b02a12009-04-22 02:26:14 +00002504 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002505 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002506 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002507
Daniel Dunbar55e87422008-11-11 02:29:29 +00002508 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2509 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002510 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002511
2512 CGF.EmitBlock(CatchBlock);
2513
Daniel Dunbar55e40722008-09-27 07:03:52 +00002514 // Handle catch list. As a special case we check if everything is
2515 // matched and avoid generating code for falling off the end if
2516 // so.
2517 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002518 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002519 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002520
Steve Naroff7ba138a2009-03-03 19:52:17 +00002521 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002522 const PointerType *PT = 0;
2523
Anders Carlsson80f25672008-09-09 17:59:25 +00002524 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002525 if (!CatchParam) {
2526 AllMatched = true;
2527 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002528 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002529
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002530 // catch(id e) always matches.
2531 // FIXME: For the time being we also match id<X>; this should
2532 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002533 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002534 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002535 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002536 }
2537
Daniel Dunbar55e40722008-09-27 07:03:52 +00002538 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002539 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002540 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002541 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002542 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002543 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002544
Anders Carlssondde0a942008-09-11 09:15:33 +00002545 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002546 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002547 break;
2548 }
2549
Daniel Dunbar129271a2008-09-27 07:36:24 +00002550 assert(PT && "Unexpected non-pointer type in @catch");
2551 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002552 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002553 assert(ObjCType && "Catch parameter must have Objective-C type!");
2554
2555 // Check if the @catch block matches the exception object.
2556 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2557
Chris Lattner34b02a12009-04-22 02:26:14 +00002558 llvm::Value *Match =
2559 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2560 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002561
Daniel Dunbar55e87422008-11-11 02:29:29 +00002562 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002563
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002564 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002565 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002566
2567 // Emit the @catch block.
2568 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002569 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002570 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002571
2572 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002573 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002574 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002575 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002576
2577 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002578 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002579
2580 CGF.EmitBlock(NextCatchBlock);
2581 }
2582
Daniel Dunbar55e40722008-09-27 07:03:52 +00002583 if (!AllMatched) {
2584 // None of the handlers caught the exception, so store it to be
2585 // rethrown at the end of the @finally block.
2586 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002587 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002588 }
2589
2590 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002591 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002592 CGF.Builder.CreateStore(
2593 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2594 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002595 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002596 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002597 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002598 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002599 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002600 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002601 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002602 }
2603
Daniel Dunbar898d5082008-09-30 01:06:03 +00002604 // Pop the exception-handling stack entry. It is important to do
2605 // this now, because the code in the @finally block is not in this
2606 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002607 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2608
Anders Carlsson273558f2009-02-07 21:37:21 +00002609 CGF.ObjCEHValueStack.pop_back();
2610
Anders Carlsson80f25672008-09-09 17:59:25 +00002611 // Emit the @finally block.
2612 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002613 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2614
2615 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2616
2617 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002618 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002619
2620 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002621 if (isTry) {
2622 if (const ObjCAtFinallyStmt* FinallyStmt =
2623 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2624 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002625 } else {
2626 // Emit objc_sync_exit(expr); as finally's sole statement for
2627 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002628 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002629 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002630
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002631 // Emit the switch block
2632 if (Info.SwitchBlock)
2633 CGF.EmitBlock(Info.SwitchBlock);
2634 if (Info.EndBlock)
2635 CGF.EmitBlock(Info.EndBlock);
2636
Daniel Dunbar898d5082008-09-30 01:06:03 +00002637 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002638 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002639 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002640 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002641
2642 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002643}
2644
2645void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002646 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002647 llvm::Value *ExceptionAsObject;
2648
2649 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2650 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2651 ExceptionAsObject =
2652 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2653 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002654 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002655 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002656 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002657 }
2658
Chris Lattnerbbccd612009-04-22 02:38:11 +00002659 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002660 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002661
2662 // Clear the insertion point to indicate we are in unreachable code.
2663 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002664}
2665
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002666/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002667/// object: objc_read_weak (id *src)
2668///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002669llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002670 llvm::Value *AddrWeakObj)
2671{
Eli Friedman8339b352009-03-07 03:57:15 +00002672 const llvm::Type* DestTy =
2673 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002674 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002675 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002676 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002677 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002678 return read_weak;
2679}
2680
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002681/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2682/// objc_assign_weak (id src, id *dst)
2683///
2684void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2685 llvm::Value *src, llvm::Value *dst)
2686{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002687 const llvm::Type * SrcTy = src->getType();
2688 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002689 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002690 assert(Size <= 8 && "does not support size > 8");
2691 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2692 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002693 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2694 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002695 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2696 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002697 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002698 src, dst, "weakassign");
2699 return;
2700}
2701
Fariborz Jahanian58626502008-11-19 00:59:10 +00002702/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2703/// objc_assign_global (id src, id *dst)
2704///
2705void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2706 llvm::Value *src, llvm::Value *dst)
2707{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002708 const llvm::Type * SrcTy = src->getType();
2709 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002710 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002711 assert(Size <= 8 && "does not support size > 8");
2712 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2713 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002714 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2715 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002716 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2717 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002718 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002719 src, dst, "globalassign");
2720 return;
2721}
2722
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002723/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2724/// objc_assign_ivar (id src, id *dst)
2725///
2726void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2727 llvm::Value *src, llvm::Value *dst)
2728{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002729 const llvm::Type * SrcTy = src->getType();
2730 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002731 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002732 assert(Size <= 8 && "does not support size > 8");
2733 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2734 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002735 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2736 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002737 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2738 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002739 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002740 src, dst, "assignivar");
2741 return;
2742}
2743
Fariborz Jahanian58626502008-11-19 00:59:10 +00002744/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2745/// objc_assign_strongCast (id src, id *dst)
2746///
2747void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2748 llvm::Value *src, llvm::Value *dst)
2749{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002750 const llvm::Type * SrcTy = src->getType();
2751 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002752 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002753 assert(Size <= 8 && "does not support size > 8");
2754 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2755 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002756 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2757 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002758 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2759 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002760 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002761 src, dst, "weakassign");
2762 return;
2763}
2764
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002765/// EmitObjCValueForIvar - Code Gen for ivar reference.
2766///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002767LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2768 QualType ObjectTy,
2769 llvm::Value *BaseValue,
2770 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002771 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002772 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002773 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2774 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002775}
2776
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002777llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002778 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002779 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002780 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002781 return llvm::ConstantInt::get(
2782 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2783 Offset);
2784}
2785
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002786/* *** Private Interface *** */
2787
2788/// EmitImageInfo - Emit the image info marker used to encode some module
2789/// level information.
2790///
2791/// See: <rdr://4810609&4810587&4810587>
2792/// struct IMAGE_INFO {
2793/// unsigned version;
2794/// unsigned flags;
2795/// };
2796enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002797 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2798 // this implies.
2799 eImageInfo_GarbageCollected = (1 << 1),
2800 eImageInfo_GCOnly = (1 << 2),
2801 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2802
2803 // A flag indicating that the module has no instances of an
2804 // @synthesize of a superclass variable. <rdar://problem/6803242>
2805 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002806};
2807
2808void CGObjCMac::EmitImageInfo() {
2809 unsigned version = 0; // Version is unused?
2810 unsigned flags = 0;
2811
2812 // FIXME: Fix and continue?
2813 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2814 flags |= eImageInfo_GarbageCollected;
2815 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2816 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002817
2818 // We never allow @synthesize of a superclass property.
2819 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002820
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002821 // Emitted as int[2];
2822 llvm::Constant *values[2] = {
2823 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2824 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2825 };
2826 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002827
2828 const char *Section;
2829 if (ObjCABI == 1)
2830 Section = "__OBJC, __image_info,regular";
2831 else
2832 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002833 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002834 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2835 llvm::ConstantArray::get(AT, values, 2),
2836 Section,
2837 0,
2838 true);
2839 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002840}
2841
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002842
2843// struct objc_module {
2844// unsigned long version;
2845// unsigned long size;
2846// const char *name;
2847// Symtab symtab;
2848// };
2849
2850// FIXME: Get from somewhere
2851static const int ModuleVersion = 7;
2852
2853void CGObjCMac::EmitModuleInfo() {
Duncan Sands9408c452009-05-09 07:08:47 +00002854 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002855
2856 std::vector<llvm::Constant*> Values(4);
2857 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2858 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002859 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002860 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002861 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002862 CreateMetadataVar("\01L_OBJC_MODULES",
2863 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2864 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002865 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002866}
2867
2868llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002869 unsigned NumClasses = DefinedClasses.size();
2870 unsigned NumCategories = DefinedCategories.size();
2871
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002872 // Return null if no symbols were defined.
2873 if (!NumClasses && !NumCategories)
2874 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2875
2876 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002877 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2878 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2879 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2880 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2881
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002882 // The runtime expects exactly the list of defined classes followed
2883 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002884 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002885 for (unsigned i=0; i<NumClasses; i++)
2886 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2887 ObjCTypes.Int8PtrTy);
2888 for (unsigned i=0; i<NumCategories; i++)
2889 Symbols[NumClasses + i] =
2890 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2891 ObjCTypes.Int8PtrTy);
2892
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002893 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002894 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002895 NumClasses + NumCategories),
2896 Symbols);
2897
2898 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2899
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002900 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002901 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2902 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002903 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002904 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2905}
2906
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002907llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002908 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002909 LazySymbols.insert(ID->getIdentifier());
2910
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002911 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2912
2913 if (!Entry) {
2914 llvm::Constant *Casted =
2915 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2916 ObjCTypes.ClassPtrTy);
2917 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002918 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2919 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002920 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002921 }
2922
2923 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002924}
2925
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002926llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002927 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2928
2929 if (!Entry) {
2930 llvm::Constant *Casted =
2931 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2932 ObjCTypes.SelectorPtrTy);
2933 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002934 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2935 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002936 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002937 }
2938
2939 return Builder.CreateLoad(Entry, false, "tmp");
2940}
2941
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002942llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002943 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002944
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002945 if (!Entry)
2946 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2947 llvm::ConstantArray::get(Ident->getName()),
2948 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002949 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002950
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002951 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002952}
2953
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002954/// GetIvarLayoutName - Returns a unique constant for the given
2955/// ivar layout bitmap.
2956llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2957 const ObjCCommonTypesHelper &ObjCTypes) {
2958 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2959}
2960
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002961static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2962 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002963 if (FQT.isObjCGCStrong())
2964 return QualType::Strong;
2965
2966 if (FQT.isObjCGCWeak())
2967 return QualType::Weak;
2968
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002969 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002970 return QualType::Strong;
2971
2972 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002973 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002974
2975 return QualType::GCNone;
2976}
2977
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002978void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2979 unsigned int BytePos,
2980 bool ForStrongLayout,
2981 bool &HasUnion) {
2982 const RecordDecl *RD = RT->getDecl();
2983 // FIXME - Use iterator.
2984 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2985 RD->field_end(CGM.getContext()));
2986 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2987 const llvm::StructLayout *RecLayout =
2988 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2989
2990 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
2991 ForStrongLayout, HasUnion);
2992}
2993
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00002994void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002995 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002996 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002997 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002998 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002999 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003000 bool IsUnion = (RD && RD->isUnion());
3001 uint64_t MaxUnionIvarSize = 0;
3002 uint64_t MaxSkippedUnionIvarSize = 0;
3003 FieldDecl *MaxField = 0;
3004 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003005 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003006 uint64_t MaxFieldOffset = 0;
3007 uint64_t MaxSkippedFieldOffset = 0;
3008 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003009
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003010 if (RecFields.empty())
3011 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00003012 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
3013 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3014
Chris Lattnerf1690852009-03-31 08:48:01 +00003015 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003016 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00003017 uint64_t FieldOffset;
3018 if (RD)
3019 FieldOffset =
3020 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3021 else
3022 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003023
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003024 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003025 if (!Field->getIdentifier() || Field->isBitField()) {
3026 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003027 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003028 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003029 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003030
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003031 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003032 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003033 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003034 if (FQT->isUnionType())
3035 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003036
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003037 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003038 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003039 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003040 continue;
3041 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003042
3043 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003044 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003045 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003046 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003047 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003048 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003049 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3050 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003051 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003052 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003053 FQT = CArray->getElementType();
3054 }
3055
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003056 assert(!FQT->isUnionType() &&
3057 "layout for array of unions not supported");
3058 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003059 int OldIndex = IvarsInfo.size() - 1;
3060 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003061
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003062 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003063 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003064 ForStrongLayout, HasUnion);
3065
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003066 // Replicate layout information for each array element. Note that
3067 // one element is already done.
3068 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003069 for (int FirstIndex = IvarsInfo.size() - 1,
3070 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003071 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003072 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3073 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3074 IvarsInfo[i].ivar_size));
3075 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3076 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3077 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003078 }
3079 continue;
3080 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003081 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003082 // At this point, we are done with Record/Union and array there of.
3083 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003084 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003085
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003086 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003087 if ((ForStrongLayout && GCAttr == QualType::Strong)
3088 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003089 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003090 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003091 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003092 MaxUnionIvarSize = UnionIvarSize;
3093 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003094 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003095 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003096 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003097 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003098 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003099 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003100 } else if ((ForStrongLayout &&
3101 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3102 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3103 if (IsUnion) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00003104 // FIXME: Why the asymmetry? We divide by word size in bits on other
3105 // side.
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003106 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003107 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003108 MaxSkippedUnionIvarSize = UnionIvarSize;
3109 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003110 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003111 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003112 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003113 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003114 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003115 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003116 }
3117 }
3118 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003119
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003120 if (LastFieldBitfield) {
3121 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003122 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3123 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003124 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003125 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003126 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003127 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3128 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003129 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003130 }
3131
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003132 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003133 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003134 MaxUnionIvarSize));
3135 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003136 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003137 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003138}
3139
3140/// BuildIvarLayout - Builds ivar layout bitmap for the class
3141/// implementation for the __strong or __weak case.
3142/// The layout map displays which words in ivar list must be skipped
3143/// and which must be scanned by GC (see below). String is built of bytes.
3144/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3145/// of words to skip and right nibble is count of words to scan. So, each
3146/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3147/// represented by a 0x00 byte which also ends the string.
3148/// 1. when ForStrongLayout is true, following ivars are scanned:
3149/// - id, Class
3150/// - object *
3151/// - __strong anything
3152///
3153/// 2. When ForStrongLayout is false, following ivars are scanned:
3154/// - __weak anything
3155///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003156llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003157 const ObjCImplementationDecl *OMD,
3158 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003159 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003160
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003161 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003162 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3163 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3164 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003165
Chris Lattnerf1690852009-03-31 08:48:01 +00003166 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003167 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003168 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian98200742009-05-12 18:14:29 +00003169
Daniel Dunbar37153282009-05-04 04:10:48 +00003170 // Add this implementations synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +00003171 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3172 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3173 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3174 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3175
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003176 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003177 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003178
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003179 SkipIvars.clear();
3180 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003181
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003182 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003183 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003184 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003185
3186 // Sort on byte position in case we encounterred a union nested in
3187 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003188 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003189 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003190 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003191 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003192
3193 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003194 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003195 unsigned int WordSize =
Duncan Sands9408c452009-05-09 07:08:47 +00003196 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003197 if (IvarsInfo[0].ivar_bytepos == 0) {
3198 WordsToSkip = 0;
3199 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003200 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003201 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3202 WordsToScan = IvarsInfo[0].ivar_size;
3203 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003204 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003205 unsigned int TailPrevGCObjC =
3206 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003207 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003208 // consecutive 'scanned' object pointers.
3209 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003210 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003211 // Skip over 'gc'able object pointer which lay over each other.
3212 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3213 continue;
3214 // Must skip over 1 or more words. We save current skip/scan values
3215 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003216 SKIP_SCAN SkScan;
3217 SkScan.skip = WordsToSkip;
3218 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003219 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003220
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003221 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003222 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3223 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003224 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003225 WordsToSkip = 0;
3226 WordsToScan = IvarsInfo[i].ivar_size;
3227 }
3228 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003229 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003230 SKIP_SCAN SkScan;
3231 SkScan.skip = WordsToSkip;
3232 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003233 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003234 }
3235
3236 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003237 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003238 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003239 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003240 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3241 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003242 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003243 IvarsInfo[LastIndex].ivar_bytepos +
3244 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003245 BytesSkipped = (LastByteSkipped > LastByteScanned);
3246 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003247 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003248 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003249 SKIP_SCAN SkScan;
3250 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3251 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003252 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003253 }
3254 }
3255 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3256 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003257 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003258 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003259 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3260 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3261 // 0xM0 followed by 0x0N detected.
3262 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3263 for (int j = i+1; j < SkipScan; j++)
3264 SkipScanIvars[j] = SkipScanIvars[j+1];
3265 --SkipScan;
3266 }
3267 }
3268
3269 // Generate the string.
3270 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003271 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003272 unsigned char byte;
3273 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3274 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3275 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3276 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3277
3278 if (skip_small > 0 || skip_big > 0)
3279 BytesSkipped = true;
3280 // first skip big.
3281 for (unsigned int ix = 0; ix < skip_big; ix++)
3282 BitMap += (unsigned char)(0xf0);
3283
3284 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003285 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003286 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003287 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003288 byte |= 0xf;
3289 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003290 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003291 byte |= scan_small;
3292 scan_small = 0;
3293 }
3294 BitMap += byte;
3295 }
3296 // next scan big
3297 for (unsigned int ix = 0; ix < scan_big; ix++)
3298 BitMap += (unsigned char)(0x0f);
3299 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003300 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003301 byte = scan_small;
3302 BitMap += byte;
3303 }
3304 }
3305 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003306 unsigned char zero = 0;
3307 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003308
3309 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3310 printf("\n%s ivar layout for class '%s': ",
3311 ForStrongLayout ? "strong" : "weak",
3312 OMD->getClassInterface()->getNameAsCString());
3313 const unsigned char *s = (unsigned char*)BitMap.c_str();
3314 for (unsigned i = 0; i < BitMap.size(); i++)
3315 if (!(s[i] & 0xf0))
3316 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3317 else
3318 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3319 printf("\n");
3320 }
3321
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003322 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3323 // final layout.
3324 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003325 return llvm::Constant::getNullValue(PtrTy);
3326 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3327 llvm::ConstantArray::get(BitMap.c_str()),
3328 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003329 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003330 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003331}
3332
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003333llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003334 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3335
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003336 // FIXME: Avoid std::string copying.
3337 if (!Entry)
3338 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3339 llvm::ConstantArray::get(Sel.getAsString()),
3340 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003341 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003342
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003343 return getConstantGEP(Entry, 0, 0);
3344}
3345
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003346// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003347llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003348 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3349}
3350
3351// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003352llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003353 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3354}
3355
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003356llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003357 std::string TypeStr;
3358 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3359
3360 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003361
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003362 if (!Entry)
3363 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3364 llvm::ConstantArray::get(TypeStr),
3365 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003366 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003367
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003368 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003369}
3370
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003371llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003372 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003373 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3374 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003375
3376 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3377
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003378 if (!Entry)
3379 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3380 llvm::ConstantArray::get(TypeStr),
3381 "__TEXT,__cstring,cstring_literals",
3382 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003383
3384 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003385}
3386
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003387// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003388llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003389 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3390
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003391 if (!Entry)
3392 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3393 llvm::ConstantArray::get(Ident->getName()),
3394 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003395 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003396
3397 return getConstantGEP(Entry, 0, 0);
3398}
3399
3400// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003401// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003402llvm::Constant *
3403 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3404 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003405 std::string TypeStr;
3406 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003407 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3408}
3409
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003410void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3411 const ObjCContainerDecl *CD,
3412 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003413 NameOut = '\01';
3414 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003415 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003416 assert (CD && "Missing container decl in GetNameForMethod");
3417 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003418 if (const ObjCCategoryImplDecl *CID =
3419 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3420 NameOut += '(';
3421 NameOut += CID->getNameAsString();
3422 NameOut+= ')';
3423 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003424 NameOut += ' ';
3425 NameOut += D->getSelector().getAsString();
3426 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003427}
3428
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003429void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003430 EmitModuleInfo();
3431
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003432 // Emit the dummy bodies for any protocols which were referenced but
3433 // never defined.
3434 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3435 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3436 if (i->second->hasInitializer())
3437 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003438
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003439 std::vector<llvm::Constant*> Values(5);
3440 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3441 Values[1] = GetClassName(i->first);
3442 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3443 Values[3] = Values[4] =
3444 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3445 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3446 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3447 Values));
3448 }
3449
3450 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003451 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003452 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003453 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003454 }
3455
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003456 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003457 llvm::GlobalValue *GV =
3458 new llvm::GlobalVariable(AT, false,
3459 llvm::GlobalValue::AppendingLinkage,
3460 llvm::ConstantArray::get(AT, Used),
3461 "llvm.used",
3462 &CGM.getModule());
3463
3464 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003465
3466 // Add assembler directives to add lazy undefined symbol references
3467 // for classes which are referenced but not defined. This is
3468 // important for correct linker interaction.
3469
3470 // FIXME: Uh, this isn't particularly portable.
3471 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003472
3473 if (!CGM.getModule().getModuleInlineAsm().empty())
3474 s << "\n";
3475
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003476 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3477 e = LazySymbols.end(); i != e; ++i) {
3478 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3479 }
3480 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3481 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003482 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003483 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3484 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003485
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003486 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003487}
3488
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003489CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003490 : CGObjCCommonMac(cgm),
3491 ObjCTypes(cgm)
3492{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003493 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003494 ObjCABI = 2;
3495}
3496
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003497/* *** */
3498
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003499ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3500: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003501{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003502 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3503 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003504
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003505 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003506 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003507 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003508 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003509 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3510
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003511 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003512 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003513 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003514
Mike Stumpf5408fe2009-05-16 07:57:57 +00003515 // FIXME: It would be nice to unify this with the opaque type, so that the IR
3516 // comes out a bit cleaner.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003517 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3518 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003519
3520 // I'm not sure I like this. The implicit coordination is a bit
3521 // gross. We should solve this in a reasonable fashion because this
3522 // is a pretty common task (match some runtime data structure with
3523 // an LLVM data structure).
3524
3525 // FIXME: This is leaked.
3526 // FIXME: Merge with rewriter code?
3527
3528 // struct _objc_super {
3529 // id self;
3530 // Class cls;
3531 // }
3532 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3533 SourceLocation(),
3534 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003535 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3536 Ctx.getObjCIdType(), 0, false));
3537 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3538 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003539 RD->completeDefinition(Ctx);
3540
3541 SuperCTy = Ctx.getTagDeclType(RD);
3542 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3543
3544 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003545 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3546
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003547 // struct _prop_t {
3548 // char *name;
3549 // char *attributes;
3550 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003551 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003552 CGM.getModule().addTypeName("struct._prop_t",
3553 PropertyTy);
3554
3555 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003556 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003557 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003558 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003559 // }
3560 PropertyListTy = llvm::StructType::get(IntTy,
3561 IntTy,
3562 llvm::ArrayType::get(PropertyTy, 0),
3563 NULL);
3564 CGM.getModule().addTypeName("struct._prop_list_t",
3565 PropertyListTy);
3566 // struct _prop_list_t *
3567 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3568
3569 // struct _objc_method {
3570 // SEL _cmd;
3571 // char *method_type;
3572 // char *_imp;
3573 // }
3574 MethodTy = llvm::StructType::get(SelectorPtrTy,
3575 Int8PtrTy,
3576 Int8PtrTy,
3577 NULL);
3578 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003579
3580 // struct _objc_cache *
3581 CacheTy = llvm::OpaqueType::get();
3582 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3583 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003584}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003585
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003586ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3587 : ObjCCommonTypesHelper(cgm)
3588{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003589 // struct _objc_method_description {
3590 // SEL name;
3591 // char *types;
3592 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003593 MethodDescriptionTy =
3594 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003595 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003596 NULL);
3597 CGM.getModule().addTypeName("struct._objc_method_description",
3598 MethodDescriptionTy);
3599
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003600 // struct _objc_method_description_list {
3601 // int count;
3602 // struct _objc_method_description[1];
3603 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003604 MethodDescriptionListTy =
3605 llvm::StructType::get(IntTy,
3606 llvm::ArrayType::get(MethodDescriptionTy, 0),
3607 NULL);
3608 CGM.getModule().addTypeName("struct._objc_method_description_list",
3609 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003610
3611 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003612 MethodDescriptionListPtrTy =
3613 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3614
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003615 // Protocol description structures
3616
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003617 // struct _objc_protocol_extension {
3618 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3619 // struct _objc_method_description_list *optional_instance_methods;
3620 // struct _objc_method_description_list *optional_class_methods;
3621 // struct _objc_property_list *instance_properties;
3622 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003623 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003624 llvm::StructType::get(IntTy,
3625 MethodDescriptionListPtrTy,
3626 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003627 PropertyListPtrTy,
3628 NULL);
3629 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3630 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003631
3632 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003633 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3634
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003635 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003636
3637 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3638 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3639
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003640 const llvm::Type *T =
3641 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3642 LongTy,
3643 llvm::ArrayType::get(ProtocolTyHolder, 0),
3644 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003645 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3646
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003647 // struct _objc_protocol {
3648 // struct _objc_protocol_extension *isa;
3649 // char *protocol_name;
3650 // struct _objc_protocol **_objc_protocol_list;
3651 // struct _objc_method_description_list *instance_methods;
3652 // struct _objc_method_description_list *class_methods;
3653 // }
3654 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003655 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003656 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3657 MethodDescriptionListPtrTy,
3658 MethodDescriptionListPtrTy,
3659 NULL);
3660 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3661
3662 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3663 CGM.getModule().addTypeName("struct._objc_protocol_list",
3664 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003665 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003666 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3667
3668 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003669 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003670 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003671
3672 // Class description structures
3673
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003674 // struct _objc_ivar {
3675 // char *ivar_name;
3676 // char *ivar_type;
3677 // int ivar_offset;
3678 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003679 IvarTy = llvm::StructType::get(Int8PtrTy,
3680 Int8PtrTy,
3681 IntTy,
3682 NULL);
3683 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3684
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003685 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003686 IvarListTy = llvm::OpaqueType::get();
3687 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3688 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3689
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003690 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003691 MethodListTy = llvm::OpaqueType::get();
3692 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3693 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3694
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003695 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003696 ClassExtensionTy =
3697 llvm::StructType::get(IntTy,
3698 Int8PtrTy,
3699 PropertyListPtrTy,
3700 NULL);
3701 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3702 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3703
3704 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3705
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003706 // struct _objc_class {
3707 // Class isa;
3708 // Class super_class;
3709 // char *name;
3710 // long version;
3711 // long info;
3712 // long instance_size;
3713 // struct _objc_ivar_list *ivars;
3714 // struct _objc_method_list *methods;
3715 // struct _objc_cache *cache;
3716 // struct _objc_protocol_list *protocols;
3717 // char *ivar_layout;
3718 // struct _objc_class_ext *ext;
3719 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003720 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3721 llvm::PointerType::getUnqual(ClassTyHolder),
3722 Int8PtrTy,
3723 LongTy,
3724 LongTy,
3725 LongTy,
3726 IvarListPtrTy,
3727 MethodListPtrTy,
3728 CachePtrTy,
3729 ProtocolListPtrTy,
3730 Int8PtrTy,
3731 ClassExtensionPtrTy,
3732 NULL);
3733 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3734
3735 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3736 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3737 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3738
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003739 // struct _objc_category {
3740 // char *category_name;
3741 // char *class_name;
3742 // struct _objc_method_list *instance_method;
3743 // struct _objc_method_list *class_method;
3744 // uint32_t size; // sizeof(struct _objc_category)
3745 // struct _objc_property_list *instance_properties;// category's @property
3746 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003747 CategoryTy = llvm::StructType::get(Int8PtrTy,
3748 Int8PtrTy,
3749 MethodListPtrTy,
3750 MethodListPtrTy,
3751 ProtocolListPtrTy,
3752 IntTy,
3753 PropertyListPtrTy,
3754 NULL);
3755 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3756
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003757 // Global metadata structures
3758
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003759 // struct _objc_symtab {
3760 // long sel_ref_cnt;
3761 // SEL *refs;
3762 // short cls_def_cnt;
3763 // short cat_def_cnt;
3764 // char *defs[cls_def_cnt + cat_def_cnt];
3765 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003766 SymtabTy = llvm::StructType::get(LongTy,
3767 SelectorPtrTy,
3768 ShortTy,
3769 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003770 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003771 NULL);
3772 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3773 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3774
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003775 // struct _objc_module {
3776 // long version;
3777 // long size; // sizeof(struct _objc_module)
3778 // char *name;
3779 // struct _objc_symtab* symtab;
3780 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003781 ModuleTy =
3782 llvm::StructType::get(LongTy,
3783 LongTy,
3784 Int8PtrTy,
3785 SymtabPtrTy,
3786 NULL);
3787 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003788
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003789
Mike Stumpf5408fe2009-05-16 07:57:57 +00003790 // FIXME: This is the size of the setjmp buffer and should be target
3791 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson124526b2008-09-09 10:10:21 +00003792 uint64_t SetJmpBufferSize = 18;
3793
3794 // Exceptions
3795 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003796 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003797
3798 ExceptionDataTy =
3799 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3800 SetJmpBufferSize),
3801 StackPtrTy, NULL);
3802 CGM.getModule().addTypeName("struct._objc_exception_data",
3803 ExceptionDataTy);
3804
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003805}
3806
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003807ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003808: ObjCCommonTypesHelper(cgm)
3809{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003810 // struct _method_list_t {
3811 // uint32_t entsize; // sizeof(struct _objc_method)
3812 // uint32_t method_count;
3813 // struct _objc_method method_list[method_count];
3814 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003815 MethodListnfABITy = llvm::StructType::get(IntTy,
3816 IntTy,
3817 llvm::ArrayType::get(MethodTy, 0),
3818 NULL);
3819 CGM.getModule().addTypeName("struct.__method_list_t",
3820 MethodListnfABITy);
3821 // struct method_list_t *
3822 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003823
3824 // struct _protocol_t {
3825 // id isa; // NULL
3826 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003827 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003828 // const struct method_list_t * const instance_methods;
3829 // const struct method_list_t * const class_methods;
3830 // const struct method_list_t *optionalInstanceMethods;
3831 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003832 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003833 // const uint32_t size; // sizeof(struct _protocol_t)
3834 // const uint32_t flags; // = 0
3835 // }
3836
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003837 // Holder for struct _protocol_list_t *
3838 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3839
3840 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3841 Int8PtrTy,
3842 llvm::PointerType::getUnqual(
3843 ProtocolListTyHolder),
3844 MethodListnfABIPtrTy,
3845 MethodListnfABIPtrTy,
3846 MethodListnfABIPtrTy,
3847 MethodListnfABIPtrTy,
3848 PropertyListPtrTy,
3849 IntTy,
3850 IntTy,
3851 NULL);
3852 CGM.getModule().addTypeName("struct._protocol_t",
3853 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003854
3855 // struct _protocol_t*
3856 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003857
Fariborz Jahanianda320092009-01-29 19:24:30 +00003858 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003859 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003860 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003861 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003862 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3863 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003864 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003865 NULL);
3866 CGM.getModule().addTypeName("struct._objc_protocol_list",
3867 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003868 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3869 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003870
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003871 // struct _objc_protocol_list*
3872 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003873
3874 // struct _ivar_t {
3875 // unsigned long int *offset; // pointer to ivar offset location
3876 // char *name;
3877 // char *type;
3878 // uint32_t alignment;
3879 // uint32_t size;
3880 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003881 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3882 Int8PtrTy,
3883 Int8PtrTy,
3884 IntTy,
3885 IntTy,
3886 NULL);
3887 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3888
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003889 // struct _ivar_list_t {
3890 // uint32 entsize; // sizeof(struct _ivar_t)
3891 // uint32 count;
3892 // struct _iver_t list[count];
3893 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003894 IvarListnfABITy = llvm::StructType::get(IntTy,
3895 IntTy,
3896 llvm::ArrayType::get(
3897 IvarnfABITy, 0),
3898 NULL);
3899 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3900
3901 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003902
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003903 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003904 // uint32_t const flags;
3905 // uint32_t const instanceStart;
3906 // uint32_t const instanceSize;
3907 // uint32_t const reserved; // only when building for 64bit targets
3908 // const uint8_t * const ivarLayout;
3909 // const char *const name;
3910 // const struct _method_list_t * const baseMethods;
3911 // const struct _objc_protocol_list *const baseProtocols;
3912 // const struct _ivar_list_t *const ivars;
3913 // const uint8_t * const weakIvarLayout;
3914 // const struct _prop_list_t * const properties;
3915 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003916
3917 // FIXME. Add 'reserved' field in 64bit abi mode!
3918 ClassRonfABITy = llvm::StructType::get(IntTy,
3919 IntTy,
3920 IntTy,
3921 Int8PtrTy,
3922 Int8PtrTy,
3923 MethodListnfABIPtrTy,
3924 ProtocolListnfABIPtrTy,
3925 IvarListnfABIPtrTy,
3926 Int8PtrTy,
3927 PropertyListPtrTy,
3928 NULL);
3929 CGM.getModule().addTypeName("struct._class_ro_t",
3930 ClassRonfABITy);
3931
3932 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3933 std::vector<const llvm::Type*> Params;
3934 Params.push_back(ObjectPtrTy);
3935 Params.push_back(SelectorPtrTy);
3936 ImpnfABITy = llvm::PointerType::getUnqual(
3937 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3938
3939 // struct _class_t {
3940 // struct _class_t *isa;
3941 // struct _class_t * const superclass;
3942 // void *cache;
3943 // IMP *vtable;
3944 // struct class_ro_t *ro;
3945 // }
3946
3947 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3948 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3949 llvm::PointerType::getUnqual(ClassTyHolder),
3950 CachePtrTy,
3951 llvm::PointerType::getUnqual(ImpnfABITy),
3952 llvm::PointerType::getUnqual(
3953 ClassRonfABITy),
3954 NULL);
3955 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3956
3957 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3958 ClassnfABITy);
3959
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003960 // LLVM for struct _class_t *
3961 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3962
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003963 // struct _category_t {
3964 // const char * const name;
3965 // struct _class_t *const cls;
3966 // const struct _method_list_t * const instance_methods;
3967 // const struct _method_list_t * const class_methods;
3968 // const struct _protocol_list_t * const protocols;
3969 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003970 // }
3971 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003972 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003973 MethodListnfABIPtrTy,
3974 MethodListnfABIPtrTy,
3975 ProtocolListnfABIPtrTy,
3976 PropertyListPtrTy,
3977 NULL);
3978 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003979
3980 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003981 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3982 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003983
3984 // MessageRefTy - LLVM for:
3985 // struct _message_ref_t {
3986 // IMP messenger;
3987 // SEL name;
3988 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003989
3990 // First the clang type for struct _message_ref_t
3991 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3992 SourceLocation(),
3993 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003994 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3995 Ctx.VoidPtrTy, 0, false));
3996 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3997 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003998 RD->completeDefinition(Ctx);
3999
4000 MessageRefCTy = Ctx.getTagDeclType(RD);
4001 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
4002 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00004003
4004 // MessageRefPtrTy - LLVM for struct _message_ref_t*
4005 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4006
4007 // SuperMessageRefTy - LLVM for:
4008 // struct _super_message_ref_t {
4009 // SUPER_IMP messenger;
4010 // SEL name;
4011 // };
4012 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4013 SelectorPtrTy,
4014 NULL);
4015 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4016
4017 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4018 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4019
Daniel Dunbare588b992009-03-01 04:46:24 +00004020
4021 // struct objc_typeinfo {
4022 // const void** vtable; // objc_ehtype_vtable + 2
4023 // const char* name; // c++ typeinfo string
4024 // Class cls;
4025 // };
4026 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4027 Int8PtrTy,
4028 ClassnfABIPtrTy,
4029 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004030 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004031 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004032}
4033
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004034llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4035 FinishNonFragileABIModule();
4036
4037 return NULL;
4038}
4039
Daniel Dunbar463b8762009-05-15 21:48:48 +00004040void CGObjCNonFragileABIMac::AddModuleClassList(const
4041 std::vector<llvm::GlobalValue*>
4042 &Container,
4043 const char *SymbolName,
4044 const char *SectionName) {
4045 unsigned NumClasses = Container.size();
4046
4047 if (!NumClasses)
4048 return;
4049
4050 std::vector<llvm::Constant*> Symbols(NumClasses);
4051 for (unsigned i=0; i<NumClasses; i++)
4052 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4053 ObjCTypes.Int8PtrTy);
4054 llvm::Constant* Init =
4055 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4056 NumClasses),
4057 Symbols);
4058
4059 llvm::GlobalVariable *GV =
4060 new llvm::GlobalVariable(Init->getType(), false,
4061 llvm::GlobalValue::InternalLinkage,
4062 Init,
4063 SymbolName,
4064 &CGM.getModule());
4065 GV->setAlignment(8);
4066 GV->setSection(SectionName);
4067 UsedGlobals.push_back(GV);
4068}
4069
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004070void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4071 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004072
Daniel Dunbar463b8762009-05-15 21:48:48 +00004073 // Build list of all implemented class addresses in array
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004074 // L_OBJC_LABEL_CLASS_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004075 AddModuleClassList(DefinedClasses,
4076 "\01L_OBJC_LABEL_CLASS_$",
4077 "__DATA, __objc_classlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004078 AddModuleClassList(DefinedNonLazyClasses,
4079 "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
4080 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004081
4082 // Build list of all implemented category addresses in array
4083 // L_OBJC_LABEL_CATEGORY_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004084 AddModuleClassList(DefinedCategories,
4085 "\01L_OBJC_LABEL_CATEGORY_$",
4086 "__DATA, __objc_catlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004087 AddModuleClassList(DefinedNonLazyCategories,
4088 "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
4089 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004090
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004091 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4092 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4093 std::vector<llvm::Constant*> Values(2);
4094 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004095 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004096 // FIXME: Fix and continue?
4097 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4098 flags |= eImageInfo_GarbageCollected;
4099 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4100 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004101 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004102 llvm::Constant* Init = llvm::ConstantArray::get(
4103 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4104 Values);
4105 llvm::GlobalVariable *IMGV =
4106 new llvm::GlobalVariable(Init->getType(), false,
4107 llvm::GlobalValue::InternalLinkage,
4108 Init,
4109 "\01L_OBJC_IMAGE_INFO",
4110 &CGM.getModule());
4111 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004112 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004113 UsedGlobals.push_back(IMGV);
4114
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004115 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004116
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004117 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4118 e = UsedGlobals.end(); i != e; ++i) {
4119 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4120 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004121
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004122 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4123 llvm::GlobalValue *GV =
4124 new llvm::GlobalVariable(AT, false,
4125 llvm::GlobalValue::AppendingLinkage,
4126 llvm::ConstantArray::get(AT, Used),
4127 "llvm.used",
4128 &CGM.getModule());
4129
4130 GV->setSection("llvm.metadata");
4131
4132}
4133
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004134/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004135/// NonLegacyDispatchMethods; false otherwise. What this means is that
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004136/// except for the 19 selectors in the list, we generate 32bit-style
4137/// message dispatch call for all the rest.
4138///
4139bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004140 if (NonLegacyDispatchMethods.empty()) {
4141 NonLegacyDispatchMethods.insert(GetNullarySelector("alloc"));
4142 NonLegacyDispatchMethods.insert(GetNullarySelector("class"));
4143 NonLegacyDispatchMethods.insert(GetNullarySelector("self"));
4144 NonLegacyDispatchMethods.insert(GetNullarySelector("isFlipped"));
4145 NonLegacyDispatchMethods.insert(GetNullarySelector("length"));
4146 NonLegacyDispatchMethods.insert(GetNullarySelector("count"));
4147 NonLegacyDispatchMethods.insert(GetNullarySelector("retain"));
4148 NonLegacyDispatchMethods.insert(GetNullarySelector("release"));
4149 NonLegacyDispatchMethods.insert(GetNullarySelector("autorelease"));
4150 NonLegacyDispatchMethods.insert(GetNullarySelector("hash"));
4151
4152 NonLegacyDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4153 NonLegacyDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4154 NonLegacyDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4155 NonLegacyDispatchMethods.insert(GetUnarySelector("objectForKey"));
4156 NonLegacyDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4157 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4158 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqual"));
4159 NonLegacyDispatchMethods.insert(GetUnarySelector("addObject"));
Fariborz Jahanianbe53be42009-05-13 16:19:02 +00004160 // "countByEnumeratingWithState:objects:count"
4161 IdentifierInfo *KeyIdents[] = {
4162 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4163 &CGM.getContext().Idents.get("objects"),
4164 &CGM.getContext().Idents.get("count")
4165 };
4166 NonLegacyDispatchMethods.insert(
4167 CGM.getContext().Selectors.getSelector(3, KeyIdents));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004168 }
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004169 return (NonLegacyDispatchMethods.count(Sel) == 0);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004170}
4171
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004172// Metadata flags
4173enum MetaDataDlags {
4174 CLS = 0x0,
4175 CLS_META = 0x1,
4176 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004177 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004178 CLS_EXCEPTION = 0x20
4179};
4180/// BuildClassRoTInitializer - generate meta-data for:
4181/// struct _class_ro_t {
4182/// uint32_t const flags;
4183/// uint32_t const instanceStart;
4184/// uint32_t const instanceSize;
4185/// uint32_t const reserved; // only when building for 64bit targets
4186/// const uint8_t * const ivarLayout;
4187/// const char *const name;
4188/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004189/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004190/// const struct _ivar_list_t *const ivars;
4191/// const uint8_t * const weakIvarLayout;
4192/// const struct _prop_list_t * const properties;
4193/// }
4194///
4195llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4196 unsigned flags,
4197 unsigned InstanceStart,
4198 unsigned InstanceSize,
4199 const ObjCImplementationDecl *ID) {
4200 std::string ClassName = ID->getNameAsString();
4201 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4202 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4203 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4204 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4205 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004206 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4207 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004208 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004209 // const struct _method_list_t * const baseMethods;
4210 std::vector<llvm::Constant*> Methods;
4211 std::string MethodListName("\01l_OBJC_$_");
4212 if (flags & CLS_META) {
4213 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004214 for (ObjCImplementationDecl::classmeth_iterator
4215 i = ID->classmeth_begin(CGM.getContext()),
4216 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004217 // Class methods should always be defined.
4218 Methods.push_back(GetMethodConstant(*i));
4219 }
4220 } else {
4221 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004222 for (ObjCImplementationDecl::instmeth_iterator
4223 i = ID->instmeth_begin(CGM.getContext()),
4224 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004225 // Instance methods should always be defined.
4226 Methods.push_back(GetMethodConstant(*i));
4227 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004228 for (ObjCImplementationDecl::propimpl_iterator
4229 i = ID->propimpl_begin(CGM.getContext()),
4230 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004231 ObjCPropertyImplDecl *PID = *i;
4232
4233 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4234 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4235
4236 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4237 if (llvm::Constant *C = GetMethodConstant(MD))
4238 Methods.push_back(C);
4239 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4240 if (llvm::Constant *C = GetMethodConstant(MD))
4241 Methods.push_back(C);
4242 }
4243 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004244 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004245 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004246 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004247
4248 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4249 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4250 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4251 + OID->getNameAsString(),
4252 OID->protocol_begin(),
4253 OID->protocol_end());
4254
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004255 if (flags & CLS_META)
4256 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4257 else
4258 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004259 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4260 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004261 if (flags & CLS_META)
4262 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4263 else
4264 Values[ 9] =
4265 EmitPropertyList(
4266 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4267 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004268 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4269 Values);
4270 llvm::GlobalVariable *CLASS_RO_GV =
4271 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4272 llvm::GlobalValue::InternalLinkage,
4273 Init,
4274 (flags & CLS_META) ?
4275 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4276 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4277 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004278 CLASS_RO_GV->setAlignment(
4279 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004280 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004281 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004282
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004283}
4284
4285/// BuildClassMetaData - This routine defines that to-level meta-data
4286/// for the given ClassName for:
4287/// struct _class_t {
4288/// struct _class_t *isa;
4289/// struct _class_t * const superclass;
4290/// void *cache;
4291/// IMP *vtable;
4292/// struct class_ro_t *ro;
4293/// }
4294///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004295llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4296 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004297 llvm::Constant *IsAGV,
4298 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004299 llvm::Constant *ClassRoGV,
4300 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004301 std::vector<llvm::Constant*> Values(5);
4302 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004303 Values[1] = SuperClassGV
4304 ? SuperClassGV
4305 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004306 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4307 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4308 Values[4] = ClassRoGV; // &CLASS_RO_GV
4309 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4310 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004311 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4312 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004313 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004314 GV->setAlignment(
4315 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004316 if (HiddenVisibility)
4317 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004318 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004319}
4320
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004321bool
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00004322CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
4323 return OD->getClassMethod(CGM.getContext(), GetNullarySelector("load")) != 0;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004324}
4325
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004326void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004327 uint32_t &InstanceStart,
4328 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004329 const ASTRecordLayout &RL =
4330 CGM.getContext().getASTObjCImplementationLayout(OID);
4331
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004332 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004333 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004334
4335 // If there are no fields, the start is the same as the end.
4336 if (!RL.getFieldCount())
4337 InstanceStart = InstanceSize;
4338 else
4339 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004340}
4341
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004342void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4343 std::string ClassName = ID->getNameAsString();
4344 if (!ObjCEmptyCacheVar) {
4345 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004346 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004347 false,
4348 llvm::GlobalValue::ExternalLinkage,
4349 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004350 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004351 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004352
4353 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004354 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004355 false,
4356 llvm::GlobalValue::ExternalLinkage,
4357 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004358 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004359 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004360 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004361 assert(ID->getClassInterface() &&
4362 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004363 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004364 uint32_t InstanceStart =
Duncan Sands9408c452009-05-09 07:08:47 +00004365 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004366 uint32_t InstanceSize = InstanceStart;
4367 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004368 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4369 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004370
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004371 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004372
Daniel Dunbar04d40782009-04-14 06:00:08 +00004373 bool classIsHidden =
4374 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004375 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004376 flags |= OBJC2_CLS_HIDDEN;
4377 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004378 // class is root
4379 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004380 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004381 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004382 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004383 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004384 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4385 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4386 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004387 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004388 // work on super class metadata symbol.
4389 std::string SuperClassName =
4390 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004391 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004392 }
4393 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4394 InstanceStart,
4395 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004396 std::string TClassName = ObjCMetaClassName + ClassName;
4397 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004398 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4399 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004400
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004401 // Metadata for the class
4402 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004403 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004404 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004405
Douglas Gregor68584ed2009-06-18 16:11:24 +00004406 if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004407 flags |= CLS_EXCEPTION;
4408
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004409 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004410 flags |= CLS_ROOT;
4411 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004412 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004413 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004414 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004415 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004416 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004417 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004418 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004419 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004420 InstanceStart,
4421 InstanceSize,
4422 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004423
4424 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004425 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004426 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4427 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004428 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004429
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004430 // Determine if this class is also "non-lazy".
4431 if (ImplementationIsNonLazy(ID))
4432 DefinedNonLazyClasses.push_back(ClassMD);
4433
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004434 // Force the definition of the EHType if necessary.
4435 if (flags & CLS_EXCEPTION)
4436 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004437}
4438
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004439/// GenerateProtocolRef - This routine is called to generate code for
4440/// a protocol reference expression; as in:
4441/// @code
4442/// @protocol(Proto1);
4443/// @endcode
4444/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4445/// which will hold address of the protocol meta-data.
4446///
4447llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4448 const ObjCProtocolDecl *PD) {
4449
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004450 // This routine is called for @protocol only. So, we must build definition
4451 // of protocol's meta-data (not a reference to it!)
4452 //
4453 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004454 ObjCTypes.ExternalProtocolPtrTy);
4455
4456 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4457 ProtocolName += PD->getNameAsCString();
4458
4459 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4460 if (PTGV)
4461 return Builder.CreateLoad(PTGV, false, "tmp");
4462 PTGV = new llvm::GlobalVariable(
4463 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004464 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004465 Init,
4466 ProtocolName,
4467 &CGM.getModule());
4468 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4469 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4470 UsedGlobals.push_back(PTGV);
4471 return Builder.CreateLoad(PTGV, false, "tmp");
4472}
4473
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004474/// GenerateCategory - Build metadata for a category implementation.
4475/// struct _category_t {
4476/// const char * const name;
4477/// struct _class_t *const cls;
4478/// const struct _method_list_t * const instance_methods;
4479/// const struct _method_list_t * const class_methods;
4480/// const struct _protocol_list_t * const protocols;
4481/// const struct _prop_list_t * const properties;
4482/// }
4483///
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004484void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004485 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004486 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4487 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004488 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004489 std::string ExtClassName(getClassSymbolPrefix() +
4490 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004491
4492 std::vector<llvm::Constant*> Values(6);
4493 Values[0] = GetClassName(OCD->getIdentifier());
4494 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004495 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004496 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004497 std::vector<llvm::Constant*> Methods;
4498 std::string MethodListName(Prefix);
4499 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4500 "_$_" + OCD->getNameAsString();
4501
Douglas Gregor653f1b12009-04-23 01:02:12 +00004502 for (ObjCCategoryImplDecl::instmeth_iterator
4503 i = OCD->instmeth_begin(CGM.getContext()),
4504 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004505 // Instance methods should always be defined.
4506 Methods.push_back(GetMethodConstant(*i));
4507 }
4508
4509 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004510 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004511 Methods);
4512
4513 MethodListName = Prefix;
4514 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4515 OCD->getNameAsString();
4516 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004517 for (ObjCCategoryImplDecl::classmeth_iterator
4518 i = OCD->classmeth_begin(CGM.getContext()),
4519 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004520 // Class methods should always be defined.
4521 Methods.push_back(GetMethodConstant(*i));
4522 }
4523
4524 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004525 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004526 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004527 const ObjCCategoryDecl *Category =
4528 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004529 if (Category) {
4530 std::string ExtName(Interface->getNameAsString() + "_$_" +
4531 OCD->getNameAsString());
4532 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4533 + Interface->getNameAsString() + "_$_"
4534 + Category->getNameAsString(),
4535 Category->protocol_begin(),
4536 Category->protocol_end());
4537 Values[5] =
4538 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4539 OCD, Category, ObjCTypes);
4540 }
4541 else {
4542 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4543 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4544 }
4545
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004546 llvm::Constant *Init =
4547 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4548 Values);
4549 llvm::GlobalVariable *GCATV
4550 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4551 false,
4552 llvm::GlobalValue::InternalLinkage,
4553 Init,
4554 ExtCatName,
4555 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004556 GCATV->setAlignment(
4557 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004558 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004559 UsedGlobals.push_back(GCATV);
4560 DefinedCategories.push_back(GCATV);
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004561
4562 // Determine if this category is also "non-lazy".
4563 if (ImplementationIsNonLazy(OCD))
4564 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004565}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004566
4567/// GetMethodConstant - Return a struct objc_method constant for the
4568/// given method if it has been defined. The result is null if the
4569/// method has not been defined. The return value has type MethodPtrTy.
4570llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4571 const ObjCMethodDecl *MD) {
4572 // FIXME: Use DenseMap::lookup
4573 llvm::Function *Fn = MethodDefinitions[MD];
4574 if (!Fn)
4575 return 0;
4576
4577 std::vector<llvm::Constant*> Method(3);
4578 Method[0] =
4579 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4580 ObjCTypes.SelectorPtrTy);
4581 Method[1] = GetMethodVarType(MD);
4582 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4583 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4584}
4585
4586/// EmitMethodList - Build meta-data for method declarations
4587/// struct _method_list_t {
4588/// uint32_t entsize; // sizeof(struct _objc_method)
4589/// uint32_t method_count;
4590/// struct _objc_method method_list[method_count];
4591/// }
4592///
4593llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4594 const std::string &Name,
4595 const char *Section,
4596 const ConstantVector &Methods) {
4597 // Return null for empty list.
4598 if (Methods.empty())
4599 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4600
4601 std::vector<llvm::Constant*> Values(3);
4602 // sizeof(struct _objc_method)
Duncan Sands9408c452009-05-09 07:08:47 +00004603 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004604 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4605 // method_count
4606 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4607 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4608 Methods.size());
4609 Values[2] = llvm::ConstantArray::get(AT, Methods);
4610 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4611
4612 llvm::GlobalVariable *GV =
4613 new llvm::GlobalVariable(Init->getType(), false,
4614 llvm::GlobalValue::InternalLinkage,
4615 Init,
4616 Name,
4617 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004618 GV->setAlignment(
4619 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004620 GV->setSection(Section);
4621 UsedGlobals.push_back(GV);
4622 return llvm::ConstantExpr::getBitCast(GV,
4623 ObjCTypes.MethodListnfABIPtrTy);
4624}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004625
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004626/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4627/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004628llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004629 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004630 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004631 // FIXME: We shouldn't need to do this lookup.
4632 unsigned Index;
4633 const ObjCInterfaceDecl *Container =
4634 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4635 assert(Container && "Unable to find ivar container!");
4636 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004637 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004638 llvm::GlobalVariable *IvarOffsetGV =
4639 CGM.getModule().getGlobalVariable(Name);
4640 if (!IvarOffsetGV)
4641 IvarOffsetGV =
4642 new llvm::GlobalVariable(ObjCTypes.LongTy,
4643 false,
4644 llvm::GlobalValue::ExternalLinkage,
4645 0,
4646 Name,
4647 &CGM.getModule());
4648 return IvarOffsetGV;
4649}
4650
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004651llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004652 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004653 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004654 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004655 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4656 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4657 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004658 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004659 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004660
Mike Stumpf5408fe2009-05-16 07:57:57 +00004661 // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
4662 // well (i.e., in ObjCIvarOffsetVariable).
Daniel Dunbar737c5022009-04-19 00:44:02 +00004663 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4664 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4665 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004666 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004667 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004668 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004669 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004670 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004671}
4672
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004673/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004674/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004675/// IvarListnfABIPtrTy.
4676/// struct _ivar_t {
4677/// unsigned long int *offset; // pointer to ivar offset location
4678/// char *name;
4679/// char *type;
4680/// uint32_t alignment;
4681/// uint32_t size;
4682/// }
4683/// struct _ivar_list_t {
4684/// uint32 entsize; // sizeof(struct _ivar_t)
4685/// uint32 count;
4686/// struct _iver_t list[count];
4687/// }
4688///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004689
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004690llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4691 const ObjCImplementationDecl *ID) {
4692
4693 std::vector<llvm::Constant*> Ivars, Ivar(5);
4694
4695 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4696 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4697
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004698 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004699
Daniel Dunbar91636d62009-04-20 00:33:43 +00004700 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004701 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004702 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004703
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004704 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4705 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004706 // Ignore unnamed bit-fields.
4707 if (!IVD->getDeclName())
4708 continue;
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004709 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004710 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004711 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4712 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004713 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004714 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sands9408c452009-05-09 07:08:47 +00004715 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004716 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004717 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004718 Align = llvm::Log2_32(Align);
4719 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004720 // NOTE. Size of a bitfield does not match gcc's, because of the
4721 // way bitfields are treated special in each. But I am told that
4722 // 'size' for bitfield ivars is ignored by the runtime so it does
4723 // not matter. If it matters, there is enough info to get the
4724 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004725 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4726 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4727 }
4728 // Return null for empty list.
4729 if (Ivars.empty())
4730 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4731 std::vector<llvm::Constant*> Values(3);
Duncan Sands9408c452009-05-09 07:08:47 +00004732 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004733 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4734 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4735 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4736 Ivars.size());
4737 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4738 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4739 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4740 llvm::GlobalVariable *GV =
4741 new llvm::GlobalVariable(Init->getType(), false,
4742 llvm::GlobalValue::InternalLinkage,
4743 Init,
4744 Prefix + OID->getNameAsString(),
4745 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004746 GV->setAlignment(
4747 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004748 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004749
4750 UsedGlobals.push_back(GV);
4751 return llvm::ConstantExpr::getBitCast(GV,
4752 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753}
4754
4755llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4756 const ObjCProtocolDecl *PD) {
4757 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4758
4759 if (!Entry) {
4760 // We use the initializer as a marker of whether this is a forward
4761 // reference or not. At module finalization we add the empty
4762 // contents for protocols which were referenced but never defined.
4763 Entry =
4764 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4765 llvm::GlobalValue::ExternalLinkage,
4766 0,
4767 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4768 &CGM.getModule());
4769 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4770 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004771 }
4772
4773 return Entry;
4774}
4775
4776/// GetOrEmitProtocol - Generate the protocol meta-data:
4777/// @code
4778/// struct _protocol_t {
4779/// id isa; // NULL
4780/// const char * const protocol_name;
4781/// const struct _protocol_list_t * protocol_list; // super protocols
4782/// const struct method_list_t * const instance_methods;
4783/// const struct method_list_t * const class_methods;
4784/// const struct method_list_t *optionalInstanceMethods;
4785/// const struct method_list_t *optionalClassMethods;
4786/// const struct _prop_list_t * properties;
4787/// const uint32_t size; // sizeof(struct _protocol_t)
4788/// const uint32_t flags; // = 0
4789/// }
4790/// @endcode
4791///
4792
4793llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4794 const ObjCProtocolDecl *PD) {
4795 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4796
4797 // Early exit if a defining object has already been generated.
4798 if (Entry && Entry->hasInitializer())
4799 return Entry;
4800
4801 const char *ProtocolName = PD->getNameAsCString();
4802
4803 // Construct method lists.
4804 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4805 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004806 for (ObjCProtocolDecl::instmeth_iterator
4807 i = PD->instmeth_begin(CGM.getContext()),
4808 e = PD->instmeth_end(CGM.getContext());
4809 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004811 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004812 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4813 OptInstanceMethods.push_back(C);
4814 } else {
4815 InstanceMethods.push_back(C);
4816 }
4817 }
4818
Douglas Gregor6ab35242009-04-09 21:40:53 +00004819 for (ObjCProtocolDecl::classmeth_iterator
4820 i = PD->classmeth_begin(CGM.getContext()),
4821 e = PD->classmeth_end(CGM.getContext());
4822 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004823 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004824 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004825 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4826 OptClassMethods.push_back(C);
4827 } else {
4828 ClassMethods.push_back(C);
4829 }
4830 }
4831
4832 std::vector<llvm::Constant*> Values(10);
4833 // isa is NULL
4834 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4835 Values[1] = GetClassName(PD->getIdentifier());
4836 Values[2] = EmitProtocolList(
4837 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4838 PD->protocol_begin(),
4839 PD->protocol_end());
4840
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004841 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004842 + PD->getNameAsString(),
4843 "__DATA, __objc_const",
4844 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004845 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004846 + PD->getNameAsString(),
4847 "__DATA, __objc_const",
4848 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004849 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004850 + PD->getNameAsString(),
4851 "__DATA, __objc_const",
4852 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004853 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004854 + PD->getNameAsString(),
4855 "__DATA, __objc_const",
4856 OptClassMethods);
4857 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4858 0, PD, ObjCTypes);
4859 uint32_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00004860 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004861 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4862 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4863 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4864 Values);
4865
4866 if (Entry) {
4867 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004868 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004869 Entry->setInitializer(Init);
4870 } else {
4871 Entry =
4872 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004873 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004874 Init,
4875 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4876 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004877 Entry->setAlignment(
4878 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004879 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004880 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004881 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4882
4883 // Use this protocol meta-data to build protocol list table in section
4884 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004885 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004886 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004887 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004888 Entry,
4889 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4890 +ProtocolName,
4891 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004892 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004893 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004894 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004895 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4896 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004897 return Entry;
4898}
4899
4900/// EmitProtocolList - Generate protocol list meta-data:
4901/// @code
4902/// struct _protocol_list_t {
4903/// long protocol_count; // Note, this is 32/64 bit
4904/// struct _protocol_t[protocol_count];
4905/// }
4906/// @endcode
4907///
4908llvm::Constant *
4909CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4910 ObjCProtocolDecl::protocol_iterator begin,
4911 ObjCProtocolDecl::protocol_iterator end) {
4912 std::vector<llvm::Constant*> ProtocolRefs;
4913
Fariborz Jahanianda320092009-01-29 19:24:30 +00004914 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004915 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004916 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4917
Daniel Dunbar948e2582009-02-15 07:36:20 +00004918 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004919 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4920 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004921 return llvm::ConstantExpr::getBitCast(GV,
4922 ObjCTypes.ProtocolListnfABIPtrTy);
4923
4924 for (; begin != end; ++begin)
4925 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4926
Fariborz Jahanianda320092009-01-29 19:24:30 +00004927 // This list is null terminated.
4928 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004929 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004930
4931 std::vector<llvm::Constant*> Values(2);
4932 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4933 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004934 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004935 ProtocolRefs.size()),
4936 ProtocolRefs);
4937
4938 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4939 GV = new llvm::GlobalVariable(Init->getType(), false,
4940 llvm::GlobalValue::InternalLinkage,
4941 Init,
4942 Name,
4943 &CGM.getModule());
4944 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004945 GV->setAlignment(
4946 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004947 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004948 return llvm::ConstantExpr::getBitCast(GV,
4949 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004950}
4951
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004952/// GetMethodDescriptionConstant - This routine build following meta-data:
4953/// struct _objc_method {
4954/// SEL _cmd;
4955/// char *method_type;
4956/// char *_imp;
4957/// }
4958
4959llvm::Constant *
4960CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4961 std::vector<llvm::Constant*> Desc(3);
4962 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4963 ObjCTypes.SelectorPtrTy);
4964 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004965 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004966 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4967 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4968}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004969
4970/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4971/// This code gen. amounts to generating code for:
4972/// @code
4973/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4974/// @encode
4975///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004976LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004977 CodeGen::CodeGenFunction &CGF,
4978 QualType ObjectTy,
4979 llvm::Value *BaseValue,
4980 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004981 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004982 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004983 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4984 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004985}
4986
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004987llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4988 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004989 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004990 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004991 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4992 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004993}
4994
Fariborz Jahanian46551122009-02-04 00:22:57 +00004995CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4996 CodeGen::CodeGenFunction &CGF,
4997 QualType ResultType,
4998 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004999 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00005000 QualType Arg0Ty,
5001 bool IsSuper,
5002 const CallArgList &CallArgs) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00005003 // FIXME. Even though IsSuper is passes. This function doese not handle calls
5004 // to 'super' receivers.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005005 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005006 llvm::Value *Arg0 = Receiver;
5007 if (!IsSuper)
5008 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005009
5010 // Find the message function name.
Mike Stumpf5408fe2009-05-16 07:57:57 +00005011 // FIXME. This is too much work to get the ABI-specific result type needed to
5012 // find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005013 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
5014 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005015 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016 std::string Name("\01l_");
5017 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005018#if 0
5019 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005020 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005021 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005022 // FIXME. Is there a better way of getting these names.
5023 // They are available in RuntimeFunctions vector pair.
5024 Name += "objc_msgSendId_stret_fixup";
5025 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005026 else
5027#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005028 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005029 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005030 Name += "objc_msgSendSuper2_stret_fixup";
5031 }
5032 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005033 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005034 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005035 Name += "objc_msgSend_stret_fixup";
5036 }
5037 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005038 else if (!IsSuper && ResultType->isFloatingType()) {
5039 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
5040 BuiltinType::Kind k = BT->getKind();
5041 if (k == BuiltinType::LongDouble) {
5042 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5043 Name += "objc_msgSend_fpret_fixup";
5044 }
5045 else {
5046 Fn = ObjCTypes.getMessageSendFixupFn();
5047 Name += "objc_msgSend_fixup";
5048 }
5049 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005050 }
5051 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005052#if 0
5053// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005054 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005055 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005056 Name += "objc_msgSendId_fixup";
5057 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005058 else
5059#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005060 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005061 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005062 Name += "objc_msgSendSuper2_fixup";
5063 }
5064 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005065 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005066 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005067 Name += "objc_msgSend_fixup";
5068 }
5069 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005070 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005071 Name += '_';
5072 std::string SelName(Sel.getAsString());
5073 // Replace all ':' in selector name with '_' ouch!
5074 for(unsigned i = 0; i < SelName.size(); i++)
5075 if (SelName[i] == ':')
5076 SelName[i] = '_';
5077 Name += SelName;
5078 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5079 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005080 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005081 std::vector<llvm::Constant*> Values(2);
5082 Values[0] = Fn;
5083 Values[1] = GetMethodVarName(Sel);
5084 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5085 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005086 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005087 Init,
5088 Name,
5089 &CGM.getModule());
5090 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005091 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005092 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005093 }
5094 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005095
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005096 CallArgList ActualArgs;
5097 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5098 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5099 ObjCTypes.MessageRefCPtrTy));
5100 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005101 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5102 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5103 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005104 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005105 Callee = CGF.Builder.CreateBitCast(Callee,
5106 llvm::PointerType::getUnqual(FTy));
5107 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005108}
5109
5110/// Generate code for a message send expression in the nonfragile abi.
5111CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5112 CodeGen::CodeGenFunction &CGF,
5113 QualType ResultType,
5114 Selector Sel,
5115 llvm::Value *Receiver,
5116 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00005117 const CallArgList &CallArgs,
5118 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005119 return LegacyDispatchedSelector(Sel)
5120 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5121 Receiver, CGF.getContext().getObjCIdType(),
5122 false, CallArgs, ObjCTypes)
5123 : EmitMessageSend(CGF, ResultType, Sel,
5124 Receiver, CGF.getContext().getObjCIdType(),
5125 false, CallArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005126}
5127
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005128llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005129CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005130 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5131
Daniel Dunbardfff2302009-03-02 05:18:14 +00005132 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005133 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5134 llvm::GlobalValue::ExternalLinkage,
5135 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005136 }
5137
5138 return GV;
5139}
5140
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005141llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005142 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005143 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5144
5145 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005146 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005147 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005148 Entry =
5149 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5150 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005151 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005152 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005153 &CGM.getModule());
5154 Entry->setAlignment(
5155 CGM.getTargetData().getPrefTypeAlignment(
5156 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005157 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5158 UsedGlobals.push_back(Entry);
5159 }
5160
5161 return Builder.CreateLoad(Entry, false, "tmp");
5162}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005163
Daniel Dunbar11394522009-04-18 08:51:00 +00005164llvm::Value *
5165CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5166 const ObjCInterfaceDecl *ID) {
5167 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5168
5169 if (!Entry) {
5170 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5171 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5172 Entry =
5173 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5174 llvm::GlobalValue::InternalLinkage,
5175 ClassGV,
5176 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5177 &CGM.getModule());
5178 Entry->setAlignment(
5179 CGM.getTargetData().getPrefTypeAlignment(
5180 ObjCTypes.ClassnfABIPtrTy));
5181 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005182 UsedGlobals.push_back(Entry);
5183 }
5184
5185 return Builder.CreateLoad(Entry, false, "tmp");
5186}
5187
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005188/// EmitMetaClassRef - Return a Value * of the address of _class_t
5189/// meta-data
5190///
5191llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5192 const ObjCInterfaceDecl *ID) {
5193 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5194 if (Entry)
5195 return Builder.CreateLoad(Entry, false, "tmp");
5196
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005197 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005198 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005199 Entry =
5200 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5201 llvm::GlobalValue::InternalLinkage,
5202 MetaClassGV,
5203 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5204 &CGM.getModule());
5205 Entry->setAlignment(
5206 CGM.getTargetData().getPrefTypeAlignment(
5207 ObjCTypes.ClassnfABIPtrTy));
5208
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005209 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005210 UsedGlobals.push_back(Entry);
5211
5212 return Builder.CreateLoad(Entry, false, "tmp");
5213}
5214
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005215/// GetClass - Return a reference to the class for the given interface
5216/// decl.
5217llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5218 const ObjCInterfaceDecl *ID) {
5219 return EmitClassRef(Builder, ID);
5220}
5221
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005222/// Generates a message send where the super is the receiver. This is
5223/// a message send to self with special delivery semantics indicating
5224/// which class's method should be called.
5225CodeGen::RValue
5226CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5227 QualType ResultType,
5228 Selector Sel,
5229 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005230 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005231 llvm::Value *Receiver,
5232 bool IsClassMessage,
5233 const CodeGen::CallArgList &CallArgs) {
5234 // ...
5235 // Create and init a super structure; this is a (receiver, class)
5236 // pair we will pass to objc_msgSendSuper.
5237 llvm::Value *ObjCSuper =
5238 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5239
5240 llvm::Value *ReceiverAsObject =
5241 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5242 CGF.Builder.CreateStore(ReceiverAsObject,
5243 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5244
5245 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005246 llvm::Value *Target;
5247 if (IsClassMessage) {
5248 if (isCategoryImpl) {
5249 // Message sent to "super' in a class method defined in
5250 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005251 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005252 Target = CGF.Builder.CreateStructGEP(Target, 0);
5253 Target = CGF.Builder.CreateLoad(Target);
5254 }
5255 else
5256 Target = EmitMetaClassRef(CGF.Builder, Class);
5257 }
5258 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005259 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005260
Mike Stumpf5408fe2009-05-16 07:57:57 +00005261 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
5262 // ObjCTypes types.
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005263 const llvm::Type *ClassTy =
5264 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5265 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5266 CGF.Builder.CreateStore(Target,
5267 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5268
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005269 return (LegacyDispatchedSelector(Sel))
5270 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5271 ObjCSuper, ObjCTypes.SuperPtrCTy,
5272 true, CallArgs,
5273 ObjCTypes)
5274 : EmitMessageSend(CGF, ResultType, Sel,
5275 ObjCSuper, ObjCTypes.SuperPtrCTy,
5276 true, CallArgs);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005277}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005278
5279llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5280 Selector Sel) {
5281 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5282
5283 if (!Entry) {
5284 llvm::Constant *Casted =
5285 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5286 ObjCTypes.SelectorPtrTy);
5287 Entry =
5288 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5289 llvm::GlobalValue::InternalLinkage,
5290 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5291 &CGM.getModule());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005292 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005293 UsedGlobals.push_back(Entry);
5294 }
5295
5296 return Builder.CreateLoad(Entry, false, "tmp");
5297}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005298/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5299/// objc_assign_ivar (id src, id *dst)
5300///
5301void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5302 llvm::Value *src, llvm::Value *dst)
5303{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005304 const llvm::Type * SrcTy = src->getType();
5305 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005306 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005307 assert(Size <= 8 && "does not support size > 8");
5308 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5309 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005310 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5311 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005312 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5313 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005314 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005315 src, dst, "assignivar");
5316 return;
5317}
5318
5319/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5320/// objc_assign_strongCast (id src, id *dst)
5321///
5322void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5323 CodeGen::CodeGenFunction &CGF,
5324 llvm::Value *src, llvm::Value *dst)
5325{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005326 const llvm::Type * SrcTy = src->getType();
5327 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005328 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005329 assert(Size <= 8 && "does not support size > 8");
5330 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5331 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005332 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5333 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005334 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5335 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005336 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005337 src, dst, "weakassign");
5338 return;
5339}
5340
5341/// EmitObjCWeakRead - Code gen for loading value of a __weak
5342/// object: objc_read_weak (id *src)
5343///
5344llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5345 CodeGen::CodeGenFunction &CGF,
5346 llvm::Value *AddrWeakObj)
5347{
Eli Friedman8339b352009-03-07 03:57:15 +00005348 const llvm::Type* DestTy =
5349 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005350 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005351 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005352 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005353 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005354 return read_weak;
5355}
5356
5357/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5358/// objc_assign_weak (id src, id *dst)
5359///
5360void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5361 llvm::Value *src, llvm::Value *dst)
5362{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005363 const llvm::Type * SrcTy = src->getType();
5364 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005365 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005366 assert(Size <= 8 && "does not support size > 8");
5367 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5368 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005369 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5370 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005371 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5372 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005373 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005374 src, dst, "weakassign");
5375 return;
5376}
5377
5378/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5379/// objc_assign_global (id src, id *dst)
5380///
5381void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5382 llvm::Value *src, llvm::Value *dst)
5383{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005384 const llvm::Type * SrcTy = src->getType();
5385 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005386 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005387 assert(Size <= 8 && "does not support size > 8");
5388 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5389 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005390 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5391 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005392 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5393 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005394 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005395 src, dst, "globalassign");
5396 return;
5397}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005398
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005399void
5400CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5401 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005402 bool isTry = isa<ObjCAtTryStmt>(S);
5403 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5404 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005405 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005406 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005407 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005408 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5409
5410 // For @synchronized, call objc_sync_enter(sync.expr). The
5411 // evaluation of the expression must occur before we enter the
5412 // @synchronized. We can safely avoid a temp here because jumps into
5413 // @synchronized are illegal & this will dominate uses.
5414 llvm::Value *SyncArg = 0;
5415 if (!isTry) {
5416 SyncArg =
5417 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5418 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005419 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005420 }
5421
5422 // Push an EH context entry, used for handling rethrows and jumps
5423 // through finally.
5424 CGF.PushCleanupBlock(FinallyBlock);
5425
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005426 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005427
5428 CGF.EmitBlock(TryBlock);
5429 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5430 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5431 CGF.EmitBranchThroughCleanup(FinallyEnd);
5432
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005433 // Emit the exception handler.
5434
5435 CGF.EmitBlock(TryHandler);
5436
5437 llvm::Value *llvm_eh_exception =
5438 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5439 llvm::Value *llvm_eh_selector_i64 =
5440 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5441 llvm::Value *llvm_eh_typeid_for_i64 =
5442 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5443 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5444 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5445
5446 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5447 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005448 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005449
5450 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005451 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005452 bool HasCatchAll = false;
5453 if (isTry) {
5454 if (const ObjCAtCatchStmt* CatchStmt =
5455 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5456 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005457 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005458 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005459
5460 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005461 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005462 // Use i8* null here to signal this is a catch all, not a cleanup.
5463 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5464 SelectorArgs.push_back(Null);
5465 HasCatchAll = true;
5466 break;
5467 }
5468
Daniel Dunbarede8de92009-03-06 00:01:21 +00005469 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5470 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005471 llvm::Value *IDEHType =
5472 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5473 if (!IDEHType)
5474 IDEHType =
5475 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5476 llvm::GlobalValue::ExternalLinkage,
5477 0, "OBJC_EHTYPE_id", &CGM.getModule());
5478 SelectorArgs.push_back(IDEHType);
5479 HasCatchAll = true;
5480 break;
5481 }
5482
5483 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005484 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005485 assert(PT && "Invalid @catch type.");
5486 const ObjCInterfaceType *IT =
5487 PT->getPointeeType()->getAsObjCInterfaceType();
5488 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005489 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005490 SelectorArgs.push_back(EHType);
5491 }
5492 }
5493 }
5494
5495 // We use a cleanup unless there was already a catch all.
5496 if (!HasCatchAll) {
5497 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005498 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005499 }
5500
5501 llvm::Value *Selector =
5502 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5503 SelectorArgs.begin(), SelectorArgs.end(),
5504 "selector");
5505 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005506 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005507 const Stmt *CatchBody = Handlers[i].second;
5508
5509 llvm::BasicBlock *Next = 0;
5510
5511 // The last handler always matches.
5512 if (i + 1 != e) {
5513 assert(CatchParam && "Only last handler can be a catch all.");
5514
5515 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5516 Next = CGF.createBasicBlock("catch.next");
5517 llvm::Value *Id =
5518 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5519 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5520 ObjCTypes.Int8PtrTy));
5521 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5522 Match, Next);
5523
5524 CGF.EmitBlock(Match);
5525 }
5526
5527 if (CatchBody) {
5528 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5529 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5530
5531 // Cleanups must call objc_end_catch.
5532 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00005533 // FIXME: It seems incorrect for objc_begin_catch to be inside this
5534 // context, but this matches gcc.
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005535 CGF.PushCleanupBlock(MatchEnd);
5536 CGF.setInvokeDest(MatchHandler);
5537
5538 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005539 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005540
5541 // Bind the catch parameter if it exists.
5542 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005543 ExcObject =
5544 CGF.Builder.CreateBitCast(ExcObject,
5545 CGF.ConvertType(CatchParam->getType()));
5546 // CatchParam is a ParmVarDecl because of the grammar
5547 // construction used to handle this, but for codegen purposes
5548 // we treat this as a local decl.
5549 CGF.EmitLocalBlockVarDecl(*CatchParam);
5550 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005551 }
5552
5553 CGF.ObjCEHValueStack.push_back(ExcObject);
5554 CGF.EmitStmt(CatchBody);
5555 CGF.ObjCEHValueStack.pop_back();
5556
5557 CGF.EmitBranchThroughCleanup(FinallyEnd);
5558
5559 CGF.EmitBlock(MatchHandler);
5560
5561 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5562 // We are required to emit this call to satisfy LLVM, even
5563 // though we don't use the result.
5564 llvm::SmallVector<llvm::Value*, 8> Args;
5565 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005566 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005567 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5568 0));
5569 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5570 CGF.Builder.CreateStore(Exc, RethrowPtr);
5571 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5572
5573 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5574
5575 CGF.EmitBlock(MatchEnd);
5576
5577 // Unfortunately, we also have to generate another EH frame here
5578 // in case this throws.
5579 llvm::BasicBlock *MatchEndHandler =
5580 CGF.createBasicBlock("match.end.handler");
5581 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005582 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005583 Cont, MatchEndHandler,
5584 Args.begin(), Args.begin());
5585
5586 CGF.EmitBlock(Cont);
5587 if (Info.SwitchBlock)
5588 CGF.EmitBlock(Info.SwitchBlock);
5589 if (Info.EndBlock)
5590 CGF.EmitBlock(Info.EndBlock);
5591
5592 CGF.EmitBlock(MatchEndHandler);
5593 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5594 // We are required to emit this call to satisfy LLVM, even
5595 // though we don't use the result.
5596 Args.clear();
5597 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005598 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005599 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5600 0));
5601 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5602 CGF.Builder.CreateStore(Exc, RethrowPtr);
5603 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5604
5605 if (Next)
5606 CGF.EmitBlock(Next);
5607 } else {
5608 assert(!Next && "catchup should be last handler.");
5609
5610 CGF.Builder.CreateStore(Exc, RethrowPtr);
5611 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5612 }
5613 }
5614
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005615 // Pop the cleanup entry, the @finally is outside this cleanup
5616 // scope.
5617 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5618 CGF.setInvokeDest(PrevLandingPad);
5619
5620 CGF.EmitBlock(FinallyBlock);
5621
5622 if (isTry) {
5623 if (const ObjCAtFinallyStmt* FinallyStmt =
5624 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5625 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5626 } else {
5627 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5628 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005629 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005630 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005631
5632 if (Info.SwitchBlock)
5633 CGF.EmitBlock(Info.SwitchBlock);
5634 if (Info.EndBlock)
5635 CGF.EmitBlock(Info.EndBlock);
5636
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005637 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005638 CGF.EmitBranch(FinallyEnd);
5639
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005640 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005641 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005642 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005643 CGF.Builder.CreateUnreachable();
5644
5645 CGF.EmitBlock(FinallyEnd);
5646}
5647
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005648/// EmitThrowStmt - Generate code for a throw statement.
5649void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5650 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005651 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005652 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005653 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005654 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005655 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5656 "Unexpected rethrow outside @catch block.");
5657 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005658 }
5659
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005660 llvm::Value *ExceptionAsObject =
5661 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5662 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5663 if (InvokeDest) {
5664 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005665 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005666 Cont, InvokeDest,
5667 &ExceptionAsObject, &ExceptionAsObject + 1);
5668 CGF.EmitBlock(Cont);
5669 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005670 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005671 CGF.Builder.CreateUnreachable();
5672
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005673 // Clear the insertion point to indicate we are in unreachable code.
5674 CGF.Builder.ClearInsertionPoint();
5675}
Daniel Dunbare588b992009-03-01 04:46:24 +00005676
5677llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005678CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5679 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005680 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005681
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005682 // If we don't need a definition, return the entry if found or check
5683 // if we use an external reference.
5684 if (!ForDefinition) {
5685 if (Entry)
5686 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005687
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005688 // If this type (or a super class) has the __objc_exception__
5689 // attribute, emit an external reference.
Douglas Gregor68584ed2009-06-18 16:11:24 +00005690 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005691 return Entry =
5692 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5693 llvm::GlobalValue::ExternalLinkage,
5694 0,
5695 (std::string("OBJC_EHTYPE_$_") +
5696 ID->getIdentifier()->getName()),
5697 &CGM.getModule());
5698 }
5699
5700 // Otherwise we need to either make a new entry or fill in the
5701 // initializer.
5702 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005703 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005704 std::string VTableName = "objc_ehtype_vtable";
5705 llvm::GlobalVariable *VTableGV =
5706 CGM.getModule().getGlobalVariable(VTableName);
5707 if (!VTableGV)
5708 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5709 llvm::GlobalValue::ExternalLinkage,
5710 0, VTableName, &CGM.getModule());
5711
5712 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5713
5714 std::vector<llvm::Constant*> Values(3);
5715 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5716 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005717 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005718 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5719
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005720 if (Entry) {
5721 Entry->setInitializer(Init);
5722 } else {
5723 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5724 llvm::GlobalValue::WeakAnyLinkage,
5725 Init,
5726 (std::string("OBJC_EHTYPE_$_") +
5727 ID->getIdentifier()->getName()),
5728 &CGM.getModule());
5729 }
5730
Daniel Dunbar04d40782009-04-14 06:00:08 +00005731 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005732 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005733 Entry->setAlignment(8);
5734
5735 if (ForDefinition) {
5736 Entry->setSection("__DATA,__objc_const");
5737 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5738 } else {
5739 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5740 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005741
5742 return Entry;
5743}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005744
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005745/* *** */
5746
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005747CodeGen::CGObjCRuntime *
5748CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005749 return new CGObjCMac(CGM);
5750}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005751
5752CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005753CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005754 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005755}